pystepmap 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-0.1.0.dist-info/METADATA +54 -0
- pystepmap-0.1.0.dist-info/RECORD +26 -0
- pystepmap-0.1.0.dist-info/WHEEL +4 -0
- pystepmap-0.1.0.dist-info/entry_points.txt +2 -0
- pystepmap-0.1.0.dist-info/licenses/LICENSE +21 -0
- pystepmap_server/__init__.py +3 -0
- pystepmap_server/api.py +890 -0
- pystepmap_server/app.py +151 -0
- pystepmap_server/cli.py +138 -0
- pystepmap_server/flows.py +542 -0
- pystepmap_server/live.py +151 -0
- pystepmap_server/locks.py +139 -0
- pystepmap_server/mcp_server.py +216 -0
- pystepmap_server/mcp_tools.py +1901 -0
- pystepmap_server/procinfo.py +61 -0
- pystepmap_server/requirements_view.py +63 -0
- pystepmap_server/runner.py +673 -0
- pystepmap_server/shared.py +198 -0
- pystepmap_server/sources.py +126 -0
- pystepmap_server/status.py +116 -0
- pystepmap_server/store.py +1091 -0
- pystepmap_server/testflows.py +648 -0
- pystepmap_server/web/assets/index-CkPpOJq9.js +1748 -0
- pystepmap_server/web/assets/index-NTWdqvqI.css +1 -0
- pystepmap_server/web/index.html +14 -0
- pystepmap_server/worker.py +303 -0
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
"""平台的四条流程:添加项目、重新分析、删除项目、标记流程变化已看过。平台服务(api.py)和 MCP 都走这里。第五条
|
|
2
|
+
"运行测试并核对"在 testflows.py:它要执行项目代码(runner.py),单独放一个模块,只有平台接口导入它;这里不导入
|
|
3
|
+
runner,MCP、分析子进程导入这个模块也带不进执行项目代码的那条路。
|
|
4
|
+
|
|
5
|
+
按 flow-style 写(.claude/skills/flow-style/SKILL.md):编排函数只写走向——先后调用哪些步骤、按哪个判断分支、以什么
|
|
6
|
+
结局结束;读目录、读写数据库、调用引擎、标记正在分析这些干活的事都在步骤里,判断函数只看步骤的结果。
|
|
7
|
+
|
|
8
|
+
每个流程返回 outcome(...):kind 是 "ok" 或 "failed"。failed 带 reason(给用户看的中文)和 code,接口层按 code 选状态码:
|
|
9
|
+
|
|
10
|
+
invalid(目录不可用)、config(分析配置不合法)、
|
|
11
|
+
no_command(没有填测试命令,testflows) → 400
|
|
12
|
+
duplicate(目录已经添加过)、overlap(和已添加的项目重叠)、
|
|
13
|
+
busy(这个项目正在分析或运行测试——测试运行拿同一把锁)、
|
|
14
|
+
moved(要标为看过的那次已经不是最新一次)、
|
|
15
|
+
confirm(测试命令还没确认过,testflows) → 409
|
|
16
|
+
not_found(项目不存在) → 404
|
|
17
|
+
analysis(引擎出错)、storage(数据库读写失败)、
|
|
18
|
+
prepare(准备运行的临时文件写不了,testflows) → 500
|
|
19
|
+
timeout(分析超时,已中止) → 504
|
|
20
|
+
|
|
21
|
+
分析在子进程里跑(worker.run_in_subprocess,当前目录是数据目录 store.path.parent),超过 PYSTEPMAP_ANALYZE_TIMEOUT 秒
|
|
22
|
+
(默认 120)就杀掉;测试给了 analyzer 时在本进程里跑。
|
|
23
|
+
|
|
24
|
+
同一个项目的分析互斥:本进程里记着哪些项目正在分析(按数据库文件和项目 id),另外拿项目的文件锁(locks.py,
|
|
25
|
+
<数据目录>/locks/<项目 id>.lock),挡住别的进程(pystepmap mcp 和 pystepmap serve 共用一个数据目录);分析期间再来一次
|
|
26
|
+
直接返回"正在分析"。标记从运行引擎一直拿到新的分析存好、旧的清理完:别的进程看到 analyzing 变假时,最新一次一定已经
|
|
27
|
+
是新结果;比较时用的"上一次"在保存前不会被别人换掉或清理掉。"标记流程变化已看过"拿同一把锁,不会插进比较和保存
|
|
28
|
+
之间。流程里不用 try … finally(图上每个结局都是终点):拿到标记之后的每个结局前都先调用"取消正在分析的标记";
|
|
29
|
+
拿着标记的步骤被 Exception 以外的异常(Ctrl+C 等)打断时,由步骤自己取消标记再往外抛(clear_mark_if_aborted)。
|
|
30
|
+
|
|
31
|
+
保存一次重新分析之前先定这次的对比基准(base_id)和流程差异(diff)(compare_with_previous)。对比基准只在"标为已看"
|
|
32
|
+
时移动(R1b):"有未看的流程变化"是上次标为已看以来(没标过就是第一次分析以来)的全部变化,后面的分析不会把前面
|
|
33
|
+
没看的变化挤掉。设上一次分析是 P:
|
|
34
|
+
- 没有 P:都没有;
|
|
35
|
+
- 图和 P 逐字节相同:沿用 P 的基准、差异和"看过的状态"记号;
|
|
36
|
+
- P 有对比基准 B(B 还在库里):基准仍是 B,差异重新算 B 到这次(行号、节点 id 都变了,不能照抄 P 的);为空时(改回去了)
|
|
37
|
+
基准仍是 B、没有差异;
|
|
38
|
+
- P 没有对比基准(第一次分析、标为已看之后,或者之后一直没改流程):和 P 比——有变化,基准就是 P;没变化,没有基准,
|
|
39
|
+
P 是"看过的状态"时这次接着带这个记号;
|
|
40
|
+
- 读不出旧图、算差异出错:记日志,按没有基准保存,不让这次分析失败。
|
|
41
|
+
"标记流程变化已看过"清掉最新一次的差异,并把它记成"看过的状态"(存成以自己为基准,对外报成没有基准,见
|
|
42
|
+
Store.clear_base):/diff 据此说对比基准是"上次标为已看时"还是"第一次分析"。B 被旧版本的服务清理掉了时当作 P 没有基准。
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import functools
|
|
48
|
+
import hashlib
|
|
49
|
+
import logging
|
|
50
|
+
import os
|
|
51
|
+
import threading
|
|
52
|
+
from collections.abc import Iterator
|
|
53
|
+
from contextlib import contextmanager
|
|
54
|
+
from pathlib import Path
|
|
55
|
+
|
|
56
|
+
from pystepkit import condition, outcome, step, workflow
|
|
57
|
+
from pystepmap.config import ConfigError, parse_config
|
|
58
|
+
from pystepmap.diff import diff_graphs, diff_to_json
|
|
59
|
+
from pystepmap.model import from_json
|
|
60
|
+
|
|
61
|
+
from .locks import project_locked, remove_lock, try_lock_project, unlock_project
|
|
62
|
+
from .shared import identity
|
|
63
|
+
from .sources import root_problem
|
|
64
|
+
from .store import (
|
|
65
|
+
DuplicateRootError,
|
|
66
|
+
NewAnalysis,
|
|
67
|
+
OverlapRootError,
|
|
68
|
+
ProjectMissingError,
|
|
69
|
+
Store,
|
|
70
|
+
StoreError,
|
|
71
|
+
)
|
|
72
|
+
from .worker import Analyzer, analyze_directory, analyze_timeout, run_in_subprocess
|
|
73
|
+
|
|
74
|
+
logger = logging.getLogger(__name__)
|
|
75
|
+
|
|
76
|
+
KEEP_ANALYSES = 5 # 每个项目最多保留最近几次分析(另外留最新一次的对比基准那次,见 Store.prune_analyses)
|
|
77
|
+
# 标记里的 title、group 要写成字面量:引擎只认字面量,写成常量名时图上取不到(分组会变成默认的"后台任务")
|
|
78
|
+
|
|
79
|
+
_busy: set[tuple[str, str]] = set() # 本进程里正在分析的 (数据库文件, 项目 id)
|
|
80
|
+
_busy_lock = threading.Lock()
|
|
81
|
+
_add_lock = threading.Lock() # 同一进程里的"保存新项目"排队
|
|
82
|
+
|
|
83
|
+
_NO_BASE = {"base_id": None, "diff": None, "acknowledged": False}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ---------- 普通函数:步骤共用的计算 ----------
|
|
87
|
+
|
|
88
|
+
def is_analyzing(store: Store, project_id: str) -> bool:
|
|
89
|
+
"""这个项目此刻有没有一次分析在进行:本进程在分析,或者别的进程(MCP、另一个服务)拿着它的分析锁。"""
|
|
90
|
+
with _busy_lock:
|
|
91
|
+
if (str(store.path), project_id) in _busy:
|
|
92
|
+
return True
|
|
93
|
+
return project_locked(store.path.parent, project_id)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def clear_mark(mark: dict | None) -> None:
|
|
97
|
+
"""取消"正在分析"的标记、释放项目锁。可以重复调用(只释放一次)。"""
|
|
98
|
+
if mark is None:
|
|
99
|
+
return
|
|
100
|
+
with _busy_lock:
|
|
101
|
+
if not mark["marked"]:
|
|
102
|
+
return
|
|
103
|
+
mark["marked"] = False
|
|
104
|
+
_busy.discard(mark["key"])
|
|
105
|
+
fd, mark["fd"] = mark["fd"], None
|
|
106
|
+
unlock_project(fd)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@contextmanager
|
|
110
|
+
def clear_mark_if_aborted(mark: dict | None) -> Iterator[None]:
|
|
111
|
+
"""拿着标记的步骤被异常打断、异常要往流程外抛时(KeyboardInterrupt、SystemExit,或者流程没有接住的错误),先取消
|
|
112
|
+
"正在分析"的标记、释放项目锁再往外抛:流程后面的"取消正在分析的标记"走不到了,不清掉的话这个项目就再也分析不了。
|
|
113
|
+
流程接住的错误(StoreError 等)也会在这里先取消标记,流程随后再取消一次也没关系(clear_mark 只释放一次)。"""
|
|
114
|
+
try:
|
|
115
|
+
yield
|
|
116
|
+
except BaseException:
|
|
117
|
+
clear_mark(mark)
|
|
118
|
+
raise
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def take_mark(store: Store, project_id: str) -> dict:
|
|
122
|
+
"""本进程里先占上(挡住本进程的另一次),再拿项目的文件锁(挡住别的进程)。任一个已经被占着时不标记,返回
|
|
123
|
+
{"marked": False};标记了返回 {"marked": True, "key", "fd"}(fd 是锁文件的描述符,取消标记时释放)。
|
|
124
|
+
锁文件建不了(数据目录出了问题)时只在本进程内互斥,记一条警告。"""
|
|
125
|
+
key = (str(store.path), project_id)
|
|
126
|
+
with _busy_lock:
|
|
127
|
+
if key in _busy:
|
|
128
|
+
return {"marked": False, "key": key, "fd": None}
|
|
129
|
+
_busy.add(key)
|
|
130
|
+
try:
|
|
131
|
+
fd = try_lock_project(store.path.parent, project_id)
|
|
132
|
+
except OSError as e:
|
|
133
|
+
logger.warning("拿不到项目 %s 的分析锁(%s),这次只在本进程内互斥", project_id, e.strerror or e)
|
|
134
|
+
fd = -1
|
|
135
|
+
except BaseException:
|
|
136
|
+
with _busy_lock:
|
|
137
|
+
_busy.discard(key)
|
|
138
|
+
raise
|
|
139
|
+
if fd is None: # 别的进程正在分析这个项目
|
|
140
|
+
with _busy_lock:
|
|
141
|
+
_busy.discard(key)
|
|
142
|
+
return {"marked": False, "key": key, "fd": None}
|
|
143
|
+
return {"marked": True, "key": key, "fd": fd}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _has_python_files(root: Path, exclude: set[str]) -> bool:
|
|
147
|
+
"""root 下(跳过排除的目录,和引擎建索引时一样)有没有 .py 文件;找到第一个就停。"""
|
|
148
|
+
for _dirpath, dirnames, filenames in os.walk(root):
|
|
149
|
+
dirnames[:] = [d for d in dirnames if d not in exclude]
|
|
150
|
+
if any(f.endswith(".py") for f in filenames):
|
|
151
|
+
return True
|
|
152
|
+
return False
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _inside(child: str, parent: str) -> bool:
|
|
156
|
+
return child != parent and os.path.commonpath([child, parent]) == parent
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _ancestors(path: str) -> set[tuple[int, int]]:
|
|
160
|
+
"""path 的每一级上级目录(不含它自己)的 (设备, inode)。"""
|
|
161
|
+
return {i for parent in Path(path).parents if (i := identity(parent)) is not None}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _overlap_with(projects: list[dict], root: str) -> dict:
|
|
165
|
+
"""root 和已添加的项目比:同一个目录("same")、在某个项目里面或包含某个项目("nested")。路径字符串和 inode
|
|
166
|
+
都比(inode 认得出大小写不同的写法)。返回 {"same", "nested", "reason"},没有的为 None。
|
|
167
|
+
目录已经不是添加时那个真实目录的项目(被删、被移走或换成了符号链接:root_problem 不为 None)不参与比较:顺着
|
|
168
|
+
换上的链接比会误判(链接指到 / 时任何目录都"在它里面");这样的项目重新分析、读源码都会被拒绝,要删除后重新添加。"""
|
|
169
|
+
projects = [p for p in projects if root_problem(p["root"]) is None]
|
|
170
|
+
me, my_ancestors = identity(root), _ancestors(root)
|
|
171
|
+
for p in projects:
|
|
172
|
+
if p["root"] == root or (me is not None and identity(p["root"]) == me):
|
|
173
|
+
return {"same": p, "nested": None, "reason": f"这个目录已经添加过(项目「{p['name']}」):{root}"}
|
|
174
|
+
for p in projects:
|
|
175
|
+
other = identity(p["root"])
|
|
176
|
+
if _inside(root, p["root"]) or (other is not None and other in my_ancestors):
|
|
177
|
+
return {"same": None, "nested": p,
|
|
178
|
+
"reason": f"这个目录在已添加的项目「{p['name']}」({p['root']})里面,不用再单独添加"}
|
|
179
|
+
if _inside(p["root"], root) or (me is not None and me in _ancestors(p["root"])):
|
|
180
|
+
return {"same": None, "nested": p,
|
|
181
|
+
"reason": f"这个目录包含已添加的项目「{p['name']}」({p['root']});要分析整个目录,先删除那个项目"}
|
|
182
|
+
return {"same": None, "nested": None, "reason": ""}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _conflict_in_store(root: str, projects: list[dict]) -> StoreError | None:
|
|
186
|
+
"""保存时在写事务里再查一次(Store.add_project 的 conflict):两次添加同时通过了查重,后保存的在这里被挡下。"""
|
|
187
|
+
found = _overlap_with(projects, root)
|
|
188
|
+
if found["same"] is not None:
|
|
189
|
+
return DuplicateRootError(root, found["same"]["id"])
|
|
190
|
+
if found["nested"] is not None:
|
|
191
|
+
return OverlapRootError(found["reason"], found["nested"]["id"])
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def home_conflict(resolved: Path) -> bool:
|
|
196
|
+
"""resolved 是根目录、用户主目录,或者包含用户主目录(/Users、经 /System/Volumes/Data 到达的主目录也算)。"""
|
|
197
|
+
if resolved == Path(resolved.anchor):
|
|
198
|
+
return True
|
|
199
|
+
me, home = identity(resolved), Path.home()
|
|
200
|
+
return me is not None and me in {identity(home), *_ancestors(str(home.resolve()))}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _compare(store: Store, project_id: str, graph_json: str) -> dict:
|
|
204
|
+
"""compare_with_previous 的实际工作(规则见模块说明),返回 {"base_id", "diff", "acknowledged"}。出错时往外抛,
|
|
205
|
+
由步骤接住。"""
|
|
206
|
+
previous = store.latest_analysis(project_id)
|
|
207
|
+
extra = None if previous is None else store.analysis_extra(previous["id"])
|
|
208
|
+
if extra is None:
|
|
209
|
+
return dict(_NO_BASE)
|
|
210
|
+
if extra["graph_sha"] == hashlib.sha256(graph_json.encode("utf-8")).hexdigest():
|
|
211
|
+
return {"base_id": extra["base_id"], "diff": extra["diff"], "acknowledged": extra["acknowledged"]}
|
|
212
|
+
new = from_json(graph_json)
|
|
213
|
+
base_text = None if extra["base_id"] is None else store.graph_json(extra["base_id"])
|
|
214
|
+
if base_text is not None: # P 有对比基准 B:基准不动,重新算 B 到这次
|
|
215
|
+
diff = diff_graphs(from_json(base_text), new)
|
|
216
|
+
return {"base_id": extra["base_id"], "diff": None if diff.empty else diff_to_json(diff), "acknowledged": False}
|
|
217
|
+
old_text = store.graph_json(previous["id"])
|
|
218
|
+
if old_text is None: # 刚被别处清理掉了
|
|
219
|
+
return dict(_NO_BASE)
|
|
220
|
+
diff = diff_graphs(from_json(old_text), new)
|
|
221
|
+
if not diff.empty:
|
|
222
|
+
return {"base_id": previous["id"], "diff": diff_to_json(diff), "acknowledged": False}
|
|
223
|
+
return {**_NO_BASE, "acknowledged": extra["acknowledged"]}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# ---------- 步骤 ----------
|
|
227
|
+
|
|
228
|
+
@step(title="校验分析配置")
|
|
229
|
+
def check_config(config: dict | None) -> dict:
|
|
230
|
+
"""返回 {"ok", "config"(规整后的配置 JSON,{} 表示全用默认值), "exclude", "reason"}。"""
|
|
231
|
+
data = {} if config is None else config
|
|
232
|
+
try:
|
|
233
|
+
parsed = parse_config(data)
|
|
234
|
+
except ConfigError as e:
|
|
235
|
+
return {"ok": False, "reason": f"分析配置不合法:{e}"}
|
|
236
|
+
return {"ok": True, "config": dict(data), "exclude": sorted(parsed.exclude_dirs), "reason": ""}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@step(title="规整并检查目录")
|
|
240
|
+
def inspect_directory(root: str, checked: dict) -> dict:
|
|
241
|
+
"""展开 ~、去掉结尾斜杠、解析符号链接,再看它能不能当项目:存在、是目录、按配置的排除规则看里面有 .py 文件。
|
|
242
|
+
返回 {"ok", "root"(解析后的绝对路径), "name"(目录名), "reason"}。"""
|
|
243
|
+
text = root.strip() if isinstance(root, str) else ""
|
|
244
|
+
if not text:
|
|
245
|
+
return {"ok": False, "reason": "请填写项目目录"}
|
|
246
|
+
if "\0" in text:
|
|
247
|
+
return {"ok": False, "reason": "目录路径里不能有空字符(NUL)"}
|
|
248
|
+
try:
|
|
249
|
+
return _examine(Path(text).expanduser(), text, checked["exclude"])
|
|
250
|
+
except (OSError, ValueError) as e: # 路径太长、某一级没有权限等
|
|
251
|
+
return {"ok": False, "reason": f"目录路径不合法:{getattr(e, 'strerror', None) or e}:{text[:200]}"}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _examine(path: Path, text: str, exclude: list[str]) -> dict:
|
|
255
|
+
if not path.is_absolute():
|
|
256
|
+
return {"ok": False, "reason": f"请填写绝对路径(可以用 ~ 开头):{text}"}
|
|
257
|
+
resolved = path.resolve()
|
|
258
|
+
if home_conflict(resolved):
|
|
259
|
+
return {"ok": False, "reason": f"不能把根目录、用户主目录或包含用户主目录的目录当作项目,请选具体的代码目录:{resolved}"}
|
|
260
|
+
if not resolved.exists():
|
|
261
|
+
return {"ok": False, "reason": f"目录不存在:{resolved}"}
|
|
262
|
+
if not resolved.is_dir():
|
|
263
|
+
return {"ok": False, "reason": f"不是目录:{resolved}"}
|
|
264
|
+
if not os.access(resolved, os.R_OK | os.X_OK):
|
|
265
|
+
return {"ok": False, "reason": f"没有权限读取这个目录:{resolved}"}
|
|
266
|
+
if not _has_python_files(resolved, set(exclude)):
|
|
267
|
+
return {"ok": False, "reason": f"目录里没有 .py 文件(排除的目录不算:{', '.join(exclude)}):{resolved}"}
|
|
268
|
+
return {"ok": True, "root": str(resolved), "name": resolved.name, "reason": ""}
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
@step(title="查找已添加的同一目录或上下级目录")
|
|
272
|
+
def find_overlap(store: Store, root: str) -> dict:
|
|
273
|
+
"""返回 {"same": 同一个目录的项目, "nested": 上级或下级目录的项目, "reason"},没有的为 None(按 inode 比)。"""
|
|
274
|
+
return _overlap_with(store.list_projects(), root)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@step(title="运行分析")
|
|
278
|
+
def run_analysis(store: Store, root: str, config: dict, analyzer: Analyzer | None = None,
|
|
279
|
+
mark: dict | None = None) -> dict:
|
|
280
|
+
"""调用引擎分析目录(只读),默认在子进程里、带超时(见 worker)。任何错都在这里接住,变成结果:
|
|
281
|
+
{"ok": True, "graph_json", "summary", "engine_version", "file_lines"} 或 {"ok": False, "code", "reason"}
|
|
282
|
+
(code:invalid、config、analysis、timeout)。mark 是"标记这个项目正在分析"的结果:被 Exception 以外的异常
|
|
283
|
+
(Ctrl+C 等)打断时由这里取消标记(见 clear_mark_if_aborted)。"""
|
|
284
|
+
with clear_mark_if_aborted(mark):
|
|
285
|
+
return _run_engine(store.path.parent, root, config, analyzer)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _run_engine(home: Path, root: str, config: dict, analyzer: Analyzer | None) -> dict:
|
|
289
|
+
"""run_analysis 的实际工作。任何 Exception 都变成结果,不往外抛(标记要靠流程后面的步骤取消)。"""
|
|
290
|
+
try:
|
|
291
|
+
problem = root_problem(root) # 兜底:检查之后、分析之前目录又被换掉了
|
|
292
|
+
if problem is not None:
|
|
293
|
+
return {"ok": False, "code": "invalid", "reason": problem[1]}
|
|
294
|
+
if analyzer is not None:
|
|
295
|
+
return analyze_directory(root, config, analyzer)
|
|
296
|
+
return run_in_subprocess(root, config, timeout=analyze_timeout(), cwd=home)
|
|
297
|
+
except Exception as e: # 不让它带走整个请求,项目和上一次的结果保持原样
|
|
298
|
+
logger.exception("分析 %s 失败", root)
|
|
299
|
+
return {"ok": False, "code": "analysis", "reason": f"分析失败:{type(e).__name__}: {e}"}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
@step(title="保存项目和这次分析")
|
|
303
|
+
def save_new_project(store: Store, target: dict, name: str | None, checked: dict, result: dict) -> dict:
|
|
304
|
+
"""项目和它的第一次分析在一个事务里写入,写之前在同一个事务里再查一次重叠(这段时间里别的添加可能已经存进去
|
|
305
|
+
了)。同一目录已经有了时抛 DuplicateRootError,和已有项目重叠时抛 OverlapRootError,写不进去时抛 StoreError。
|
|
306
|
+
同一进程里的添加在这里排队(库的写锁另外挡住别的进程)。"""
|
|
307
|
+
shown = (name or "").strip() or target["name"]
|
|
308
|
+
analysis = NewAnalysis(result["engine_version"], result["summary"], result["graph_json"], config=checked["config"],
|
|
309
|
+
file_lines=result["file_lines"]) # 第一次分析:没有对比基准
|
|
310
|
+
with _add_lock:
|
|
311
|
+
project_id, analysis_id = store.add_project(name=shown, root=target["root"], config=checked["config"],
|
|
312
|
+
analysis=analysis,
|
|
313
|
+
conflict=functools.partial(_conflict_in_store, target["root"]))
|
|
314
|
+
return {"project_id": project_id, "analysis_id": analysis_id}
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@step(title="检查项目目录")
|
|
318
|
+
def check_project_directory(root: str) -> dict:
|
|
319
|
+
"""添加时存下的根目录现在还是不是同一个真实目录:没被删掉,没被移走后原地换成符号链接(顺着链接分析会读到项目
|
|
320
|
+
之外)。返回 {"ok", "reason"}。"""
|
|
321
|
+
problem = root_problem(root)
|
|
322
|
+
return {"ok": problem is None, "reason": "" if problem is None else problem[1]}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
@step(title="标记这个项目正在分析")
|
|
326
|
+
def mark_analyzing(store: Store, project_id: str) -> dict:
|
|
327
|
+
"""见 take_mark:{"marked", "key", "fd"}。"""
|
|
328
|
+
return take_mark(store, project_id)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
@step(title="取消正在分析的标记")
|
|
332
|
+
def unmark_analyzing(mark: dict) -> None:
|
|
333
|
+
clear_mark(mark)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
@step(title="读取项目")
|
|
337
|
+
def load_project(store: Store, project_id: str) -> dict:
|
|
338
|
+
"""返回 {"found", "project", "reason"}。"""
|
|
339
|
+
project = store.get_project(project_id)
|
|
340
|
+
if project is None:
|
|
341
|
+
return {"found": False, "project": None, "reason": f"项目不存在(可能已经删除了):{project_id}"}
|
|
342
|
+
return {"found": True, "project": project, "reason": ""}
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@step(title="和上一次分析比较流程")
|
|
346
|
+
def compare_with_previous(store: Store, project_id: str, result: dict, mark: dict | None = None) -> dict:
|
|
347
|
+
"""定这次的对比基准、算流程差异(规则见模块说明),返回 {"base_id", "diff", "acknowledged"}。读不出旧图、算差异
|
|
348
|
+
出错时记日志,按没有基准处理(都为 None),不让这次分析失败。mark:拿着的标记(见 clear_mark_if_aborted)。"""
|
|
349
|
+
with clear_mark_if_aborted(mark):
|
|
350
|
+
try:
|
|
351
|
+
return _compare(store, project_id, result["graph_json"])
|
|
352
|
+
except Exception:
|
|
353
|
+
logger.exception("项目 %s 和上一次分析比较失败,这次按没有对比基准保存", project_id)
|
|
354
|
+
return dict(_NO_BASE)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
@step(title="保存这次分析")
|
|
358
|
+
def save_analysis(store: Store, project_id: str, result: dict, config: dict, compared: dict,
|
|
359
|
+
mark: dict | None = None) -> int:
|
|
360
|
+
"""连同这次用的配置、功能线涉及的文件、对比基准和差异一起存。项目不存在了(分析期间被删)时抛
|
|
361
|
+
ProjectMissingError,写不进去时抛 StoreError。"""
|
|
362
|
+
with clear_mark_if_aborted(mark):
|
|
363
|
+
return store.add_analysis(project_id, NewAnalysis(
|
|
364
|
+
result["engine_version"], result["summary"], result["graph_json"], config=config,
|
|
365
|
+
file_lines=result["file_lines"], base_id=compared["base_id"], diff=compared["diff"],
|
|
366
|
+
acknowledged=compared.get("acknowledged", False)))
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
@step(title="清理旧分析,只留最近 5 次、对比基准和最近一次全量运行用的那次") # 标题要写成字面量,图上才认得出;改 KEEP_ANALYSES 时一起改
|
|
370
|
+
def prune_old_analyses(store: Store, project_id: str, mark: dict | None = None) -> int:
|
|
371
|
+
"""最新一次的对比基准那次、最近一次跑完的全量运行用的那次也留着(重新算差异、分出运行之后才有的结局要用它们的图)。清理失败不影响这次分析的结果:记下来,下次再清。"""
|
|
372
|
+
with clear_mark_if_aborted(mark):
|
|
373
|
+
try:
|
|
374
|
+
return store.prune_analyses(project_id, keep=KEEP_ANALYSES)
|
|
375
|
+
except StoreError:
|
|
376
|
+
logger.exception("清理项目 %s 的旧分析失败", project_id)
|
|
377
|
+
return 0
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
@step(title="删除平台里的项目记录")
|
|
381
|
+
def delete_project_records(store: Store, project_id: str) -> bool:
|
|
382
|
+
"""删除项目、它的全部分析、手工改的标题分组和测试运行。只删平台里的记录,不动项目的代码。"""
|
|
383
|
+
return store.delete_project(project_id)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
@step(title="删掉项目的锁文件")
|
|
387
|
+
def delete_lock_file(store: Store, project_id: str) -> bool:
|
|
388
|
+
"""<数据目录>/locks/<项目 id>.lock:没人拿着时删掉,有人拿着(还在分析、跑测试)时留着(见 locks.remove_lock)。"""
|
|
389
|
+
return remove_lock(store.path.parent, project_id)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
@step(title="存下这次变化,清掉对比基准")
|
|
393
|
+
def clear_diff_base(store: Store, project_id: str, analysis_id: int | None = None, mark: dict | None = None) -> dict:
|
|
394
|
+
"""最新一次分析的对比基准和流程差异置空:以后的分析从这次起比。analysis_id 是用户看过的那次:最新一次已经不是
|
|
395
|
+
它时不清(Store.clear_base 在同一条语句里判断)。清掉之前,这次的流程差异先存成一条变更记录(同一个事务里,
|
|
396
|
+
每个项目留最近 10 条,见 Store.clear_base)。返回 {"cleared", "reason"};写不进去时抛 StoreError。"""
|
|
397
|
+
with clear_mark_if_aborted(mark):
|
|
398
|
+
cleared = store.clear_base(project_id, analysis_id=analysis_id)
|
|
399
|
+
return {"cleared": cleared, "reason": "" if cleared else "分析结果已经更新,请先看新的变化"}
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
# ---------- 判断:只看步骤的结果 ----------
|
|
403
|
+
|
|
404
|
+
@condition(title="配置不合法?")
|
|
405
|
+
def config_is_invalid(checked: dict) -> bool:
|
|
406
|
+
return not checked["ok"]
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@condition(title="目录不可用?")
|
|
410
|
+
def directory_is_unusable(target: dict) -> bool:
|
|
411
|
+
return not target["ok"]
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
@condition(title="这个目录已经添加过?")
|
|
415
|
+
def already_added(overlap: dict) -> bool:
|
|
416
|
+
return overlap["same"] is not None
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
@condition(title="和已添加的项目目录重叠?")
|
|
420
|
+
def overlaps_project(overlap: dict) -> bool:
|
|
421
|
+
return overlap["nested"] is not None
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
@condition(title="分析失败?")
|
|
425
|
+
def analysis_failed(result: dict) -> bool:
|
|
426
|
+
return not result["ok"]
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
@condition(title="这个项目正在分析?")
|
|
430
|
+
def already_analyzing(mark: dict) -> bool:
|
|
431
|
+
return not mark["marked"]
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
@condition(title="项目不存在?")
|
|
435
|
+
def project_is_missing(found: dict) -> bool:
|
|
436
|
+
return not found["found"]
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
@condition(title="最新一次已经不是看过的那次?")
|
|
440
|
+
def latest_has_moved(cleared: dict) -> bool:
|
|
441
|
+
return not cleared["cleared"]
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
# ---------- 流程 ----------
|
|
445
|
+
|
|
446
|
+
@workflow(name="add_project", title="添加项目", group="项目管理")
|
|
447
|
+
def add_project(store: Store, root: str, name: str | None = None, config: dict | None = None, *,
|
|
448
|
+
analyzer: Analyzer | None = None) -> dict:
|
|
449
|
+
"""校验 → 查重 → 分析 → 入库。分析或保存失败时什么都不留下。"""
|
|
450
|
+
checked = check_config(config)
|
|
451
|
+
if config_is_invalid(checked):
|
|
452
|
+
return outcome("failed", title="配置不合法,没有添加", reason=checked["reason"], code="config")
|
|
453
|
+
target = inspect_directory(root, checked)
|
|
454
|
+
if directory_is_unusable(target):
|
|
455
|
+
return outcome("failed", title="目录不可用,没有添加", reason=target["reason"], code="invalid")
|
|
456
|
+
overlap = find_overlap(store, target["root"])
|
|
457
|
+
if already_added(overlap):
|
|
458
|
+
return outcome("failed", title="目录已经添加过", reason=overlap["reason"], code="duplicate",
|
|
459
|
+
project_id=overlap["same"]["id"])
|
|
460
|
+
if overlaps_project(overlap):
|
|
461
|
+
return outcome("failed", title="和已添加的项目重叠,没有添加", reason=overlap["reason"], code="overlap")
|
|
462
|
+
result = run_analysis(store, target["root"], checked["config"], analyzer)
|
|
463
|
+
if analysis_failed(result):
|
|
464
|
+
return outcome("failed", title="分析失败,没有添加", reason=result["reason"], code=result["code"])
|
|
465
|
+
try:
|
|
466
|
+
saved = save_new_project(store, target, name, checked, result)
|
|
467
|
+
except DuplicateRootError as e: # 两次添加同时通过了查重:后保存的这次在写事务里被挡下
|
|
468
|
+
return outcome("failed", title="同时添加了同一目录,这次没有添加", reason=str(e), code="duplicate",
|
|
469
|
+
project_id=e.project_id)
|
|
470
|
+
except OverlapRootError as e:
|
|
471
|
+
return outcome("failed", title="同时添加了重叠的目录,这次没有添加", reason=str(e), code="overlap")
|
|
472
|
+
except StoreError as e:
|
|
473
|
+
return outcome("failed", title="保存失败,没有添加", reason=str(e), code="storage")
|
|
474
|
+
return outcome("ok", title="项目已添加", project_id=saved["project_id"], analysis_id=saved["analysis_id"],
|
|
475
|
+
summary=result["summary"])
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
@workflow(name="reanalyze_project", title="重新分析", group="项目管理")
|
|
479
|
+
def reanalyze_project(store: Store, project_id: str, *, analyzer: Analyzer | None = None) -> dict:
|
|
480
|
+
"""取项目 → 检查目录 → 标记正在分析 → 分析 → 和上一次比 → 存一次新分析 → 清理旧分析 → 取消标记。失败(包括
|
|
481
|
+
超时)时项目和上一次的结果保持原样;手工改的标题分组不受影响。"""
|
|
482
|
+
found = load_project(store, project_id)
|
|
483
|
+
if project_is_missing(found):
|
|
484
|
+
return outcome("failed", title="项目不存在", reason=found["reason"], code="not_found")
|
|
485
|
+
directory = check_project_directory(found["project"]["root"])
|
|
486
|
+
if directory_is_unusable(directory):
|
|
487
|
+
return outcome("failed", title="项目目录不可用,保留上一次的结果", reason=directory["reason"], code="invalid")
|
|
488
|
+
mark = mark_analyzing(store, project_id)
|
|
489
|
+
if already_analyzing(mark):
|
|
490
|
+
return outcome("failed", title="正在分析,这次没有做", reason="正在分析", code="busy")
|
|
491
|
+
result = run_analysis(store, found["project"]["root"], found["project"]["config"], analyzer, mark)
|
|
492
|
+
if analysis_failed(result):
|
|
493
|
+
unmark_analyzing(mark)
|
|
494
|
+
return outcome("failed", title="分析失败,保留上一次的结果", reason=result["reason"], code=result["code"])
|
|
495
|
+
compared = compare_with_previous(store, project_id, result, mark)
|
|
496
|
+
try:
|
|
497
|
+
analysis_id = save_analysis(store, project_id, result, found["project"]["config"], compared, mark)
|
|
498
|
+
except ProjectMissingError as e:
|
|
499
|
+
unmark_analyzing(mark)
|
|
500
|
+
return outcome("failed", title="项目在分析期间被删除了", reason=str(e), code="not_found")
|
|
501
|
+
except StoreError as e:
|
|
502
|
+
unmark_analyzing(mark)
|
|
503
|
+
return outcome("failed", title="保存失败,保留上一次的结果", reason=str(e), code="storage")
|
|
504
|
+
prune_old_analyses(store, project_id, mark)
|
|
505
|
+
unmark_analyzing(mark)
|
|
506
|
+
return outcome("ok", title="分析完成", analysis_id=analysis_id, summary=result["summary"])
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
@workflow(name="remove_project", title="删除项目", group="项目管理")
|
|
510
|
+
def remove_project(store: Store, project_id: str) -> dict:
|
|
511
|
+
"""只删平台里的记录(项目、分析、手工改的标题分组、测试运行)和项目的锁文件,不动项目的代码。"""
|
|
512
|
+
found = load_project(store, project_id)
|
|
513
|
+
if project_is_missing(found):
|
|
514
|
+
return outcome("failed", title="项目不存在", reason=found["reason"], code="not_found")
|
|
515
|
+
try:
|
|
516
|
+
delete_project_records(store, project_id)
|
|
517
|
+
except StoreError as e:
|
|
518
|
+
return outcome("failed", title="删除失败", reason=str(e), code="storage")
|
|
519
|
+
delete_lock_file(store, project_id)
|
|
520
|
+
return outcome("ok", title="项目已删除", project_id=project_id)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
@workflow(name="acknowledge_changes", title="标记流程变化已看过", group="项目管理")
|
|
524
|
+
def acknowledge_changes(store: Store, project_id: str, analysis_id: int | None = None) -> dict:
|
|
525
|
+
"""取项目 → 拿项目的分析锁 → 清掉最新一次分析的对比基准和流程差异 → 放开锁。以后的分析从这次起比;不删也不
|
|
526
|
+
新增分析。analysis_id 是用户看过差异的那次分析(界面总是给出):最新一次已经换了时不清,结局 moved。正在分析
|
|
527
|
+
(本进程或别的进程)时不做,结局 busy:那次分析存下的会是新的最新一次。"""
|
|
528
|
+
found = load_project(store, project_id)
|
|
529
|
+
if project_is_missing(found):
|
|
530
|
+
return outcome("failed", title="项目不存在", reason=found["reason"], code="not_found")
|
|
531
|
+
mark = mark_analyzing(store, project_id)
|
|
532
|
+
if already_analyzing(mark):
|
|
533
|
+
return outcome("failed", title="正在分析,这次没有标记", reason="正在分析,等分析完再标为看过", code="busy")
|
|
534
|
+
try:
|
|
535
|
+
cleared = clear_diff_base(store, project_id, analysis_id, mark)
|
|
536
|
+
except StoreError as e:
|
|
537
|
+
unmark_analyzing(mark)
|
|
538
|
+
return outcome("failed", title="保存失败,变化仍标着", reason=str(e), code="storage")
|
|
539
|
+
unmark_analyzing(mark)
|
|
540
|
+
if latest_has_moved(cleared):
|
|
541
|
+
return outcome("failed", title="分析结果已经更新,这次没有标记", reason=cleared["reason"], code="moved")
|
|
542
|
+
return outcome("ok", title="流程变化已标为看过", project_id=project_id)
|