pystepmap-core 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pystepmap/__init__.py +3 -0
- pystepmap/analyze.py +68 -0
- pystepmap/build.py +1101 -0
- pystepmap/cli.py +427 -0
- pystepmap/config.py +144 -0
- pystepmap/diff.py +733 -0
- pystepmap/engineid.py +73 -0
- pystepmap/entries.py +196 -0
- pystepmap/external.py +280 -0
- pystepmap/index.py +529 -0
- pystepmap/kit.py +431 -0
- pystepmap/kit_assets/SKILL.md +455 -0
- pystepmap/kit_assets/check_edited_file.py +160 -0
- pystepmap/kit_assets/dbos.md +91 -0
- pystepmap/kit_assets/openspec-flow-rules.yaml +19 -0
- pystepmap/kit_assets/pre-commit +91 -0
- pystepmap/kit_assets/requirements.md +52 -0
- pystepmap/kit_assets/routes.md +55 -0
- pystepmap/kit_assets/transfer_workflow.py +256 -0
- pystepmap/lines.py +164 -0
- pystepmap/lint.py +348 -0
- pystepmap/model.py +261 -0
- pystepmap/outline.py +863 -0
- pystepmap/progress.py +174 -0
- pystepmap/query.py +386 -0
- pystepmap/requirements.py +765 -0
- pystepmap/resolve.py +605 -0
- pystepmap/rules.py +538 -0
- pystepmap/runpath.py +585 -0
- pystepmap/selfcheck.py +112 -0
- pystepmap/stale.py +49 -0
- pystepmap/titles.py +65 -0
- pystepmap/trace.py +756 -0
- pystepmap/verify.py +968 -0
- pystepmap_core-0.1.0.dist-info/METADATA +31 -0
- pystepmap_core-0.1.0.dist-info/RECORD +39 -0
- pystepmap_core-0.1.0.dist-info/WHEEL +4 -0
- pystepmap_core-0.1.0.dist-info/entry_points.txt +2 -0
- pystepmap_core-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
"""业务需求:先设计流程,实现后对照(设计见 docs/superpowers/specs/2026-11-18-requirements-design.md)。
|
|
2
|
+
|
|
3
|
+
需求存在被分析的项目里:<项目>/.pystepmap/requirements/<编号>-<短标题>.md,一条一个文件:
|
|
4
|
+
|
|
5
|
+
# 大额转账要人工复核
|
|
6
|
+
|
|
7
|
+
- 编号:R003
|
|
8
|
+
- 状态:已确认
|
|
9
|
+
- 功能线:账户转账
|
|
10
|
+
|
|
11
|
+
## 说明
|
|
12
|
+
|
|
13
|
+
单笔超过 5 万的转账先交人工复核。
|
|
14
|
+
|
|
15
|
+
## 设计的流程
|
|
16
|
+
|
|
17
|
+
```flow
|
|
18
|
+
步骤:参数校验
|
|
19
|
+
判断:需要人工复核?
|
|
20
|
+
是:
|
|
21
|
+
步骤:提交人工复核
|
|
22
|
+
结局(跳过):已提交人工复核
|
|
23
|
+
步骤:执行转账
|
|
24
|
+
结局(成功):转账完成
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
流程的写法(缩进文本,行首关键字,冒号、括号全角半角都认,缩进用空格):
|
|
28
|
+
- `步骤:标题`,下面可以缩进一个 `失败时:`,带一段这一步出错(抛出异常被接住)之后的内容;`判断:标题`,下面缩进的
|
|
29
|
+
`是:` / `否:` 各带一段更深一层的内容;`循环:标题`,下面缩进的是循环体;`结局(成功 | 跳过 | 失败):标题`。
|
|
30
|
+
- 一段内容从上到下依次执行;判断的分支里没有走到结局的,走完回到判断后面的那一行;没写的分支就是直接往下走。
|
|
31
|
+
- 标题就是图上节点的标题。不写变量、参数、代码。
|
|
32
|
+
|
|
33
|
+
对照(compare):设计的节点和实现的图按"类型 + 标题"配对(标题去掉空白和句末标点,问号不分全角半角),报告:
|
|
34
|
+
- missing:设计里有、实现里没有的步骤 / 判断 / 循环 / 结局(在这条功能线的根函数和它派发的任务里都找不到);
|
|
35
|
+
- extra:功能线的根函数里有、设计里没有的(只看带中文标题的步骤 / 判断 / 循环 / 结局;"执行到函数末尾"、
|
|
36
|
+
"未捕获异常退出"这类隐含结局和捕获节点不算);
|
|
37
|
+
- kind:结局的分类不一样(设计是失败,实现是跳过);
|
|
38
|
+
- order:走向不一致——(几条路都走不通、而且拿掉同一个节点之后都走得通时,只报这一个节点"位置和设计不一样",
|
|
39
|
+
见 _misplaced)设计里到某个结局的一条路上依次经过的节点(判断带着走的是"是"还是"否"),在根函数里到
|
|
40
|
+
同一个结局的任何一条路上都不是按这个顺序、这些分支出现的。路上配不上的步骤 / 循环(已经在 missing 里)先拿掉再比;
|
|
41
|
+
路上有配不上的判断时这条路不比(实现里没有它,两个分支分不开),在 notes 里说明。
|
|
42
|
+
功能线找不到时所有设计的节点都算 missing,并说明。局限:靠标题配对,标题改了就配不上;循环只比有没有、不比次数;
|
|
43
|
+
走向只在根函数里比(派发出去的任务里的顺序不比)。
|
|
44
|
+
|
|
45
|
+
项目用 OpenSpec 管需求时不用另写需求文件:OpenSpec 的 Markdown 文件(openspec/changes/<变更>/ 下的;openspec/specs/ 下的;
|
|
46
|
+
已归档的 openspec/changes/archive/<变更>/ 下的也读,编号是 archive/<变更名>,状态"已归档",排在最后——那是当时的设计,
|
|
47
|
+
和现在的代码不一致不算问题)里每个 ```flow 代码块就是一条需求,写法同上,块里第一行写 `功能线:账户转账`。编号是变更名
|
|
48
|
+
(一个变更里有几块时第二块起是 `变更名#2`;specs 下的是 `specs/<能力名>`),标题是变更名加代码块上方最近的标题(同一个小节里放了
|
|
49
|
+
几块时改用各自写的功能线,免得重名)。
|
|
50
|
+
状态不存在文件里(变更的进度由 OpenSpec 管):进行中的变更按"已确认"对照,specs 下的按"已实现"对照。
|
|
51
|
+
|
|
52
|
+
只用标准库;只读项目文件——写文件只有 save_requirement,由调用方(MCP 的保存工具)明确调用,只写
|
|
53
|
+
.pystepmap/requirements/,不写 OpenSpec 的文件。
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
from __future__ import annotations
|
|
57
|
+
|
|
58
|
+
import re
|
|
59
|
+
from collections import deque
|
|
60
|
+
from dataclasses import dataclass, field
|
|
61
|
+
from pathlib import Path
|
|
62
|
+
|
|
63
|
+
from .model import FunctionGraph, ProjectGraph
|
|
64
|
+
|
|
65
|
+
DIR = ".pystepmap/requirements"
|
|
66
|
+
ARCHIVE_DIR = "archive" # openspec/changes/archive/:已归档的变更
|
|
67
|
+
ARCHIVED = "已归档" # 已归档的变更里的流程的状态(不在 STATUSES 里:不能存成这个状态,对照结果也不改它)
|
|
68
|
+
OPENSPEC_DIR = "openspec" # 项目用 OpenSpec 时,它的文件里的 ```flow 代码块也是需求
|
|
69
|
+
MAX_OPENSPEC_FILES = 5000 # openspec/ 下最多看这么多个 Markdown 文件
|
|
70
|
+
STATUSES = ("草稿", "已确认", "已实现", "已完成")
|
|
71
|
+
END_KINDS = {"成功": "ok", "跳过": "skipped", "失败": "failed"}
|
|
72
|
+
END_NAMES = {v: k for k, v in END_KINDS.items()}
|
|
73
|
+
TYPE_NAMES = {"step": "步骤", "cond": "判断", "loop": "循环", "end": "结局"}
|
|
74
|
+
MAX_PATHS = 2000 # 设计的流程最多展开这么多条路;再多就不比走向(判断一个接一个、都不带结局时路数翻倍)
|
|
75
|
+
MAX_FILE = 200_000 # 需求文件最大字节数(再大不读)
|
|
76
|
+
_ID = re.compile(r"^R\d{3,}$")
|
|
77
|
+
_CJK = re.compile(r"[一-鿿]")
|
|
78
|
+
_COLON = "::"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class RequirementError(ValueError):
|
|
82
|
+
"""需求写不了:编号、状态不合法,或者流程解析不了。"""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class Item:
|
|
87
|
+
"""设计流程里的一个节点。kind:step / cond / loop / end。"""
|
|
88
|
+
|
|
89
|
+
kind: str
|
|
90
|
+
title: str
|
|
91
|
+
line: int # 在流程文本里的行号(从 1 起)
|
|
92
|
+
end_kind: str = "" # 结局:ok / skipped / failed
|
|
93
|
+
yes: list[Item] = field(default_factory=list) # 判断的"是"分支
|
|
94
|
+
no: list[Item] = field(default_factory=list) # 判断的"否"分支
|
|
95
|
+
body: list[Item] = field(default_factory=list) # 循环体
|
|
96
|
+
fail: list[Item] = field(default_factory=list) # 步骤的"失败时"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class Requirement:
|
|
101
|
+
id: str
|
|
102
|
+
title: str
|
|
103
|
+
status: str
|
|
104
|
+
line: str # 功能线:标题、sid 或入口函数的限定名(空 = 没写)
|
|
105
|
+
description: str
|
|
106
|
+
flow_text: str
|
|
107
|
+
file: str = "" # 相对项目根目录的路径
|
|
108
|
+
items: list[Item] = field(default_factory=list)
|
|
109
|
+
errors: list[str] = field(default_factory=list) # 文件、流程哪里读不懂(有的话不对照)
|
|
110
|
+
text: str = "" # 文件的原文(从文件读出来的才有;给界面看)
|
|
111
|
+
source: str = "pystepmap" # pystepmap:.pystepmap/requirements/ 里的文件;openspec:OpenSpec 文件里的 flow 代码块
|
|
112
|
+
archived: bool = False # OpenSpec 已归档的变更(openspec/changes/archive/<变更>/)里的:当时的设计,列出来但和正在做的分开
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass
|
|
116
|
+
class Difference:
|
|
117
|
+
kind: str # missing / extra / kind / order / no_line
|
|
118
|
+
text: str # 给人看的一句
|
|
119
|
+
type: str = "" # 节点类型 step / cond / loop / end
|
|
120
|
+
title: str = ""
|
|
121
|
+
node: str = "" # extra、kind:实现里那个节点的 sid
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass
|
|
125
|
+
class Comparison:
|
|
126
|
+
line_sid: str = "" # 对上的功能线(没找到时空)
|
|
127
|
+
line_title: str = ""
|
|
128
|
+
differences: list[Difference] = field(default_factory=list)
|
|
129
|
+
outcomes: list[tuple[str, str, str]] = field(default_factory=list) # 设计的结局:(标题, 分类, 实现里的节点 sid 或 "")
|
|
130
|
+
notes: list[str] = field(default_factory=list)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def matches(self) -> bool:
|
|
134
|
+
return bool(self.line_sid) and not self.differences
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# ---------- 读文件 ----------
|
|
138
|
+
|
|
139
|
+
def _norm(title: str) -> str:
|
|
140
|
+
"""配对用的标题:去掉空白、反引号,问号不分全角半角,去掉句末的句号、分号。"""
|
|
141
|
+
s = "".join(title.replace("`", "").split()).replace("?", "?")
|
|
142
|
+
return s.rstrip("。;;.")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def parse_flow(text: str) -> tuple[list[Item], list[str]]:
|
|
146
|
+
"""流程文本 → (节点树, 读不懂的地方)。有读不懂的地方时节点树不可靠,调用方不该拿去对照。"""
|
|
147
|
+
errors: list[str] = []
|
|
148
|
+
rows: list[tuple[int, int, str]] = [] # (行号, 缩进, 内容)
|
|
149
|
+
for no, raw in enumerate(text.splitlines(), 1):
|
|
150
|
+
if not raw.strip() or raw.strip().startswith("#"):
|
|
151
|
+
continue
|
|
152
|
+
if "\t" in raw[: len(raw) - len(raw.lstrip())]:
|
|
153
|
+
errors.append(f"第 {no} 行:缩进要用空格,不要用制表符")
|
|
154
|
+
continue
|
|
155
|
+
rows.append((no, len(raw) - len(raw.lstrip(" ")), raw.strip()))
|
|
156
|
+
pos = 0
|
|
157
|
+
|
|
158
|
+
def head(content: str) -> tuple[str, str, str]:
|
|
159
|
+
"""(关键字, 括号里的, 冒号后面的);不是"关键字:……"的样子时关键字为空。"""
|
|
160
|
+
m = re.match(r"^(步骤|判断|循环|结局|失败时|是|否)\s*(?:[((]\s*([^))]*)\s*[))])?\s*[::]\s*(.*)$", content)
|
|
161
|
+
return (m.group(1), (m.group(2) or "").strip(), m.group(3).strip()) if m else ("", "", "")
|
|
162
|
+
|
|
163
|
+
def block(indent: int) -> list[Item]:
|
|
164
|
+
nonlocal pos
|
|
165
|
+
out: list[Item] = []
|
|
166
|
+
while pos < len(rows):
|
|
167
|
+
no, ind, content = rows[pos]
|
|
168
|
+
if ind < indent:
|
|
169
|
+
break
|
|
170
|
+
if ind > indent:
|
|
171
|
+
errors.append(f"第 {no} 行:缩进多了(上一行不是判断的分支、也不是循环)")
|
|
172
|
+
pos += 1
|
|
173
|
+
continue
|
|
174
|
+
key, paren, rest = head(content)
|
|
175
|
+
if key in ("", "是", "否", "失败时"):
|
|
176
|
+
errors.append(f"第 {no} 行:读不懂 {content!r}——每行以 步骤: / 判断: / 循环: / 结局(成功|跳过|失败): 开头"
|
|
177
|
+
if key == "" else f"第 {no} 行:{key}: 只能写在{'步骤' if key == '失败时' else '判断'}的下面")
|
|
178
|
+
pos += 1
|
|
179
|
+
continue
|
|
180
|
+
if not rest:
|
|
181
|
+
errors.append(f"第 {no} 行:{key} 没有写标题")
|
|
182
|
+
pos += 1
|
|
183
|
+
if out and out[-1].kind == "end":
|
|
184
|
+
errors.append(f"第 {no} 行:前面已经是结局,这一行走不到")
|
|
185
|
+
if key == "步骤":
|
|
186
|
+
item = Item("step", rest, no)
|
|
187
|
+
if pos < len(rows) and rows[pos][1] > indent and head(rows[pos][2])[0] == "失败时":
|
|
188
|
+
fno, find, fcontent = rows[pos]
|
|
189
|
+
if head(fcontent)[2]:
|
|
190
|
+
errors.append(f"第 {fno} 行:失败时: 后面不要接内容,内容写在下一行并再缩进一层")
|
|
191
|
+
pos += 1
|
|
192
|
+
item.fail = block(_deeper(find))
|
|
193
|
+
if not item.fail:
|
|
194
|
+
errors.append(f"第 {fno} 行:失败时: 下面没有内容")
|
|
195
|
+
out.append(item)
|
|
196
|
+
elif key == "结局":
|
|
197
|
+
if paren not in END_KINDS:
|
|
198
|
+
errors.append(f"第 {no} 行:结局要写成 结局(成功): / 结局(跳过): / 结局(失败):")
|
|
199
|
+
out.append(Item("end", rest, no, end_kind=END_KINDS.get(paren, "ok")))
|
|
200
|
+
elif key == "循环":
|
|
201
|
+
item = Item("loop", rest, no)
|
|
202
|
+
item.body = block(_deeper(indent))
|
|
203
|
+
out.append(item)
|
|
204
|
+
else:
|
|
205
|
+
item = Item("cond", rest, no)
|
|
206
|
+
seen: set[str] = set()
|
|
207
|
+
while pos < len(rows) and rows[pos][1] > indent:
|
|
208
|
+
bno, bind, bcontent = rows[pos]
|
|
209
|
+
bkey, _, brest = head(bcontent)
|
|
210
|
+
if bkey not in ("是", "否"):
|
|
211
|
+
errors.append(f"第 {bno} 行:判断的下面只能是 是: 或 否:,然后再缩进一层写内容")
|
|
212
|
+
pos += 1
|
|
213
|
+
continue
|
|
214
|
+
if bkey in seen:
|
|
215
|
+
errors.append(f"第 {bno} 行:{bkey}: 写了两次")
|
|
216
|
+
seen.add(bkey)
|
|
217
|
+
if brest:
|
|
218
|
+
errors.append(f"第 {bno} 行:{bkey}: 后面不要接内容,内容写在下一行并再缩进一层")
|
|
219
|
+
pos += 1
|
|
220
|
+
inner = block(_deeper(bind))
|
|
221
|
+
if bkey == "是":
|
|
222
|
+
item.yes = inner
|
|
223
|
+
else:
|
|
224
|
+
item.no = inner
|
|
225
|
+
out.append(item)
|
|
226
|
+
return out
|
|
227
|
+
|
|
228
|
+
def _deeper(indent: int) -> int:
|
|
229
|
+
return rows[pos][1] if pos < len(rows) and rows[pos][1] > indent else indent + 1
|
|
230
|
+
|
|
231
|
+
items = block(rows[0][1] if rows else 0)
|
|
232
|
+
if not rows:
|
|
233
|
+
errors.append("流程是空的")
|
|
234
|
+
return items, errors
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def parse_requirement(text: str, file: str = "") -> Requirement:
|
|
238
|
+
"""需求文件的内容 → Requirement。读不懂的地方记在 errors 里,不抛异常。"""
|
|
239
|
+
title, meta, sections, current, fence = "", {}, {}, "", False
|
|
240
|
+
for raw in text.splitlines():
|
|
241
|
+
if raw.strip().startswith("```"):
|
|
242
|
+
fence = not fence
|
|
243
|
+
if current == "设计的流程":
|
|
244
|
+
continue
|
|
245
|
+
if not fence and raw.startswith("# ") and not title:
|
|
246
|
+
title = raw[2:].strip()
|
|
247
|
+
elif not fence and raw.startswith("## "):
|
|
248
|
+
current = raw[3:].strip()
|
|
249
|
+
sections[current] = []
|
|
250
|
+
elif current:
|
|
251
|
+
sections[current].append(raw)
|
|
252
|
+
else:
|
|
253
|
+
m = re.match(r"^\s*[-*]\s*(编号|状态|功能线)\s*[::]\s*(.*)$", raw)
|
|
254
|
+
if m:
|
|
255
|
+
meta[m.group(1)] = m.group(2).strip()
|
|
256
|
+
flow_text = "\n".join(sections.get("设计的流程", [])).strip("\n")
|
|
257
|
+
r = Requirement(id=meta.get("编号", ""), title=title, status=meta.get("状态", ""), line=meta.get("功能线", ""),
|
|
258
|
+
description="\n".join(sections.get("说明", [])).strip(), flow_text=flow_text, file=file)
|
|
259
|
+
if not title:
|
|
260
|
+
r.errors.append("没有标题(第一行写 # 标题)")
|
|
261
|
+
if not _ID.match(r.id):
|
|
262
|
+
r.errors.append(f"编号要写成 R 加至少三位数字(- 编号:R001),现在是 {r.id!r}")
|
|
263
|
+
if r.status not in STATUSES:
|
|
264
|
+
r.errors.append(f"状态要是 {' / '.join(STATUSES)} 之一,现在是 {r.status!r}")
|
|
265
|
+
if "设计的流程" not in sections:
|
|
266
|
+
r.errors.append("没有「## 设计的流程」一节")
|
|
267
|
+
else:
|
|
268
|
+
r.items, errors = parse_flow(flow_text)
|
|
269
|
+
r.errors += [f"设计的流程 {e}" for e in errors]
|
|
270
|
+
return r
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
_FENCE = re.compile(r"^(`{3,}|~{3,})\s*([^\s`]*)")
|
|
274
|
+
_LINE_HEAD = re.compile(r"^\s*功能线\s*[::]\s*(.*)$")
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def flow_blocks(text: str) -> list[tuple[str, str]]:
|
|
278
|
+
"""Markdown 里的 ```flow 代码块(~~~ 也认):[(代码块上方最近的标题,没有时 "", 块里的文本)]。别的代码块里的
|
|
279
|
+
标题、围栏不算。"""
|
|
280
|
+
out: list[tuple[str, str]] = []
|
|
281
|
+
heading, fence, is_flow, buf = "", "", False, []
|
|
282
|
+
for raw in text.splitlines():
|
|
283
|
+
s = raw.strip()
|
|
284
|
+
if fence:
|
|
285
|
+
if s.startswith(fence) and not s.strip(fence[0]):
|
|
286
|
+
if is_flow:
|
|
287
|
+
out.append((heading, "\n".join(buf)))
|
|
288
|
+
fence = ""
|
|
289
|
+
else:
|
|
290
|
+
buf.append(raw)
|
|
291
|
+
elif m := _FENCE.match(s):
|
|
292
|
+
fence, is_flow, buf = m.group(1), m.group(2).lower() == "flow", []
|
|
293
|
+
elif s.startswith("#"):
|
|
294
|
+
heading = s.lstrip("#").strip()
|
|
295
|
+
return out
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _openspec_files(root: Path) -> list[tuple[Path, str]]:
|
|
299
|
+
"""OpenSpec 里要看的 Markdown 文件:[(路径, 所属的编号前缀)]。进行中的变更(openspec/changes/<变更>/)前缀是变更名;
|
|
300
|
+
当前规格(openspec/specs/<能力>/)前缀是 specs/<能力>;已归档的变更(openspec/changes/archive/<变更>/)前缀是
|
|
301
|
+
archive/<变更>,排在最后。链接不跟。"""
|
|
302
|
+
base = root / OPENSPEC_DIR
|
|
303
|
+
if not base.is_dir() or base.is_symlink():
|
|
304
|
+
return []
|
|
305
|
+
groups: list[tuple[Path, str]] = []
|
|
306
|
+
for kind in ("changes", "specs"):
|
|
307
|
+
top = base / kind
|
|
308
|
+
if not top.is_dir() or top.is_symlink():
|
|
309
|
+
continue
|
|
310
|
+
for sub in sorted(top.iterdir()):
|
|
311
|
+
if sub.is_dir() and not sub.is_symlink() and not (kind == "changes" and sub.name == ARCHIVE_DIR):
|
|
312
|
+
groups.append((sub, sub.name if kind == "changes" else f"specs/{sub.name}"))
|
|
313
|
+
archive = base / "changes" / ARCHIVE_DIR
|
|
314
|
+
if archive.is_dir() and not archive.is_symlink():
|
|
315
|
+
groups += [(sub, f"{ARCHIVE_DIR}/{sub.name}") for sub in sorted(archive.iterdir())
|
|
316
|
+
if sub.is_dir() and not sub.is_symlink()]
|
|
317
|
+
out: list[tuple[Path, str]] = []
|
|
318
|
+
for folder, prefix in groups:
|
|
319
|
+
for path in sorted(folder.rglob("*.md")):
|
|
320
|
+
if len(out) >= MAX_OPENSPEC_FILES:
|
|
321
|
+
return out
|
|
322
|
+
if path.is_file() and not path.is_symlink() and not any((root / p).is_symlink() for p in path.relative_to(root).parents):
|
|
323
|
+
out.append((path, prefix))
|
|
324
|
+
return out
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def load_openspec(root: Path) -> list[Requirement]:
|
|
328
|
+
"""OpenSpec 文件里的 flow 代码块,每块一条需求(见模块说明)。没有 openspec/ 目录、没有 flow 代码块时空。"""
|
|
329
|
+
out: list[Requirement] = []
|
|
330
|
+
counts: dict[str, int] = {}
|
|
331
|
+
for path, prefix in _openspec_files(root):
|
|
332
|
+
rel = path.relative_to(root).as_posix()
|
|
333
|
+
try:
|
|
334
|
+
if path.stat().st_size > MAX_FILE:
|
|
335
|
+
continue
|
|
336
|
+
text = path.read_text(encoding="utf-8")
|
|
337
|
+
except (OSError, ValueError):
|
|
338
|
+
continue # OpenSpec 的文件读不了不是需求的错:不列
|
|
339
|
+
if "flow" not in text:
|
|
340
|
+
continue
|
|
341
|
+
blocks = flow_blocks(text)
|
|
342
|
+
shared = {h for h, _ in blocks if sum(1 for x, _ in blocks if x == h) > 1} # 一个小节里放了几块:标题会重名
|
|
343
|
+
for heading, body in blocks:
|
|
344
|
+
line, rows = "", []
|
|
345
|
+
for raw in body.splitlines():
|
|
346
|
+
m = _LINE_HEAD.match(raw)
|
|
347
|
+
if m and not line:
|
|
348
|
+
line = " ".join(m.group(1).split())
|
|
349
|
+
rows.append("") # 留一个空行:流程里报错的行号还是代码块里的行号
|
|
350
|
+
else:
|
|
351
|
+
rows.append(raw)
|
|
352
|
+
counts[prefix] = counts.get(prefix, 0) + 1
|
|
353
|
+
rid = prefix if counts[prefix] == 1 else f"{prefix}#{counts[prefix]}"
|
|
354
|
+
archived = prefix.startswith(ARCHIVE_DIR + "/")
|
|
355
|
+
name = prefix.split("/", 1)[1] if archived else prefix
|
|
356
|
+
# 标题:变更名加代码块上方最近的小节标题;同一个小节里有几块时小节标题分不开它们,改用各自写的功能线
|
|
357
|
+
said = line if line and (heading in shared or not heading) else heading
|
|
358
|
+
r = Requirement(id=rid, title=f"{name}:{said}" if said else name,
|
|
359
|
+
status=ARCHIVED if archived else "已实现" if prefix.startswith("specs/") else "已确认",
|
|
360
|
+
line=line, description="", flow_text="\n".join(rows).strip("\n"), file=rel, text=text,
|
|
361
|
+
source="openspec", archived=archived)
|
|
362
|
+
r.items, errors = parse_flow(r.flow_text)
|
|
363
|
+
r.errors = [f"设计的流程 {e}" for e in errors]
|
|
364
|
+
if not line:
|
|
365
|
+
r.errors.append("flow 代码块里没有写功能线(块里第一行写 功能线:<功能线的标题>)")
|
|
366
|
+
out.append(r)
|
|
367
|
+
return out
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def uses_openspec(root: Path) -> bool:
|
|
371
|
+
"""项目是不是用 OpenSpec 管需求(根目录下有 openspec/ 目录)。"""
|
|
372
|
+
return (root / OPENSPEC_DIR).is_dir()
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def load_requirements(root: Path) -> list[Requirement]:
|
|
376
|
+
"""项目里的全部需求:.pystepmap/requirements/ 里的文件(按编号、文件名排序),后面是 OpenSpec 文件里的 flow 代码块
|
|
377
|
+
(load_openspec)。都没有时空;读不了、太大的需求文件也列出来(errors 里说明)。链接到别处的文件不读。"""
|
|
378
|
+
return _load_own(root) + load_openspec(root)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _load_own(root: Path) -> list[Requirement]:
|
|
382
|
+
folder = root / DIR
|
|
383
|
+
if not folder.is_dir() or folder.is_symlink():
|
|
384
|
+
return []
|
|
385
|
+
out: list[Requirement] = []
|
|
386
|
+
for path in sorted(folder.glob("*.md")):
|
|
387
|
+
rel = f"{DIR}/{path.name}"
|
|
388
|
+
if path.is_symlink() or not path.is_file():
|
|
389
|
+
continue
|
|
390
|
+
try:
|
|
391
|
+
if path.stat().st_size > MAX_FILE:
|
|
392
|
+
raise ValueError(f"文件太大(超过 {MAX_FILE} 字节)")
|
|
393
|
+
text = path.read_text(encoding="utf-8")
|
|
394
|
+
out.append(parse_requirement(text, rel))
|
|
395
|
+
out[-1].text = text
|
|
396
|
+
except (OSError, ValueError) as e:
|
|
397
|
+
out.append(Requirement(id="", title=path.name, status="", line="", description="", flow_text="", file=rel,
|
|
398
|
+
errors=[f"读不了:{e}"]))
|
|
399
|
+
ids: dict[str, str] = {}
|
|
400
|
+
for r in out:
|
|
401
|
+
if r.id and r.id in ids:
|
|
402
|
+
r.errors.append(f"编号 {r.id} 和 {ids[r.id]} 重复")
|
|
403
|
+
ids.setdefault(r.id, r.file)
|
|
404
|
+
return sorted(out, key=lambda r: (r.id or "~", r.file))
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
# ---------- 写文件 ----------
|
|
408
|
+
|
|
409
|
+
def render_requirement(r: Requirement) -> str:
|
|
410
|
+
body = f"# {r.title}\n\n- 编号:{r.id}\n- 状态:{r.status}\n- 功能线:{r.line}\n\n## 说明\n\n{r.description.strip()}\n\n"
|
|
411
|
+
return body + f"## 设计的流程\n\n```flow\n{r.flow_text.strip(chr(10))}\n```\n"
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def next_id(existing: list[Requirement]) -> str:
|
|
415
|
+
numbers = [int(r.id[1:]) for r in existing if _ID.match(r.id)]
|
|
416
|
+
return f"R{max(numbers, default=0) + 1:03d}"
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _slug(title: str) -> str:
|
|
420
|
+
s = re.sub(r'[\s/\\:*?"<>|.\x00-\x1f]+', "-", title).strip("-")
|
|
421
|
+
return s[:40] or "需求"
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def save_requirement(root: Path, *, title: str, line: str, description: str, flow: str, status: str = "草稿",
|
|
425
|
+
id: str | None = None) -> Requirement:
|
|
426
|
+
"""新建(id 不给)或整条改写(id 给出、已经存在)一条需求,写进 <root>/.pystepmap/requirements/。这是唯一写
|
|
427
|
+
项目文件的地方。标题、状态、流程不合法时抛 RequirementError,什么都不写。返回写下的需求。"""
|
|
428
|
+
title, line = " ".join(title.split()), " ".join(line.split())
|
|
429
|
+
if not title:
|
|
430
|
+
raise RequirementError("需求没有标题")
|
|
431
|
+
if status not in STATUSES:
|
|
432
|
+
raise RequirementError(f"状态要是 {' / '.join(STATUSES)} 之一,现在是 {status!r}")
|
|
433
|
+
_, errors = parse_flow(flow)
|
|
434
|
+
if errors:
|
|
435
|
+
raise RequirementError("设计的流程读不懂:" + ";".join(errors[:8]))
|
|
436
|
+
if "```" in flow or "```" in description:
|
|
437
|
+
raise RequirementError("说明和流程里不要写 ``` 代码块围栏")
|
|
438
|
+
existing = _load_own(root)
|
|
439
|
+
if id is not None and not any(r.id == id for r in existing) and any(r.id == id for r in load_openspec(root)):
|
|
440
|
+
raise RequirementError(f"{id} 写在 OpenSpec 的文件里:直接改那个文件里的 flow 代码块,save_requirement 不写 OpenSpec 的文件")
|
|
441
|
+
folder = root / DIR
|
|
442
|
+
if folder.is_symlink() or (root / ".pystepmap").is_symlink():
|
|
443
|
+
raise RequirementError(f"{DIR} 是一个链接,不往里写")
|
|
444
|
+
if id is None:
|
|
445
|
+
new = Requirement(next_id(existing), title, status, line, description, flow)
|
|
446
|
+
target = folder / f"{new.id}-{_slug(title)}.md"
|
|
447
|
+
else:
|
|
448
|
+
found = [r for r in existing if r.id == id]
|
|
449
|
+
if not found:
|
|
450
|
+
raise RequirementError(f"没有编号是 {id} 的需求(新建时不要给编号)")
|
|
451
|
+
new = Requirement(id, title, status, line, description, flow)
|
|
452
|
+
target = root / found[0].file
|
|
453
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
454
|
+
target.write_text(render_requirement(new), encoding="utf-8")
|
|
455
|
+
new.file = str(target.relative_to(root))
|
|
456
|
+
new.items, _ = parse_flow(flow)
|
|
457
|
+
return new
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
# ---------- 对照 ----------
|
|
461
|
+
|
|
462
|
+
Step = tuple[str, str, str] # (类型, 配对用的标题, 判断走的分支 yes / no;其余为空)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def design_paths(items: list[Item]) -> tuple[list[tuple[list[Step], Item | None]], bool]:
|
|
466
|
+
"""设计的流程里的每一条路:(依次经过的节点, 走到的结局;走到末尾没有结局时 None)。循环体按走一遍算,再加一条
|
|
467
|
+
不进循环体的路。第二项:路太多(超过 MAX_PATHS)被截断了没有。"""
|
|
468
|
+
done: list[tuple[list[Step], Item | None]] = []
|
|
469
|
+
cut = False
|
|
470
|
+
|
|
471
|
+
def walk(seq: list[Item], prefix: list[Step], rest: list[list[Item]]) -> None:
|
|
472
|
+
nonlocal cut
|
|
473
|
+
if len(done) >= MAX_PATHS:
|
|
474
|
+
cut = True
|
|
475
|
+
return
|
|
476
|
+
for i, it in enumerate(seq):
|
|
477
|
+
after = [seq[i + 1:], *rest]
|
|
478
|
+
if it.kind == "end":
|
|
479
|
+
done.append((prefix, it))
|
|
480
|
+
return
|
|
481
|
+
if it.kind == "step":
|
|
482
|
+
prefix = [*prefix, ("step", _norm(it.title), "")]
|
|
483
|
+
if it.fail:
|
|
484
|
+
walk(it.fail, prefix, after)
|
|
485
|
+
elif it.kind == "loop":
|
|
486
|
+
here = [*prefix, ("loop", _norm(it.title), "")]
|
|
487
|
+
if it.body:
|
|
488
|
+
walk(it.body, here, after)
|
|
489
|
+
prefix = here
|
|
490
|
+
else:
|
|
491
|
+
walk(it.yes, [*prefix, ("cond", _norm(it.title), "yes")], after)
|
|
492
|
+
walk(it.no, [*prefix, ("cond", _norm(it.title), "no")], after)
|
|
493
|
+
return
|
|
494
|
+
if rest:
|
|
495
|
+
walk(rest[0], prefix, rest[1:])
|
|
496
|
+
else:
|
|
497
|
+
done.append((prefix, None))
|
|
498
|
+
|
|
499
|
+
walk(items, [], [])
|
|
500
|
+
return done, cut
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _all_items(items: list[Item]) -> list[Item]:
|
|
504
|
+
out: list[Item] = []
|
|
505
|
+
for it in items:
|
|
506
|
+
out.append(it)
|
|
507
|
+
out += _all_items(it.yes) + _all_items(it.no) + _all_items(it.body) + _all_items(it.fail)
|
|
508
|
+
return out
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def find_line(graph: ProjectGraph, name: str):
|
|
512
|
+
"""需求里写的功能线 → 图上的功能线:sid、标题(含手工没改过的完整标题)、入口函数的限定名,按这个顺序找;
|
|
513
|
+
找不到、或者对上不止一条时 None。"""
|
|
514
|
+
name = name.strip()
|
|
515
|
+
if not name:
|
|
516
|
+
return None
|
|
517
|
+
for pick in (lambda ln: ln.sid == name,
|
|
518
|
+
lambda ln: _norm(name) in (_norm(ln.title), _norm(ln.title_full or "")),
|
|
519
|
+
lambda ln: graph.functions[ln.root.function].qualname == name):
|
|
520
|
+
hits = [ln for ln in graph.lines if pick(ln)]
|
|
521
|
+
if len(hits) == 1:
|
|
522
|
+
return hits[0]
|
|
523
|
+
if hits:
|
|
524
|
+
return None
|
|
525
|
+
return None
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _line_functions(graph: ProjectGraph, line) -> list[FunctionGraph]:
|
|
529
|
+
out, stack = [], [line.root]
|
|
530
|
+
while stack:
|
|
531
|
+
task = stack.pop()
|
|
532
|
+
if task.function in graph.functions and not task.goto:
|
|
533
|
+
out.append(graph.functions[task.function])
|
|
534
|
+
stack += task.children
|
|
535
|
+
return out
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _shown(node) -> bool:
|
|
539
|
+
"""实现里算数的节点:步骤、判断、循环、写出来的结局(隐含的"执行到函数末尾""未捕获异常退出"不算)。"""
|
|
540
|
+
if node.type == "end":
|
|
541
|
+
return node.sid not in ("end:implicit", "end:uncaught") and node.end_kind != "exception"
|
|
542
|
+
return node.type in ("step", "cond", "loop")
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _order_holds(fg: FunctionGraph, steps: list[Step], end: Item) -> bool:
|
|
546
|
+
"""根函数里有没有一条路:按 steps 的顺序经过这些节点(判断从写明的那个分支出去),最后到 end 这个结局。实现里
|
|
547
|
+
多出来的节点可以夹在中间。状态 (节点, i):到了这个节点,它前面已经按顺序对上了 steps 的前 i 个。"""
|
|
548
|
+
by_id = {n.id: n for n in fg.nodes}
|
|
549
|
+
outs: dict[str, list] = {}
|
|
550
|
+
for e in fg.edges:
|
|
551
|
+
outs.setdefault(e.src, []).append(e)
|
|
552
|
+
start = next((n.id for n in fg.nodes if n.type == "start"), None)
|
|
553
|
+
if start is None:
|
|
554
|
+
return False
|
|
555
|
+
want_end = _norm(end.title)
|
|
556
|
+
seen = {(start, 0)}
|
|
557
|
+
queue = deque(seen)
|
|
558
|
+
while queue:
|
|
559
|
+
nid, i = queue.popleft()
|
|
560
|
+
node = by_id[nid]
|
|
561
|
+
if node.type == "end":
|
|
562
|
+
if i == len(steps) and _norm(node.title) == want_end:
|
|
563
|
+
return True
|
|
564
|
+
continue
|
|
565
|
+
moves = [(e.dst, i) for e in outs.get(nid, [])] # 不把这个节点算作设计里的下一个
|
|
566
|
+
if i < len(steps) and (node.type, _norm(node.title)) == steps[i][:2]:
|
|
567
|
+
branch = steps[i][2] # 是设计里的下一个:判断只从写明的分支出去
|
|
568
|
+
moves += [(e.dst, i + 1) for e in outs.get(nid, []) if not branch or e.branch == branch]
|
|
569
|
+
for state in moves:
|
|
570
|
+
if state not in seen and state[0] in by_id:
|
|
571
|
+
seen.add(state)
|
|
572
|
+
queue.append(state)
|
|
573
|
+
return False
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _path_text(steps: list[Step], end: Item) -> str:
|
|
577
|
+
parts = [f"{t}{'(是)' if b == 'yes' else '(否)' if b == 'no' else ''}" for _, t, b in steps]
|
|
578
|
+
return " → ".join([*parts, f"结局「{end.title}」"])
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _misplaced(fg: FunctionGraph, broken: list[tuple[list[Step], Item]]) -> tuple[str, str] | None:
|
|
582
|
+
"""几条路都走不通时,找那个"放错了位置"的节点:每条走不通的路上都有它,把它从路上拿掉之后每条路都走得通。
|
|
583
|
+
返回它的(类型, 归一化的标题);找不到这样的一个节点时 None(各条路照旧分别报)。按第一条路上的顺序找。"""
|
|
584
|
+
shared = set.intersection(*({st[:2] for st in steps} for steps, _ in broken))
|
|
585
|
+
for kind, title, _ in broken[0][0]:
|
|
586
|
+
if (kind, title) in shared and all(
|
|
587
|
+
_order_holds(fg, [st for st in steps if st[:2] != (kind, title)], end) for steps, end in broken):
|
|
588
|
+
return kind, title
|
|
589
|
+
return None
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _misplaced_difference(moved: tuple[str, str], in_root: dict, designed: list[Item],
|
|
593
|
+
broken: dict[str, tuple[list[Step], Item]]) -> Difference:
|
|
594
|
+
""""放错位置"的一句话:设计里它前后是谁、实现里它在第几行、因此几条路走不通(附最短的一条当例子)。"""
|
|
595
|
+
kind, key = moved
|
|
596
|
+
title = next((it.title for it in designed if (it.kind, _norm(it.title)) == moved), key)
|
|
597
|
+
names = {(it.kind, _norm(it.title)): it.title for it in designed}
|
|
598
|
+
steps = next(steps for steps, _ in broken.values() if moved in {st[:2] for st in steps})
|
|
599
|
+
at = next(i for i, st in enumerate(steps) if st[:2] == moved)
|
|
600
|
+
before = f"「{names.get(steps[at - 1][:2], steps[at - 1][1])}」之后" if at else "最前面"
|
|
601
|
+
after = f"、「{names.get(steps[at + 1][:2], steps[at + 1][1])}」之前" if at + 1 < len(steps) else ""
|
|
602
|
+
node = in_root[moved]
|
|
603
|
+
example = min(broken, key=len)
|
|
604
|
+
return Difference(
|
|
605
|
+
"order", f"走向不一致:{TYPE_NAMES[kind]}「{title}」的位置和设计不一样——设计里它在{before}{after},实现里它在第 {node.line} 行;"
|
|
606
|
+
f"因此设计的 {len(broken)} 条路按顺序走不通,例如:{example}", kind, title, node.sid)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def compare(req: Requirement, graph: ProjectGraph) -> Comparison:
|
|
610
|
+
"""需求的设计流程和图上的实现对照。req.errors 不为空时不该调用(设计读不懂,没法比)。"""
|
|
611
|
+
out = Comparison()
|
|
612
|
+
designed = _all_items(req.items)
|
|
613
|
+
for it in designed:
|
|
614
|
+
if it.kind == "end":
|
|
615
|
+
out.outcomes.append((it.title, it.end_kind, ""))
|
|
616
|
+
line = find_line(graph, req.line)
|
|
617
|
+
if line is None:
|
|
618
|
+
why = "需求里没有写功能线" if not req.line.strip() else f"图上找不到功能线「{req.line}」(还没有实现,或者名字对不上、对上不止一条)"
|
|
619
|
+
out.differences.append(Difference("no_line", why))
|
|
620
|
+
out.differences += [Difference("missing", f"{TYPE_NAMES[it.kind]}「{it.title}」还没有实现", it.kind, it.title)
|
|
621
|
+
for it in designed]
|
|
622
|
+
return out
|
|
623
|
+
out.line_sid, out.line_title = line.sid, line.title
|
|
624
|
+
root = graph.functions[line.root.function]
|
|
625
|
+
everywhere: dict[tuple[str, str], list] = {}
|
|
626
|
+
for fg in _line_functions(graph, line):
|
|
627
|
+
for n in fg.nodes:
|
|
628
|
+
if _shown(n):
|
|
629
|
+
everywhere.setdefault((n.type, _norm(n.title)), []).append(n)
|
|
630
|
+
in_root = {(n.type, _norm(n.title)): n for n in reversed(root.nodes) if _shown(n)}
|
|
631
|
+
wanted = {(it.kind, _norm(it.title)) for it in designed}
|
|
632
|
+
# 入口函数没有写 return 的那条路(没有返回内容的接口):结局是隐含的"执行到函数末尾"。设计里照这个标题写了才配它;
|
|
633
|
+
# 没写时不算实现里多出来的(_shown 不认它)
|
|
634
|
+
fell = next((n for n in root.nodes if n.sid == "end:implicit"), None)
|
|
635
|
+
if fell is not None and ("end", _norm(fell.title)) in wanted:
|
|
636
|
+
everywhere.setdefault(("end", _norm(fell.title)), []).append(fell)
|
|
637
|
+
in_root.setdefault(("end", _norm(fell.title)), fell)
|
|
638
|
+
|
|
639
|
+
missing: set[tuple[str, str]] = set()
|
|
640
|
+
for it in designed:
|
|
641
|
+
key = (it.kind, _norm(it.title))
|
|
642
|
+
hits = everywhere.get(key, [])
|
|
643
|
+
if not hits:
|
|
644
|
+
if key not in missing:
|
|
645
|
+
# 实现里成功的那条路没有写 return:标题对不上多半是因为这个,说明两种写法
|
|
646
|
+
hint = (f"(实现里入口函数走到末尾没有写 return,那个结局的标题是「{fell.title}」:设计里写成 "
|
|
647
|
+
f"`结局(成功):{fell.title}`,或者在代码末尾写 return outcome(\"ok\", title=\"{it.title}\"))"
|
|
648
|
+
if it.kind == "end" and it.end_kind == "ok" and fell is not None
|
|
649
|
+
and ("end", _norm(fell.title)) not in wanted else "")
|
|
650
|
+
out.differences.append(Difference("missing", f"设计里的{TYPE_NAMES[it.kind]}「{it.title}」在实现里没有{hint}",
|
|
651
|
+
it.kind, it.title))
|
|
652
|
+
missing.add(key)
|
|
653
|
+
elif it.kind == "end" and all(n.end_kind != it.end_kind for n in hits):
|
|
654
|
+
have = hits[0]
|
|
655
|
+
out.differences.append(Difference(
|
|
656
|
+
"kind", f"结局「{it.title}」设计的是{END_NAMES[it.end_kind]},实现的是{END_NAMES.get(have.end_kind, have.end_kind)}",
|
|
657
|
+
"end", it.title, have.sid))
|
|
658
|
+
out.outcomes = [(t, k, next((n.sid for n in everywhere.get(("end", _norm(t)), [])), "")) for t, k, _ in out.outcomes]
|
|
659
|
+
for key, n in in_root.items():
|
|
660
|
+
if key not in wanted and _CJK.search(n.title):
|
|
661
|
+
out.differences.append(Difference("extra", f"实现里的{TYPE_NAMES[n.type]}「{n.title}」设计里没有", n.type, n.title, n.sid))
|
|
662
|
+
|
|
663
|
+
paths, cut = design_paths(req.items)
|
|
664
|
+
if cut:
|
|
665
|
+
out.notes.append(f"设计的流程展开超过 {MAX_PATHS} 条路,走向没有比全")
|
|
666
|
+
broken: dict[str, tuple[list[Step], Item]] = {} # 走不通的路:文字 -> (路上的节点, 结局),按设计里的顺序
|
|
667
|
+
for steps, end in paths:
|
|
668
|
+
if end is None:
|
|
669
|
+
out.notes.append("设计里有一条路走到末尾没有写结局,这条路的走向没有比")
|
|
670
|
+
continue
|
|
671
|
+
if ("end", _norm(end.title)) not in in_root:
|
|
672
|
+
continue # 这个结局配不上(已经在 missing 里),或者在派发出去的任务里:走向只在根函数里比
|
|
673
|
+
# 路上有实现里没有的判断时不比:实现里没有它,它的两个分支分不开,拿掉它再比会把两个分支的内容都要求在同一条路上,
|
|
674
|
+
# 走不通又会算到它前面那个位置没错的判断头上。这个判断已经报了 missing,实现之后再对照
|
|
675
|
+
gone = next((st for st in steps if st[0] == "cond" and st[:2] in missing), None)
|
|
676
|
+
if gone is not None:
|
|
677
|
+
title = next(it.title for it in designed if (it.kind, _norm(it.title)) == gone[:2])
|
|
678
|
+
out.notes.append(f"设计里的判断「{title}」在实现里没有,经过它的路走向没有比(实现了这个判断再对照)")
|
|
679
|
+
continue
|
|
680
|
+
# 路上配不上的步骤 / 循环(已经在 missing 里)、在派发出去的任务里的节点先拿掉,剩下的照样要按顺序走得通
|
|
681
|
+
steps = [st for st in steps if (st[0], st[1]) in in_root]
|
|
682
|
+
if not _order_holds(root, steps, end):
|
|
683
|
+
broken.setdefault(_path_text(steps, end), (steps, end))
|
|
684
|
+
moved = _misplaced(root, list(broken.values())) if len(broken) > 1 else None
|
|
685
|
+
if moved is not None:
|
|
686
|
+
out.differences.append(_misplaced_difference(moved, in_root, designed, broken))
|
|
687
|
+
else:
|
|
688
|
+
out.differences += [Difference("order", f"走向不一致:设计的这条路在实现里走不通——{text}", "end", end.title)
|
|
689
|
+
for text, (_, end) in broken.items()]
|
|
690
|
+
if designed and len(missing) == len(wanted):
|
|
691
|
+
out.notes.insert(0, "设计的节点一个都没配上:对照按标题配对,多半不是没实现,而是标题对不上——这条功能线的代码没有用 pystepkit "
|
|
692
|
+
"标记时,图上的标题来自文档注释或代码原文;用 get_flow 看图上现在的标题,把设计里的标题写成和它一样"
|
|
693
|
+
"(或者给代码加上 @step / @condition / outcome 的 title)")
|
|
694
|
+
out.notes = list(dict.fromkeys(out.notes))
|
|
695
|
+
return out
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def reachable_status(req: Requirement, cmp: Comparison | None, covered: bool | None = None) -> str:
|
|
699
|
+
"""按对照结果,这条需求现在够得上的状态:设计读不懂、或者还是草稿 → 原样;对照有差异 → 已确认;没有差异 →
|
|
700
|
+
已实现;并且设计的每个结局都有测试走到(covered 为 True)→ 已完成。covered 为 None 表示不知道(没跑过测试)。"""
|
|
701
|
+
if req.errors or cmp is None or req.status not in STATUSES or req.status == "草稿":
|
|
702
|
+
return req.status
|
|
703
|
+
if not cmp.matches:
|
|
704
|
+
return "已确认"
|
|
705
|
+
return "已完成" if covered else "已实现"
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
# ---------- 设计的流程 → 图(给平台的画布画)----------
|
|
709
|
+
|
|
710
|
+
NO_END_TITLE = "(设计里没有写结局)"
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def design_graph(reqs: list[Requirement]) -> ProjectGraph:
|
|
714
|
+
"""把读得懂的需求的设计流程变成一张图:每条需求一个函数图、一条"功能线"(分组"需求"),节点、连线的类型和代码
|
|
715
|
+
分析出来的图一样,平台的画布可以直接画。函数的 key / sid 是"<需求文件>::<编号>",节点的 sid 是"<类型>:L<流程
|
|
716
|
+
文本里的行号>"(start、end:implicit 同代码的图),节点的行号都是 0(没有源码可看)。读不懂的需求不在图里。"""
|
|
717
|
+
from .model import SCHEMA_VERSION, Edge, FlowLine, LineTask, Node, SelfCheck
|
|
718
|
+
|
|
719
|
+
functions: dict[str, FunctionGraph] = {}
|
|
720
|
+
lines: list[FlowLine] = []
|
|
721
|
+
for r in reqs:
|
|
722
|
+
if r.errors or not r.id:
|
|
723
|
+
continue
|
|
724
|
+
nodes: list[Node] = [Node("n1", "start", r.title, sid="start")]
|
|
725
|
+
edges: list[Edge] = []
|
|
726
|
+
|
|
727
|
+
def add(node_type: str, title: str, sid: str, pending: list[tuple[str, str, str]], *, nodes=nodes, edges=edges,
|
|
728
|
+
**attrs) -> str:
|
|
729
|
+
nid = f"n{len(nodes) + 1}"
|
|
730
|
+
nodes.append(Node(nid, node_type, title, sid=sid, **attrs))
|
|
731
|
+
edges.extend(Edge(src, nid, kind, branch=branch) for src, kind, branch in pending)
|
|
732
|
+
return nid
|
|
733
|
+
|
|
734
|
+
def emit(items: list[Item], pending: list[tuple[str, str, str]], *, add=add,
|
|
735
|
+
edges=edges) -> list[tuple[str, str, str]]:
|
|
736
|
+
"""依次放 items,pending(来源节点、连线类型、分支)接到第一个节点上;返回走完之后还悬空的出边。"""
|
|
737
|
+
for it in items:
|
|
738
|
+
sid = f"{it.kind}:L{it.line}"
|
|
739
|
+
if it.kind == "end":
|
|
740
|
+
add("end", it.title, sid, pending, end_kind=it.end_kind)
|
|
741
|
+
return []
|
|
742
|
+
if it.kind == "step":
|
|
743
|
+
nid = add("step", it.title, sid, pending)
|
|
744
|
+
pending = [(nid, "next", ""), *(emit(it.fail, [(nid, "raise", "")]) if it.fail else [])]
|
|
745
|
+
elif it.kind == "loop":
|
|
746
|
+
nid = add("loop", it.title, sid, pending)
|
|
747
|
+
if it.body:
|
|
748
|
+
edges.extend(Edge(src, nid, "loop_back") for src, _, _ in emit(it.body, [(nid, "loop_each", "")]))
|
|
749
|
+
pending = [(nid, "loop_exit", "")]
|
|
750
|
+
else:
|
|
751
|
+
nid = add("cond", it.title, sid, pending)
|
|
752
|
+
pending = [*emit(it.yes, [(nid, "yes", "yes")]), *emit(it.no, [(nid, "no", "no")])]
|
|
753
|
+
return pending
|
|
754
|
+
|
|
755
|
+
left = emit(r.items, [("n1", "next", "")])
|
|
756
|
+
if left:
|
|
757
|
+
add("end", NO_END_TITLE, "end:implicit", left, end_kind="ok")
|
|
758
|
+
key = f"{r.file}::{r.id}"
|
|
759
|
+
functions[key] = FunctionGraph(key=key, file=r.file, qualname=r.id, line=0, end_line=0, kind="workflow",
|
|
760
|
+
title=r.title, is_async=False, sid=key, marked=True, group="需求", nodes=nodes,
|
|
761
|
+
edges=edges)
|
|
762
|
+
lines.append(FlowLine(id=key, title=r.title, group="需求", kind="workflow", root=LineTask(function=key),
|
|
763
|
+
sid=f"line:{key}"))
|
|
764
|
+
return ProjectGraph(schema_version=SCHEMA_VERSION, root="", functions=functions, lines=lines, common_tasks=[],
|
|
765
|
+
selfcheck=SelfCheck([], [], 0, 0, []), file_hashes={}, sids={k: k for k in sorted(functions)})
|