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
pystepmap/diff.py
ADDED
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
"""两次分析之间的流程差异:哪些函数的节点、连线变了,哪些功能线因此有变化。纯函数,只读两张图。
|
|
2
|
+
|
|
3
|
+
配对方法见 docs/graph-schema.md "两种标识:key 与 sid":
|
|
4
|
+
- 函数、功能线按 sid 配对;只在新图里的是新增,只在旧图里的是删除。
|
|
5
|
+
- 配上对的函数:两边的节点各按(行,生成顺序)排成序列(开始节点最前,执行到函数末尾、未捕获异常退出最后),取去掉
|
|
6
|
+
#n 的基础 sid 做序列对齐(difflib.SequenceMatcher)。对上的节点配对、不算变化(标题因为注释或被调函数的文档变了也不
|
|
7
|
+
算);对不上的一段里再按顺序配一次:类型相同、文字(标题 + 副标题,完整形式,前 200 字)相似度不低于 0.6 的,取
|
|
8
|
+
保持顺序的最多对(最长公共子序列),配上的算改动(旧的改成了新的),其余旧的删除、新的新增。所以紧挨着改了的节点
|
|
9
|
+
插进一个节点,不会让配对错开。一段太大时不逐对比(见 MAX_BLOCK_PAIRS、MAX_BLOCK_WORK)。
|
|
10
|
+
- 连线没有标识:只比两端都配上对(对上的或改动的)的连线,按(起点,终点,kind,label)比;一端是新增 / 删除节点的
|
|
11
|
+
连线不单列,只有一个例外:新增的判断 / 循环 / 捕获节点的出边报成新增连线(看得到新分支通向哪里)。
|
|
12
|
+
节点的增删已经说明了的连线变化也不单列(改动的节点算留下的)。少掉的 A→B(多出的同理,换成旧图和删除的节点):
|
|
13
|
+
新图里从 A 第一步进新增的节点(A 是判断节点时从同一个分支出发)、之后只经新增的节点走得到 B;或者新图里有一条从
|
|
14
|
+
新增节点 P 到 B、kind 和 label 都相同的连线,而 P 只经新增的节点走得到 A(一段的入口换了,如 try 体第一句前插了
|
|
15
|
+
一句,异常连线改从新的第一句出发)。在两个留下的节点之间插进 / 删掉节点因此不报连线变化。
|
|
16
|
+
- 功能线有变化:它涉及的函数(新图、旧图里各自的 line_functions,按 sid 合并)里有变化的,或者派发树上的任务集合变了。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import difflib
|
|
22
|
+
import json
|
|
23
|
+
from dataclasses import MISSING, asdict, dataclass, field, fields
|
|
24
|
+
from typing import Literal, get_args, get_origin, get_type_hints
|
|
25
|
+
|
|
26
|
+
from .model import (
|
|
27
|
+
Edge,
|
|
28
|
+
FlowLine,
|
|
29
|
+
FunctionGraph,
|
|
30
|
+
LineTask,
|
|
31
|
+
Node,
|
|
32
|
+
ProjectGraph,
|
|
33
|
+
parse_key,
|
|
34
|
+
)
|
|
35
|
+
from .query import line_functions
|
|
36
|
+
|
|
37
|
+
DIFF_VERSION = 1
|
|
38
|
+
SIMILAR = 0.6 # 对不上的一段里,两个同类型节点的文字相似度(difflib ratio)不低于它才算"旧的改成了新的"
|
|
39
|
+
TEXT_LIMIT = 200 # 比相似时每个节点的文字只取前这么多字
|
|
40
|
+
# 对不上的一段太大时不再逐对比相似,全算删除和新增(整个函数大改时):两边节点数之积超过 MAX_BLOCK_PAIRS,或两边文字
|
|
41
|
+
# 总长之积超过 MAX_BLOCK_WORK。后者按最坏情况(很长、很重复的文字)量过:到上限时逐对比相似约 1.5 秒
|
|
42
|
+
MAX_BLOCK_PAIRS = 30_000
|
|
43
|
+
MAX_BLOCK_WORK = 200_000_000
|
|
44
|
+
_BRANCHING = ("cond", "loop", "catch") # 新增时把出边也报成新增连线的节点类型
|
|
45
|
+
_IMPLICIT_ENDS = ("end:implicit", "end:uncaught")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class NodeChange:
|
|
50
|
+
"""一个节点的变化;old_* / new_* 哪边没有就是空。标题、副标题是完整形式(x_full 不为空就用它,否则用 x)。"""
|
|
51
|
+
|
|
52
|
+
status: Literal["added", "removed", "changed"]
|
|
53
|
+
type: str
|
|
54
|
+
new_id: str = ""
|
|
55
|
+
new_sid: str = ""
|
|
56
|
+
new_title: str = ""
|
|
57
|
+
new_subtitle: str = ""
|
|
58
|
+
new_line: int = 0
|
|
59
|
+
old_sid: str = ""
|
|
60
|
+
old_title: str = ""
|
|
61
|
+
old_subtitle: str = ""
|
|
62
|
+
old_line: int = 0
|
|
63
|
+
# 以下只有 removed 有,界面和文本用来指位置:按旧图的控制流往回找到的、最近的仍然在的前驱节点(同样近的取源码里
|
|
64
|
+
# 最靠后的)在新图里的 id、标题(完整形式),以及它通往被删节点的那条连线怎么走(是 / 否 / case 模式 / 每次 / 循环
|
|
65
|
+
# 结束,普通顺序为空)。往回找不到时退回源码顺序里前面最近的仍然在的节点(after_label 为空);都没有时为空
|
|
66
|
+
after: str = ""
|
|
67
|
+
after_title: str = ""
|
|
68
|
+
after_label: str = ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class EdgeChange:
|
|
73
|
+
status: Literal["added", "removed"]
|
|
74
|
+
kind: str
|
|
75
|
+
label: str
|
|
76
|
+
# 两端节点在新图里的 id。removed:两端都是留下的节点(对上的或改动的),这里是它们在新图里的 id(旧图里的 id 不同,
|
|
77
|
+
# 按节点配对对应)。added:一般两端也都是留下的节点;新增的判断 / 循环 / 捕获节点的出边、新增节点的异常连线,起点是
|
|
78
|
+
# 新增节点;留下的判断进新增节点的分支,终点是新增节点
|
|
79
|
+
src: str
|
|
80
|
+
dst: str
|
|
81
|
+
# 两端节点在新图里的类型、标题(完整形式)、行号:给文本按标题写连线用
|
|
82
|
+
src_type: str = ""
|
|
83
|
+
src_title: str = ""
|
|
84
|
+
src_line: int = 0
|
|
85
|
+
dst_type: str = ""
|
|
86
|
+
dst_title: str = ""
|
|
87
|
+
dst_line: int = 0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class FunctionChange:
|
|
92
|
+
"""标题、文件:新增、改动的取新图,删除的取旧图。删除的函数不列节点;新增的函数节点全列为 added,连线只列判断 /
|
|
93
|
+
循环 / 捕获节点的出边。"""
|
|
94
|
+
|
|
95
|
+
status: Literal["added", "removed", "changed"]
|
|
96
|
+
sid: str
|
|
97
|
+
title: str
|
|
98
|
+
file: str
|
|
99
|
+
new_key: str = ""
|
|
100
|
+
old_key: str = ""
|
|
101
|
+
nodes: list[NodeChange] = field(default_factory=list) # 按源码顺序(删除的在它原来的位置)
|
|
102
|
+
edges: list[EdgeChange] = field(default_factory=list) # 先多出的(新图的顺序),再少掉的(旧图的顺序)
|
|
103
|
+
# 只有 changed 的函数会是 True:它所在的文件两次分析时内容一样(指纹相同)。流程却变了,说明不是这个函数的代码改了,
|
|
104
|
+
# 而是引擎的画法变了,或者它调用的别的文件里的函数变了(标题、解析到的目标)
|
|
105
|
+
file_same: bool = False
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass
|
|
109
|
+
class LineChange:
|
|
110
|
+
"""标题、分组:新增、改动的取新图,删除的取旧图。"""
|
|
111
|
+
|
|
112
|
+
status: Literal["added", "removed", "changed"]
|
|
113
|
+
sid: str
|
|
114
|
+
title: str
|
|
115
|
+
group: str
|
|
116
|
+
new_id: str = ""
|
|
117
|
+
functions: list[str] = field(default_factory=list) # 这条线涉及的、有变化的函数 sid(removed 的线为空)
|
|
118
|
+
tasks_added: list[str] = field(default_factory=list) # 派发树上多出的任务函数 sid(只有 changed 的线有)
|
|
119
|
+
tasks_removed: list[str] = field(default_factory=list) # 派发树上少掉的任务函数 sid(只有 changed 的线有)
|
|
120
|
+
root: str = "" # 根函数的 sid(删除的线取旧图,其余取新图)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass
|
|
124
|
+
class GraphDiff:
|
|
125
|
+
functions: dict[str, FunctionChange] = field(default_factory=dict) # 函数 sid → 变化,按 sid 排序;只列有变化的
|
|
126
|
+
lines: list[LineChange] = field(default_factory=list) # 只列有变化的,按(分组,标题)
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def empty(self) -> bool:
|
|
130
|
+
return not self.functions and not self.lines
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# ---------- 节点、连线 ----------
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _base(sid: str) -> str:
|
|
137
|
+
"""去掉区分重名的 #n。"""
|
|
138
|
+
return sid.partition("#")[0]
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _ordered(fg: FunctionGraph) -> list[Node]:
|
|
142
|
+
"""按(行,生成顺序)排的节点;开始节点最前,执行到函数末尾、未捕获异常退出最后(它们的行是 0)。"""
|
|
143
|
+
def rank(item: tuple[int, Node]) -> tuple[int, int, int]:
|
|
144
|
+
i, n = item
|
|
145
|
+
if n.sid == "start":
|
|
146
|
+
return 0, 0, i
|
|
147
|
+
if n.sid in _IMPLICIT_ENDS:
|
|
148
|
+
return 2, 0, i
|
|
149
|
+
return 1, n.line, i
|
|
150
|
+
return [n for _, n in sorted(enumerate(fg.nodes), key=rank)]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _change(status: Literal["added", "removed", "changed"], old: Node | None, new: Node | None) -> NodeChange:
|
|
154
|
+
c = NodeChange(status=status, type=(new or old).type)
|
|
155
|
+
if new is not None:
|
|
156
|
+
c.new_id, c.new_sid, c.new_line = new.id, new.sid, new.line
|
|
157
|
+
c.new_title, c.new_subtitle = new.title_full or new.title, new.subtitle_full or new.subtitle
|
|
158
|
+
if old is not None:
|
|
159
|
+
c.old_sid, c.old_line = old.sid, old.line
|
|
160
|
+
c.old_title, c.old_subtitle = old.title_full or old.title, old.subtitle_full or old.subtitle
|
|
161
|
+
return c
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _text(n: Node) -> str:
|
|
165
|
+
"""比相似用的文字:标题 + 副标题(完整形式),只取前 TEXT_LIMIT 个字。"""
|
|
166
|
+
return f"{n.title_full or n.title} {n.subtitle_full or n.subtitle}"[:TEXT_LIMIT]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _similarity(old: list[str], new: list[str], old_types: list[str], new_types: list[str]) -> list[list[bool]]:
|
|
170
|
+
"""sim[i][j]:第 i 个旧节点和第 j 个新节点类型相同、文字(old / new)相似度不低于 SIMILAR。"""
|
|
171
|
+
sim = [[False] * len(new) for _ in old]
|
|
172
|
+
for j, b in enumerate(new):
|
|
173
|
+
sm = difflib.SequenceMatcher(None, autojunk=False)
|
|
174
|
+
sm.set_seq2(b) # seq2 的预处理只做一次
|
|
175
|
+
for i, a in enumerate(old):
|
|
176
|
+
if old_types[i] != new_types[j]:
|
|
177
|
+
continue
|
|
178
|
+
if a == b:
|
|
179
|
+
sim[i][j] = True
|
|
180
|
+
continue
|
|
181
|
+
sm.set_seq1(a)
|
|
182
|
+
sim[i][j] = sm.real_quick_ratio() >= SIMILAR and sm.quick_ratio() >= SIMILAR and sm.ratio() >= SIMILAR
|
|
183
|
+
return sim
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _pair_block(old: list[Node], new: list[Node]) -> list[tuple[str, Node | None, Node | None]]:
|
|
187
|
+
"""对不上的一段:保持顺序、配上最多对相似的节点(最长公共子序列),配上的是改动,其余旧的删除、新的新增。
|
|
188
|
+
一段太大时不配,全算删除和新增:两边节点数之积超过 MAX_BLOCK_PAIRS,或两边文字总长之积超过 MAX_BLOCK_WORK
|
|
189
|
+
(逐对比相似的开销大致和它成正比)。"""
|
|
190
|
+
n, m = len(old), len(new)
|
|
191
|
+
old_texts, new_texts = [_text(o) for o in old], [_text(x) for x in new]
|
|
192
|
+
if n * m > MAX_BLOCK_PAIRS or sum(map(len, old_texts)) * sum(map(len, new_texts)) > MAX_BLOCK_WORK:
|
|
193
|
+
return [("removed", o, None) for o in old] + [("added", None, x) for x in new]
|
|
194
|
+
sim = _similarity(old_texts, new_texts, [o.type for o in old], [x.type for x in new])
|
|
195
|
+
best = [[0] * (m + 1) for _ in range(n + 1)] # best[i][j]:old[i:] 和 new[j:] 最多配上几对
|
|
196
|
+
for i in range(n - 1, -1, -1):
|
|
197
|
+
for j in range(m - 1, -1, -1):
|
|
198
|
+
best[i][j] = max(best[i + 1][j], best[i][j + 1], best[i + 1][j + 1] + 1 if sim[i][j] else 0)
|
|
199
|
+
out: list[tuple[str, Node | None, Node | None]] = []
|
|
200
|
+
i = j = 0
|
|
201
|
+
while i < n or j < m:
|
|
202
|
+
if i < n and j < m and sim[i][j] and best[i][j] == best[i + 1][j + 1] + 1:
|
|
203
|
+
out.append(("changed", old[i], new[j]))
|
|
204
|
+
i, j = i + 1, j + 1
|
|
205
|
+
elif j == m or (i < n and best[i + 1][j] >= best[i][j + 1]):
|
|
206
|
+
out.append(("removed", old[i], None))
|
|
207
|
+
i += 1
|
|
208
|
+
else:
|
|
209
|
+
out.append(("added", None, new[j]))
|
|
210
|
+
j += 1
|
|
211
|
+
return out
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _align(old: list[Node], new: list[Node]) -> list[tuple[str, Node | None, Node | None]]:
|
|
215
|
+
"""按基础 sid 对齐两个节点序列:(same | changed | removed | added, 旧节点, 新节点),按源码顺序。"""
|
|
216
|
+
a, b = [_base(n.sid) for n in old], [_base(n.sid) for n in new]
|
|
217
|
+
ops = [("equal", 0, len(a), 0, len(b))] if a == b else \
|
|
218
|
+
difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes()
|
|
219
|
+
out: list[tuple[str, Node | None, Node | None]] = []
|
|
220
|
+
for tag, i1, i2, j1, j2 in ops:
|
|
221
|
+
if tag == "equal":
|
|
222
|
+
out.extend(("same", o, n) for o, n in zip(old[i1:i2], new[j1:j2], strict=True))
|
|
223
|
+
else: # replace;delete / insert 只有一边
|
|
224
|
+
out += _pair_block(old[i1:i2], new[j1:j2])
|
|
225
|
+
return out
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
EdgeKey = tuple[str, str, str, str] # (起点,终点,kind,label),端点是新图里的 id
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class _Links:
|
|
232
|
+
"""一张函数图的连线,按起点、终点各建一份索引。"""
|
|
233
|
+
|
|
234
|
+
def __init__(self, fg: FunctionGraph) -> None:
|
|
235
|
+
self.out: dict[str, list[Edge]] = {}
|
|
236
|
+
self.into: dict[str, list[Edge]] = {}
|
|
237
|
+
for e in fg.edges:
|
|
238
|
+
self.out.setdefault(e.src, []).append(e)
|
|
239
|
+
self.into.setdefault(e.dst, []).append(e)
|
|
240
|
+
|
|
241
|
+
def reaches(self, start: str, goal: str, through: set[str]) -> bool:
|
|
242
|
+
"""从 start 出发、中间只经过 through 里的节点(可以一个都不经过),走得到 goal。"""
|
|
243
|
+
stack, seen = [start], {start}
|
|
244
|
+
while stack:
|
|
245
|
+
for e in self.out.get(stack.pop(), ()):
|
|
246
|
+
if e.dst == goal:
|
|
247
|
+
return True
|
|
248
|
+
if e.dst in through and e.dst not in seen:
|
|
249
|
+
seen.add(e.dst)
|
|
250
|
+
stack.append(e.dst)
|
|
251
|
+
return False
|
|
252
|
+
|
|
253
|
+
def explains(self, edge: Edge, src: str, dst: str, src_is_cond: bool, through: set[str]) -> bool:
|
|
254
|
+
"""另一张图里的连线 edge(两端在这张图里是 src、dst)在这张图里没有了,能不能由这张图里新增(或删除)的节点
|
|
255
|
+
through 说明:
|
|
256
|
+
1. 从 src 出发、第一步就进 through(src 是判断节点时,这一步的分支要和 edge 相同;edge 是异常连线时,这一步
|
|
257
|
+
也要是异常连线),之后只经 through 里的节点,走得到 dst——在两个留下的节点之间插进 / 删掉了节点;
|
|
258
|
+
2. 这张图里有一条从 through 里的节点 P 到 dst 的连线,kind、label 和 edge 相同,P 只经 through 里的节点走得到
|
|
259
|
+
src——一段的入口换了,例如 try 体第一句前面插了一句,异常连线改从新的第一句出发。"""
|
|
260
|
+
for e in self.out.get(src, ()):
|
|
261
|
+
if e.dst in through and (not src_is_cond or e.branch == edge.branch) \
|
|
262
|
+
and (edge.kind != "raise" or e.kind == "raise") and self.reaches(e.dst, dst, through):
|
|
263
|
+
return True
|
|
264
|
+
return any(e.src in through and (e.kind, e.label) == (edge.kind, edge.label) and self.reaches(e.src, src, through)
|
|
265
|
+
for e in self.into.get(dst, ()))
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _edge_change(status: Literal["added", "removed"], key: EdgeKey, nodes: dict[str, Node]) -> EdgeChange:
|
|
269
|
+
src, dst, kind, label = key
|
|
270
|
+
s, t = nodes[src], nodes[dst]
|
|
271
|
+
return EdgeChange(status, kind, label, src, dst, s.type, s.title_full or s.title, s.line,
|
|
272
|
+
t.type, t.title_full or t.title, t.line)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _paired_edges(fg: FunctionGraph, to_new: dict[str, str]) -> dict[EdgeKey, Edge]:
|
|
276
|
+
"""两端都配上对的连线,键的端点换成新图里的 id;按连线顺序。"""
|
|
277
|
+
out: dict[EdgeKey, Edge] = {}
|
|
278
|
+
for e in fg.edges:
|
|
279
|
+
src, dst = to_new.get(e.src), to_new.get(e.dst)
|
|
280
|
+
if src is not None and dst is not None:
|
|
281
|
+
out.setdefault((src, dst, e.kind, e.label), e)
|
|
282
|
+
return out
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _edges_with_added_end(fg: FunctionGraph, added: set[str], nodes: dict[str, Node]) -> dict[EdgeKey, EdgeChange]:
|
|
286
|
+
"""一端是新增节点、照样报成新增连线的(让人看到新的分支、新的异常落点通向哪里):
|
|
287
|
+
- 新增的判断 / 循环 / 捕获节点的出边;
|
|
288
|
+
- 新增节点的异常连线(新的 try 体入口);
|
|
289
|
+
- 留下的判断节点进新增节点的分支(新的 case、新的 else,或分支开头插进的节点)。"""
|
|
290
|
+
out: dict[EdgeKey, EdgeChange] = {}
|
|
291
|
+
for e in fg.edges:
|
|
292
|
+
src_added, dst_added = e.src in added, e.dst in added
|
|
293
|
+
if (src_added and (nodes[e.src].type in _BRANCHING or e.kind == "raise")) \
|
|
294
|
+
or (not src_added and dst_added and nodes[e.src].type == "cond" and e.branch):
|
|
295
|
+
key = (e.src, e.dst, e.kind, e.label)
|
|
296
|
+
out[key] = _edge_change("added", key, nodes)
|
|
297
|
+
return out
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _after_word(e: Edge) -> str:
|
|
301
|
+
"""连线怎么走,给删除的节点指位置用:判断的分支是 是 / 否 / case 模式(都不匹配),循环进体是"每次"、正常结束是
|
|
302
|
+
"循环结束",其余(顺序等)为空。"""
|
|
303
|
+
if e.branch == "yes":
|
|
304
|
+
return "是"
|
|
305
|
+
if e.branch == "no":
|
|
306
|
+
return "否"
|
|
307
|
+
if e.branch:
|
|
308
|
+
return e.label
|
|
309
|
+
return {"loop_each": "每次", "loop_exit": "循环结束"}.get(e.kind, "")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _after(olds: list[Node], to_new: dict[str, str], links: _Links) -> dict[str, tuple[str, str]]:
|
|
313
|
+
"""每个删除的旧节点 -> (挂在哪个仍然在的节点之后:它的新 id, 通往它的那条连线怎么走)。
|
|
314
|
+
按旧图的控制流往回找:沿入边广度优先(不看 loop_back、raise),只穿过删除的节点,到最近一层仍然在的前驱;同一层
|
|
315
|
+
有几个时取源码里最靠后的。一个都找不到(比如只有异常连线进来的捕获节点)时退回源码顺序里前面最近的仍然在的节点。"""
|
|
316
|
+
position = {n.id: i for i, n in enumerate(olds)}
|
|
317
|
+
out: dict[str, tuple[str, str]] = {}
|
|
318
|
+
last = "" # 源码顺序里前面最近的仍然在的节点(新 id)
|
|
319
|
+
for node in olds:
|
|
320
|
+
if node.id in to_new:
|
|
321
|
+
last = to_new[node.id]
|
|
322
|
+
continue
|
|
323
|
+
frontier, seen = [node.id], {node.id}
|
|
324
|
+
found: dict[str, Edge] = {} # 仍然在的前驱(旧 id)-> 从它出发、通往被删节点的连线
|
|
325
|
+
while frontier and not found:
|
|
326
|
+
step: list[str] = []
|
|
327
|
+
for x in frontier:
|
|
328
|
+
for e in links.into.get(x, ()):
|
|
329
|
+
if e.kind in ("loop_back", "raise"):
|
|
330
|
+
continue
|
|
331
|
+
if e.src in to_new:
|
|
332
|
+
found.setdefault(e.src, e)
|
|
333
|
+
elif e.src not in seen:
|
|
334
|
+
seen.add(e.src)
|
|
335
|
+
step.append(e.src)
|
|
336
|
+
frontier = step
|
|
337
|
+
if found:
|
|
338
|
+
best = max(found, key=position.__getitem__)
|
|
339
|
+
out[node.id] = (to_new[best], _after_word(found[best]))
|
|
340
|
+
else:
|
|
341
|
+
out[node.id] = (last, "")
|
|
342
|
+
return out
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _diff_function(old: FunctionGraph, new: FunctionGraph) -> tuple[list[NodeChange], list[EdgeChange]]:
|
|
346
|
+
olds = _ordered(old)
|
|
347
|
+
pairs = _align(olds, _ordered(new))
|
|
348
|
+
to_new = {o.id: n.id for status, o, n in pairs if status in ("same", "changed")}
|
|
349
|
+
to_old = {n_id: o_id for o_id, n_id in to_new.items()}
|
|
350
|
+
added_ids = {n.id for status, _, n in pairs if status == "added"}
|
|
351
|
+
removed_ids = {o.id for status, o, _ in pairs if status == "removed"}
|
|
352
|
+
by_id = {n.id: n for n in new.nodes}
|
|
353
|
+
old_links, new_links = _Links(old), _Links(new)
|
|
354
|
+
after = _after(olds, to_new, old_links)
|
|
355
|
+
nodes = []
|
|
356
|
+
for status, o, n in pairs:
|
|
357
|
+
if status == "same":
|
|
358
|
+
continue
|
|
359
|
+
c = _change(status, o, n)
|
|
360
|
+
if status == "removed" and after[o.id][0]:
|
|
361
|
+
c.after, c.after_label = after[o.id]
|
|
362
|
+
c.after_title = by_id[c.after].title_full or by_id[c.after].title
|
|
363
|
+
nodes.append(c)
|
|
364
|
+
old_edges, new_edges = _paired_edges(old, to_new), _paired_edges(new, {i: i for i in to_new.values()})
|
|
365
|
+
changes = _edges_with_added_end(new, added_ids, by_id)
|
|
366
|
+
for key, e in new_edges.items():
|
|
367
|
+
if key not in old_edges and not old_links.explains(
|
|
368
|
+
e, to_old[key[0]], to_old[key[1]], by_id[key[0]].type == "cond", removed_ids):
|
|
369
|
+
changes[key] = _edge_change("added", key, by_id)
|
|
370
|
+
order = {(e.src, e.dst, e.kind, e.label): i for i, e in enumerate(new.edges)}
|
|
371
|
+
edges = sorted(changes.values(), key=lambda c: order[(c.src, c.dst, c.kind, c.label)])
|
|
372
|
+
edges += [_edge_change("removed", key, by_id) for key, e in old_edges.items()
|
|
373
|
+
if key not in new_edges and not new_links.explains(e, key[0], key[1], by_id[key[0]].type == "cond",
|
|
374
|
+
added_ids)]
|
|
375
|
+
return nodes, edges
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
# ---------- 函数、功能线 ----------
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _sids(graph: ProjectGraph, keys: list[str]) -> list[str]:
|
|
382
|
+
return list(dict.fromkeys(graph.functions[k].sid for k in keys if k in graph.functions))
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _tasks(root: LineTask) -> list[str]:
|
|
386
|
+
"""派发树上的任务 key,先序,不重复。"""
|
|
387
|
+
out: dict[str, None] = {}
|
|
388
|
+
stack = [root]
|
|
389
|
+
while stack:
|
|
390
|
+
t = stack.pop()
|
|
391
|
+
out[t.function] = None
|
|
392
|
+
stack.extend(reversed(t.children))
|
|
393
|
+
return list(out)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _diff_functions(old: ProjectGraph, new: ProjectGraph) -> dict[str, FunctionChange]:
|
|
397
|
+
out: dict[str, FunctionChange] = {}
|
|
398
|
+
for sid in sorted(old.sids.keys() | new.sids.keys()):
|
|
399
|
+
o, n = old.functions.get(old.sids.get(sid, "")), new.functions.get(new.sids.get(sid, ""))
|
|
400
|
+
if n is not None and o is None:
|
|
401
|
+
by_id = {x.id: x for x in n.nodes}
|
|
402
|
+
out[sid] = FunctionChange("added", sid, n.title, n.file, new_key=n.key,
|
|
403
|
+
nodes=[_change("added", None, x) for x in _ordered(n)],
|
|
404
|
+
edges=list(_edges_with_added_end(n, set(by_id), by_id).values()))
|
|
405
|
+
elif o is not None and n is None:
|
|
406
|
+
out[sid] = FunctionChange("removed", sid, o.title, o.file, old_key=o.key)
|
|
407
|
+
elif o is not None and n is not None:
|
|
408
|
+
nodes, edges = _diff_function(o, n)
|
|
409
|
+
if nodes or edges:
|
|
410
|
+
digest = new.file_hashes.get(n.file)
|
|
411
|
+
same = o.file == n.file and digest is not None and old.file_hashes.get(o.file) == digest
|
|
412
|
+
out[sid] = FunctionChange("changed", sid, n.title, n.file, n.key, o.key, nodes, edges, file_same=same)
|
|
413
|
+
return out
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _root_sid(graph: ProjectGraph, line: FlowLine) -> str:
|
|
417
|
+
fg = graph.functions.get(line.root.function)
|
|
418
|
+
return fg.sid if fg is not None else ""
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _diff_lines(old: ProjectGraph, new: ProjectGraph, changed: dict[str, FunctionChange]) -> list[LineChange]:
|
|
422
|
+
olds, news = {ln.sid: ln for ln in old.lines}, {ln.sid: ln for ln in new.lines}
|
|
423
|
+
out: list[LineChange] = []
|
|
424
|
+
for sid in olds.keys() | news.keys():
|
|
425
|
+
o, n = olds.get(sid), news.get(sid)
|
|
426
|
+
if n is None:
|
|
427
|
+
out.append(LineChange("removed", sid, o.title, o.group, root=_root_sid(old, o)))
|
|
428
|
+
continue
|
|
429
|
+
involved = dict.fromkeys(_sids(new, line_functions(new, n)))
|
|
430
|
+
if o is not None:
|
|
431
|
+
involved.update(dict.fromkeys(_sids(old, line_functions(old, o))))
|
|
432
|
+
functions = [s for s in involved if s in changed]
|
|
433
|
+
if o is None:
|
|
434
|
+
out.append(LineChange("added", sid, n.title, n.group, n.id, functions, root=_root_sid(new, n)))
|
|
435
|
+
continue
|
|
436
|
+
new_tasks, old_tasks = _sids(new, _tasks(n.root)), _sids(old, _tasks(o.root))
|
|
437
|
+
new_set, old_set = set(new_tasks), set(old_tasks)
|
|
438
|
+
added = [s for s in new_tasks if s not in old_set]
|
|
439
|
+
removed = [s for s in old_tasks if s not in new_set]
|
|
440
|
+
if functions or added or removed:
|
|
441
|
+
out.append(LineChange("changed", sid, n.title, n.group, n.id, functions, added, removed,
|
|
442
|
+
_root_sid(new, n)))
|
|
443
|
+
out.sort(key=lambda c: (c.group, c.title, c.sid))
|
|
444
|
+
return out
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def diff_graphs(old: ProjectGraph, new: ProjectGraph) -> GraphDiff:
|
|
448
|
+
"""old 到 new 流程变了什么。两张图要分析的是同一个目录(函数 sid 里的路径相对分析的目录)。"""
|
|
449
|
+
functions = _diff_functions(old, new)
|
|
450
|
+
return GraphDiff(functions=functions, lines=_diff_lines(old, new, functions))
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
# ---------- JSON ----------
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def diff_to_json(d: GraphDiff) -> dict:
|
|
457
|
+
"""dataclass 原样转字典,空字段照留;顶层另带 "version"。"""
|
|
458
|
+
return {"version": DIFF_VERSION, **asdict(d)}
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
class DiffFormatError(ValueError):
|
|
462
|
+
"""存下来的流程差异格式不对(缺字段、类型不对)。信息是中文。"""
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _fits(value: object, tp: object) -> bool:
|
|
466
|
+
"""value 是不是 tp(字段的类型注解)要的值:Literal 的取值、str、int(不含 bool)、list(list[str] 逐项看)。"""
|
|
467
|
+
origin = get_origin(tp)
|
|
468
|
+
if origin is Literal:
|
|
469
|
+
return value in get_args(tp)
|
|
470
|
+
if origin is list:
|
|
471
|
+
return isinstance(value, list) and (get_args(tp)[0] is not str or all(isinstance(x, str) for x in value))
|
|
472
|
+
if tp is bool:
|
|
473
|
+
return type(value) is bool
|
|
474
|
+
if tp is int:
|
|
475
|
+
return type(value) is int
|
|
476
|
+
if tp is str:
|
|
477
|
+
return isinstance(value, str)
|
|
478
|
+
return True
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _load(cls, data: object, where: str):
|
|
482
|
+
"""按 dataclass cls 的字段读一个 JSON 对象:不认识的字段忽略;缺了没有默认值的字段、类型不对时抛 DiffFormatError。"""
|
|
483
|
+
if not isinstance(data, dict):
|
|
484
|
+
raise DiffFormatError(f"流程差异的格式不对:{where} 应该是对象")
|
|
485
|
+
hints = get_type_hints(cls)
|
|
486
|
+
values = {}
|
|
487
|
+
for f in fields(cls):
|
|
488
|
+
if f.name not in data:
|
|
489
|
+
if f.default is MISSING and f.default_factory is MISSING:
|
|
490
|
+
raise DiffFormatError(f"流程差异的格式不对:{where} 缺少 {f.name}")
|
|
491
|
+
continue
|
|
492
|
+
value = data[f.name]
|
|
493
|
+
if not _fits(value, hints[f.name]):
|
|
494
|
+
shown = json.dumps(value, ensure_ascii=False)[:80]
|
|
495
|
+
raise DiffFormatError(f"流程差异的格式不对:{where}.{f.name} 的值不对:{shown}")
|
|
496
|
+
values[f.name] = value
|
|
497
|
+
return cls(**values)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def diff_from_json(data: dict) -> GraphDiff:
|
|
501
|
+
"""读回 diff_to_json 的结果。不认识的字段忽略,缺的可选字段取默认值;不是对象、版本不对、缺字段、类型不对时抛
|
|
502
|
+
ValueError(中文说明;格式不对时是它的子类 DiffFormatError)。"""
|
|
503
|
+
version = data.get("version") if isinstance(data, dict) else None
|
|
504
|
+
if version != DIFF_VERSION:
|
|
505
|
+
raise ValueError(f"不是版本 {DIFF_VERSION} 的流程差异(顶层不是对象,或 version 是 {version!r})")
|
|
506
|
+
functions, lines = data.get("functions"), data.get("lines")
|
|
507
|
+
if not isinstance(functions, dict) or not isinstance(lines, list):
|
|
508
|
+
raise DiffFormatError("流程差异的格式不对:functions 应该是对象,lines 应该是列表")
|
|
509
|
+
|
|
510
|
+
def function(sid: str, f: object) -> FunctionChange:
|
|
511
|
+
fc = _load(FunctionChange, f, f"functions[{sid}]")
|
|
512
|
+
fc.nodes = [_load(NodeChange, c, f"functions[{sid}].nodes[{i}]") for i, c in enumerate(fc.nodes)]
|
|
513
|
+
fc.edges = [_load(EdgeChange, e, f"functions[{sid}].edges[{i}]") for i, e in enumerate(fc.edges)]
|
|
514
|
+
return fc
|
|
515
|
+
|
|
516
|
+
return GraphDiff(
|
|
517
|
+
functions={sid: function(sid, f) for sid, f in functions.items()},
|
|
518
|
+
lines=[_load(LineChange, ln, f"lines[{i}]") for i, ln in enumerate(lines)],
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
# ---------- 给 AI 看的文本 ----------
|
|
523
|
+
|
|
524
|
+
_STATUS = {"added": "新增", "removed": "删除", "changed": "改动"}
|
|
525
|
+
_TYPE = {"start": "开始", "step": "步骤", "cond": "判断", "loop": "循环", "catch": "捕获", "end": "结局"}
|
|
526
|
+
_KIND = {"next": "顺序", "yes": "是", "no": "否", "case": "分支", "loop_each": "进入循环体", "loop_back": "回到循环",
|
|
527
|
+
"loop_exit": "循环结束", "break": "跳出循环", "raise": "异常", "finally": "进入 finally"}
|
|
528
|
+
_IMPLICIT = ("start", "end:uncaught") # 每个函数都有的隐含节点,文本里不列
|
|
529
|
+
MAX_TEXT_LINES = 30 # 文本里完整列出的有变化的功能线
|
|
530
|
+
MAX_TEXT_ITEMS = 40 # 每个函数完整列出的节点 + 连线
|
|
531
|
+
MAX_TEXT_CHARS = 20_000 # 整段文本的硬上限(含最后那句提示)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _more(count: int, unit: str) -> str:
|
|
535
|
+
"""超出上限时的一行提示;unit 和数的东西一致:条功能线、处(节点 + 连线)、行(整段截断)。"""
|
|
536
|
+
return f"…还有 {count} {unit}未列出(用 flow 参数只看一条功能线)"
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _label(title: str, subtitle: str) -> str:
|
|
540
|
+
return f"「{title}」" + (f"({subtitle})" if subtitle and subtitle != title else "")
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _loc(file: str, line: int) -> str:
|
|
544
|
+
return f"{file}:{line}" if line else file
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _node_text(c: NodeChange, file: str) -> str:
|
|
548
|
+
kind = _TYPE.get(c.type, c.type)
|
|
549
|
+
if c.status == "added":
|
|
550
|
+
return f"{kind}{_label(c.new_title, c.new_subtitle)} {_loc(file, c.new_line)}"
|
|
551
|
+
if c.status == "removed":
|
|
552
|
+
where = f"(原来在「{c.after_title}」之后{',' + c.after_label if c.after_label else ''})" if c.after_title else ""
|
|
553
|
+
return f"{kind}{_label(c.old_title, c.old_subtitle)} {_loc(file, c.old_line)}{where}"
|
|
554
|
+
if (c.old_title, c.old_subtitle) == (c.new_title, c.new_subtitle):
|
|
555
|
+
return f"{kind}{_label(c.new_title, c.new_subtitle)}(标题没变,语句变了) " \
|
|
556
|
+
f"{_loc(file, c.old_line)} → {_loc(file, c.new_line)}"
|
|
557
|
+
return f"{kind}{_label(c.old_title, c.old_subtitle)} → {_label(c.new_title, c.new_subtitle)} " \
|
|
558
|
+
f"{_loc(file, c.new_line)}"
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _end(type_: str, title: str, line: int) -> str:
|
|
562
|
+
"""连线一端:类型「标题」L行(隐含节点没有行号)。"""
|
|
563
|
+
return f"{_TYPE.get(type_, type_)}「{title}」" + (f"L{line}" if line else "")
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _word(e: EdgeChange) -> str:
|
|
567
|
+
"""连线怎么走:是 / 否、case 的模式、顺序、回到循环 是……"""
|
|
568
|
+
if e.kind == "case":
|
|
569
|
+
return e.label
|
|
570
|
+
word = _KIND.get(e.kind, e.kind)
|
|
571
|
+
return f"{word} {e.label}" if e.label else word
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _edge_text(e: EdgeChange) -> str:
|
|
575
|
+
return f"连线{'新增' if e.status == 'added' else '删除'}:{_end(e.src_type, e.src_title, e.src_line)} " \
|
|
576
|
+
f"—{_word(e)}→ {_end(e.dst_type, e.dst_title, e.dst_line)}"
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def engine_note(d: GraphDiff, engines: tuple[str, str] | None) -> str:
|
|
580
|
+
"""两次分析的引擎标识(基准那次, 最新一次;见 engineid)不一样时的一句提醒:有变化的函数里几个所在的文件没改——它们
|
|
581
|
+
的变化不是代码改动引起的。引擎没变、没有函数级的变化时空串。"""
|
|
582
|
+
if engines is None or engines[0] == engines[1]:
|
|
583
|
+
return ""
|
|
584
|
+
changed = [fc for fc in d.functions.values() if fc.status == "changed"]
|
|
585
|
+
same = sum(1 for fc in changed if fc.file_same)
|
|
586
|
+
head = f"⚠ 两次分析之间引擎也变了({engines[0]} → {engines[1]})"
|
|
587
|
+
if not changed:
|
|
588
|
+
return head + ":新增、删除的函数是代码改动,其余变化可能有一部分是引擎的画法变了引起的。"
|
|
589
|
+
if same == 0:
|
|
590
|
+
return head + f":流程有改动的 {len(changed)} 个函数所在的文件也都改过,分不出哪些变化是引擎引起的,对照代码的改动看。"
|
|
591
|
+
which = "所在的文件内容都没变" if same == len(changed) else f"里 {same} 个所在的文件内容没变(下面标着「文件没改」)"
|
|
592
|
+
return (head + f":流程有改动的 {len(changed)} 个函数{which}——这些不是代码改动,是引擎的画法变了引起的"
|
|
593
|
+
"(少数情况是它调用的别的文件里的函数改了)。不要把它们当成这次改代码造成的流程变化。")
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
MAX_BRIEF_OUTCOMES = 6 # 只写个数的那一行里最多写出几个结局的标题
|
|
597
|
+
MAX_BRIEF_NAMES = 12 # "另有新增的函数"那一行里最多列几个标题
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def _counts(fc: FunctionChange) -> str:
|
|
601
|
+
"""一个函数的变化缩成一句。新增的函数:各类节点的个数和结局的标题;改动的函数:节点新增 / 删除 / 改动各几个、
|
|
602
|
+
连线变了几条。"""
|
|
603
|
+
nodes = [c for c in fc.nodes if (c.new_sid or c.old_sid) not in _IMPLICIT]
|
|
604
|
+
if fc.status == "added":
|
|
605
|
+
parts = [f"{_TYPE[t]} {n}" for t in ("step", "cond", "loop", "catch", "end")
|
|
606
|
+
if (n := sum(1 for c in nodes if c.type == t))]
|
|
607
|
+
ends = [c.new_title for c in nodes if c.type == "end"]
|
|
608
|
+
more = f" 等 {len(ends)} 个" if len(ends) > MAX_BRIEF_OUTCOMES else ""
|
|
609
|
+
return "、".join(parts) + ("(" + "".join(f"「{t}」" for t in ends[:MAX_BRIEF_OUTCOMES]) + more + ")" if ends else "")
|
|
610
|
+
parts = [f"节点{_STATUS[st]} {n}" for st in ("added", "removed", "changed") if (n := sum(1 for c in nodes if c.status == st))]
|
|
611
|
+
return "、".join(parts + ([f"连线变化 {len(fc.edges)}"] if fc.edges else []))
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _function_text(fc: FunctionChange, tag: bool = False, brief: bool = False) -> list[str]:
|
|
615
|
+
"""一个函数的变化:节点按 新增 / 删除 / 改动 分组(新增的判断 / 循环 / 捕获节点下面列它的出边),其余连线在
|
|
616
|
+
"连线"下面;节点 + 连线最多列 MAX_TEXT_ITEMS 处。brief:只写一行,节点、连线不逐个列(见 _counts)。"""
|
|
617
|
+
key = fc.new_key or fc.old_key
|
|
618
|
+
where = _loc(fc.file, parse_key(key)[2]) if key else fc.file
|
|
619
|
+
if fc.status == "removed":
|
|
620
|
+
return [f"### 函数 [删除] {fc.title} {fc.sid}(原在 {where})"]
|
|
621
|
+
out = [f"### 函数 [{_STATUS[fc.status]}] {fc.title} {fc.sid} {where}{' 〔文件没改:引擎变化引起〕' if tag and fc.file_same else ''}"]
|
|
622
|
+
if brief:
|
|
623
|
+
return [out[0] + (f" ——{counts}" if (counts := _counts(fc)) else "")]
|
|
624
|
+
added = {c.new_id for c in fc.nodes if c.status == "added"}
|
|
625
|
+
under: dict[str, list[EdgeChange]] = {} # 新增节点的 id -> 它的出边
|
|
626
|
+
others: list[EdgeChange] = []
|
|
627
|
+
for e in fc.edges:
|
|
628
|
+
(under.setdefault(e.src, []) if e.status == "added" and e.src in added else others).append(e)
|
|
629
|
+
items: list[tuple[str, str]] = [] # (小标题, 行)
|
|
630
|
+
for status in ("added", "removed", "changed"):
|
|
631
|
+
for c in fc.nodes:
|
|
632
|
+
if c.status == status and (c.new_sid or c.old_sid) not in _IMPLICIT:
|
|
633
|
+
items.append((_STATUS[status], f" - {_node_text(c, fc.file)}"))
|
|
634
|
+
items += [(_STATUS[status], f" {_word(e)} → {_end(e.dst_type, e.dst_title, e.dst_line)}")
|
|
635
|
+
for e in (under.get(c.new_id, ()) if status == "added" else ())]
|
|
636
|
+
items += [("连线", f" - {_edge_text(e)}") for e in others]
|
|
637
|
+
heading = ""
|
|
638
|
+
for group, row in items[:MAX_TEXT_ITEMS]:
|
|
639
|
+
if group != heading:
|
|
640
|
+
out.append(group)
|
|
641
|
+
heading = group
|
|
642
|
+
out.append(row)
|
|
643
|
+
if len(items) > MAX_TEXT_ITEMS:
|
|
644
|
+
out.append(_more(len(items) - MAX_TEXT_ITEMS, "处"))
|
|
645
|
+
return out
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _capped(rows: list[str]) -> str:
|
|
649
|
+
"""整段不超过 MAX_TEXT_CHARS:超出时在行边界截断,最后一行说还有多少行(不算空行)没列出。"""
|
|
650
|
+
text = "\n".join(rows)
|
|
651
|
+
if len(text) <= MAX_TEXT_CHARS:
|
|
652
|
+
return text
|
|
653
|
+
room = MAX_TEXT_CHARS - len(_more(len(rows), "行")) - 1
|
|
654
|
+
kept: list[str] = []
|
|
655
|
+
size = -1 # 第一行前面没有换行符
|
|
656
|
+
for row in rows:
|
|
657
|
+
if size + 1 + len(row) > room:
|
|
658
|
+
break
|
|
659
|
+
size += 1 + len(row)
|
|
660
|
+
kept.append(row)
|
|
661
|
+
return "\n".join([*kept, _more(sum(1 for row in rows[len(kept):] if row.strip()), "行")])
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def _line_functions(ln: LineChange, functions: dict[str, FunctionChange]) -> list[str]:
|
|
665
|
+
"""文本里列在这条线下面的函数 sid:有变化的线是它涉及的有变化的函数;删除的线是它的根函数(有变化时)。"""
|
|
666
|
+
if ln.status != "removed":
|
|
667
|
+
return ln.functions
|
|
668
|
+
return [ln.root] if ln.root in functions else []
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def diff_text(d: GraphDiff, *, line_sid: str | None = None, engines: tuple[str, str] | None = None,
|
|
672
|
+
brief: Literal["", "added", "all"] = "") -> str:
|
|
673
|
+
"""给 AI 看的中文文本:按有变化的功能线、再按函数分组,每个节点带文件:行号(新增、改动的是本次分析的行号,删除的
|
|
674
|
+
是上一次的),连线写两端节点的标题和行号。删除的线下面列它的根函数。line_sid 给出时只说这条线。没有变化时是一句话。
|
|
675
|
+
上限:完整列出前 MAX_TEXT_LINES 条线、每个函数前 MAX_TEXT_ITEMS 处(节点 + 连线),整段不超过 MAX_TEXT_CHARS 字;
|
|
676
|
+
超出的部分用一行"…还有 N 条功能线 / 处 / 行未列出"带过。同一个函数在几条线里出现时只详细列一次,之后写"同上:函数
|
|
677
|
+
sid"。engines:(基准那次, 最新一次)的引擎标识,不一样时开头加一句提醒(engine_note),所在文件没改的函数标出来。
|
|
678
|
+
brief:哪些函数只写一行、不逐个列节点和连线(见 _counts)——"added" 是新增的函数(刚写出来的,写的人知道里面有什么),
|
|
679
|
+
"all" 是全部;默认都逐个列。brief 时新增的函数里只有功能线的根函数单独一行,别的并成一行标题。"""
|
|
680
|
+
note = engine_note(d, engines)
|
|
681
|
+
tag = bool(note)
|
|
682
|
+
|
|
683
|
+
folded: set[str] = set() # 已经并进"另有新增的函数"那一行的函数 sid
|
|
684
|
+
|
|
685
|
+
def rows(fcs: list[FunctionChange], root: str = "") -> list[str]:
|
|
686
|
+
"""几个函数的变化。brief 时,新增的函数里只有功能线的根函数(root)单独写一行,其余的(它用到的步骤、判断函数)
|
|
687
|
+
并成一行只列标题;同一个函数在几条线里出现时只详细列一次,之后写"同上"(并进一行的不再重复)。"""
|
|
688
|
+
got: list[str] = []
|
|
689
|
+
names: list[str] = []
|
|
690
|
+
for fc in fcs:
|
|
691
|
+
if brief and fc.status == "added" and fc.sid != root:
|
|
692
|
+
if fc.sid not in folded:
|
|
693
|
+
folded.add(fc.sid)
|
|
694
|
+
names.append(fc.title)
|
|
695
|
+
elif fc.sid in shown:
|
|
696
|
+
got.append(f"### 同上:{fc.sid}")
|
|
697
|
+
else:
|
|
698
|
+
shown.add(fc.sid)
|
|
699
|
+
got += _function_text(fc, tag, brief == "all" or (brief == "added" and fc.status == "added"))
|
|
700
|
+
if names:
|
|
701
|
+
more = f" 等 {len(names)} 个" if len(names) > MAX_BRIEF_NAMES else ""
|
|
702
|
+
got.append(f"另有新增的函数 {len(names)} 个(步骤、判断函数等):{'、'.join(names[:MAX_BRIEF_NAMES])}{more}")
|
|
703
|
+
return got
|
|
704
|
+
if line_sid is not None:
|
|
705
|
+
lines = [ln for ln in d.lines if ln.sid == line_sid]
|
|
706
|
+
if not lines:
|
|
707
|
+
return f"功能线 {line_sid} 的流程没有变化"
|
|
708
|
+
out = []
|
|
709
|
+
else:
|
|
710
|
+
if d.empty:
|
|
711
|
+
return "流程没有变化"
|
|
712
|
+
lines = d.lines
|
|
713
|
+
out = [f"流程有变化:{len(d.lines)} 条功能线、{len(d.functions)} 个函数。"]
|
|
714
|
+
if not brief or any(fc.status != "added" for fc in d.functions.values()) and brief != "all":
|
|
715
|
+
out.append("新增、改动的节点给本次分析的行号,删除的给拿来比的那次(较早的)分析的行号;连线两端是本次分析的节点。")
|
|
716
|
+
if note:
|
|
717
|
+
out.append(note)
|
|
718
|
+
shown: set[str] = set()
|
|
719
|
+
for ln in lines[:MAX_TEXT_LINES]:
|
|
720
|
+
out += ["", f"## 功能线 [{_STATUS[ln.status]}] {ln.title}({ln.group}) {ln.sid}"]
|
|
721
|
+
if ln.tasks_added:
|
|
722
|
+
out.append("派发的任务多了:" + "、".join(ln.tasks_added))
|
|
723
|
+
if ln.tasks_removed:
|
|
724
|
+
out.append("派发的任务少了:" + "、".join(ln.tasks_removed))
|
|
725
|
+
out += rows([d.functions[sid] for sid in _line_functions(ln, d.functions) if sid in d.functions], ln.root)
|
|
726
|
+
if len(lines) > MAX_TEXT_LINES:
|
|
727
|
+
out += ["", _more(len(lines) - MAX_TEXT_LINES, "条功能线")]
|
|
728
|
+
on_lines = {sid for ln in d.lines for sid in _line_functions(ln, d.functions)}
|
|
729
|
+
rest = [fc for sid, fc in d.functions.items() if sid not in on_lines] if line_sid is None else []
|
|
730
|
+
if rest:
|
|
731
|
+
out += ["", "## 其他有变化的函数(不在任何有变化的功能线上)"]
|
|
732
|
+
out += rows(rest)
|
|
733
|
+
return _capped(out)
|