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/engineid.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""引擎标识:包的版本号加上"出图用到的源码"的指纹,平台把它和每次分析一起保存(engine_version)。
|
|
2
|
+
|
|
3
|
+
版本号(__version__)不是每次改引擎都会升:从源码仓库运行时,修一处画法(比如 finally 的连线)之后重新分析,没改过的
|
|
4
|
+
项目代码也会冒出流程变化。指纹跟着源码变,所以两次分析的引擎标识不同,就说明中间引擎改过——流程差异据此提醒
|
|
5
|
+
"所在文件没改的函数,变化是引擎引起的"(diff.diff_text 的 engines)。
|
|
6
|
+
|
|
7
|
+
指纹只算出图用到的模块:从 analyze.py 起,顺着 `from pystepmap.x import …` / `from .x import …` 找到的包内模块
|
|
8
|
+
(build、resolve、rules……)。命令行、套件安装、记录插件、差异和查询的文字这些改了不影响图,不算。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ast
|
|
14
|
+
import hashlib
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from pystepmap import __version__
|
|
18
|
+
|
|
19
|
+
_PACKAGE = Path(__file__).resolve().parent
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _imports(source: str) -> set[str]:
|
|
23
|
+
"""这段源码导入了包里的哪些模块(模块名,不带包名)。"""
|
|
24
|
+
out: set[str] = set()
|
|
25
|
+
for node in ast.walk(ast.parse(source)):
|
|
26
|
+
if isinstance(node, ast.ImportFrom):
|
|
27
|
+
if node.level == 1:
|
|
28
|
+
out.update([node.module.split(".")[0]] if node.module else [a.name for a in node.names])
|
|
29
|
+
elif node.level == 0 and node.module and node.module.split(".")[0] == "pystepmap":
|
|
30
|
+
parts = node.module.split(".")
|
|
31
|
+
out.update([parts[1]] if len(parts) > 1 else [a.name for a in node.names])
|
|
32
|
+
elif isinstance(node, ast.Import):
|
|
33
|
+
out.update(a.name.split(".")[1] for a in node.names if a.name.startswith("pystepmap."))
|
|
34
|
+
return out
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def engine_modules(package: Path = _PACKAGE, start: str = "analyze") -> list[str]:
|
|
38
|
+
"""出图用到的包内模块名(排好序):从 start 起顺着包内的导入找。读不了、解析不了的模块算进去但不往下找。"""
|
|
39
|
+
seen: set[str] = set()
|
|
40
|
+
todo = [start]
|
|
41
|
+
while todo:
|
|
42
|
+
name = todo.pop()
|
|
43
|
+
path = package / f"{name}.py"
|
|
44
|
+
if name in seen or not path.is_file():
|
|
45
|
+
continue
|
|
46
|
+
seen.add(name)
|
|
47
|
+
try:
|
|
48
|
+
todo += _imports(path.read_text(encoding="utf-8"))
|
|
49
|
+
except (OSError, SyntaxError, ValueError):
|
|
50
|
+
continue
|
|
51
|
+
return sorted(seen)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def engine_fingerprint(package: Path = _PACKAGE) -> str:
|
|
55
|
+
"""出图用到的源码的指纹(8 位十六进制);一个模块都读不到时空串。"""
|
|
56
|
+
h = hashlib.sha256()
|
|
57
|
+
found = False
|
|
58
|
+
for name in engine_modules(package):
|
|
59
|
+
try:
|
|
60
|
+
data = (package / f"{name}.py").read_bytes()
|
|
61
|
+
except OSError:
|
|
62
|
+
continue
|
|
63
|
+
found = True
|
|
64
|
+
h.update(name.encode() + b"\0" + data + b"\0")
|
|
65
|
+
return h.hexdigest()[:8] if found else ""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _engine_version() -> str:
|
|
69
|
+
fp = engine_fingerprint()
|
|
70
|
+
return f"{__version__}+{fp}" if fp else __version__
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
ENGINE_VERSION = _engine_version() # 例如 0.1.0+3fa9c1d2
|
pystepmap/entries.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""没有装饰器规则可认的入口:不靠标记、不靠配置,尽量把"会被外面调起来的函数"找出来,各成一条功能线。
|
|
2
|
+
|
|
3
|
+
识别规则(rules.py)只认路由、任务、工作流的装饰器。新手让 AI 写的项目常常是一个脚本、一个命令行工具、一个机器人:
|
|
4
|
+
没有这些装饰器,功能线就是空的。这里补四种,类型都还是普通函数(kind 不变),只是给它一个分组和 rule:
|
|
5
|
+
|
|
6
|
+
- `main`:`if __name__ == "__main__":` 块里调用的项目内函数(含 `asyncio.run(main())` 这种包了一层的)——分组"脚本入口"。它只是把一个已经认出来的
|
|
7
|
+
入口跑起来时(演示、启动代码:沿调用能走到路由、任务或工作流)不算,里面没有步骤、判断、循环的小工具也不算;
|
|
8
|
+
- `command`:命令行框架的子命令,装饰器是 `@x.command(...)` / `@click.command()` / `@x.callback()`——分组"命令行";
|
|
9
|
+
- `handler`:顶层函数挂着项目外对象的装饰器(`@scheduler.scheduled_job(...)`、`@bot.message_handler(...)`、
|
|
10
|
+
`@app.on_event("startup")`),项目里又没有人调用它:是框架来调的——分组"其他入口";
|
|
11
|
+
- `comment`:函数定义(有装饰器时是第一个装饰器)上面紧挨着的一行注释 `# pystepmap: 入口` 或
|
|
12
|
+
`# pystepmap: 入口 每日对账`(冒号全角半角都行,"入口"也可以写 entry)。后面的文字是功能线的标题。这是不装任何包、
|
|
13
|
+
不改配置就能点名入口的办法:别的规则都没认出来时,写这一行就一定成线——分组"其他入口";
|
|
14
|
+
- `fallback`:上面这些加上路由、任务、工作流一个都没有时(`fallback_entries` 没关),把没有人调用、也没有被当作值
|
|
15
|
+
交出去的顶层函数当入口;还是没有,就放宽到全部模块级函数、再到类的公开方法。只要项目里有函数,就有功能线。
|
|
16
|
+
|
|
17
|
+
`extra_entries`(配置里点名的入口)照旧,优先于这里。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import ast
|
|
23
|
+
import re
|
|
24
|
+
|
|
25
|
+
from .external import ExternalObjects
|
|
26
|
+
from .index import FunctionInfo, ProjectIndex
|
|
27
|
+
from .model import FunctionGraph, ProjectGraph
|
|
28
|
+
from .resolve import Resolver
|
|
29
|
+
|
|
30
|
+
GROUP_SCRIPT = "脚本入口"
|
|
31
|
+
GROUP_COMMAND = "命令行"
|
|
32
|
+
GROUP_OTHER = "其他入口"
|
|
33
|
+
ENTRY_KINDS = ("route", "task", "workflow")
|
|
34
|
+
AUTO_GROUPS = {"main": GROUP_SCRIPT, "command": GROUP_COMMAND, "handler": GROUP_OTHER, "comment": GROUP_OTHER,
|
|
35
|
+
"fallback": GROUP_OTHER}
|
|
36
|
+
ENTRY_COMMENT = "# pystepmap: 入口" # 给人和 AI 看的写法(提示里引用)
|
|
37
|
+
|
|
38
|
+
_COMMAND = re.compile(r"(^|\.)(command|callback)$")
|
|
39
|
+
_MARK = re.compile(r"^#\s*pystepmap\s*[::]\s*(?:入口|entry)\b\s*[::]?\s*(.*)$", re.IGNORECASE)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def comment_mark(fn: FunctionInfo, index: ProjectIndex) -> str | None:
|
|
43
|
+
"""函数上面紧挨着的入口注释里的标题(没写标题时 "");没有这行注释时 None。"""
|
|
44
|
+
first = min([fn.node.lineno, *(d.lineno for d in fn.node.decorator_list)])
|
|
45
|
+
lines = index.modules[fn.file].lines
|
|
46
|
+
if first < 2 or first - 2 >= len(lines):
|
|
47
|
+
return None
|
|
48
|
+
m = _MARK.match(lines[first - 2].strip())
|
|
49
|
+
return m.group(1).strip() if m else None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _is_main_guard(st: ast.stmt) -> bool:
|
|
53
|
+
"""if __name__ == "__main__":(两边谁在前都行)。"""
|
|
54
|
+
if not isinstance(st, ast.If) or not isinstance(st.test, ast.Compare) or len(st.test.ops) != 1 \
|
|
55
|
+
or not isinstance(st.test.ops[0], ast.Eq):
|
|
56
|
+
return False
|
|
57
|
+
sides = [st.test.left, st.test.comparators[0]]
|
|
58
|
+
return any(isinstance(s, ast.Name) and s.id == "__name__" for s in sides) \
|
|
59
|
+
and any(isinstance(s, ast.Constant) and s.value == "__main__" for s in sides)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _main_calls(index: ProjectIndex, resolver: Resolver) -> list[str]:
|
|
63
|
+
"""各模块 __main__ 块里调用的项目内函数的 key。"""
|
|
64
|
+
found: dict[str, None] = {}
|
|
65
|
+
for mod in index.modules.values():
|
|
66
|
+
for st in mod.tree.body:
|
|
67
|
+
if not _is_main_guard(st):
|
|
68
|
+
continue
|
|
69
|
+
for n in ast.walk(st):
|
|
70
|
+
if isinstance(n, ast.Call):
|
|
71
|
+
sym = resolver.symbol(n.func, mod, None)
|
|
72
|
+
if sym and sym[0] == "func":
|
|
73
|
+
found.setdefault(sym[1], None)
|
|
74
|
+
return list(found)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _decorator_func(dec: ast.expr) -> ast.expr:
|
|
78
|
+
return dec.func if isinstance(dec, ast.Call) else dec
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _is_command(fn: FunctionInfo) -> bool:
|
|
82
|
+
return any(_COMMAND.search(ast.unparse(_decorator_func(d))) for d in fn.decorators)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _is_handler(fn: FunctionInfo, index: ProjectIndex, objects: ExternalObjects) -> bool:
|
|
86
|
+
"""装饰器是项目外对象上的方法(@x.方法 / @x.方法(...),x 是外部导入的名字或用外部库建出来的模块级对象)。"""
|
|
87
|
+
roots = objects.module_roots(index.modules[fn.file])
|
|
88
|
+
for dec in fn.decorators:
|
|
89
|
+
func = _decorator_func(dec)
|
|
90
|
+
if isinstance(func, ast.Attribute):
|
|
91
|
+
base = func.value
|
|
92
|
+
while isinstance(base, ast.Attribute):
|
|
93
|
+
base = base.value
|
|
94
|
+
if isinstance(base, ast.Name) and base.id in roots:
|
|
95
|
+
return True
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _drives_entry(key: str, functions: dict[str, FunctionGraph]) -> bool:
|
|
100
|
+
"""从这个函数沿调用能走到一个已经认出来的入口(路由、任务、工作流):它只是把那条功能线跑起来的演示 / 启动代码。"""
|
|
101
|
+
seen, stack = {key}, [key]
|
|
102
|
+
while stack:
|
|
103
|
+
for k in functions[stack.pop()].call_targets:
|
|
104
|
+
if k in functions and k not in seen:
|
|
105
|
+
if functions[k].kind in ENTRY_KINDS:
|
|
106
|
+
return True
|
|
107
|
+
seen.add(k)
|
|
108
|
+
stack.append(k)
|
|
109
|
+
return False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def auto_entries(functions: dict[str, FunctionGraph], index: ProjectIndex, resolver: Resolver,
|
|
113
|
+
objects: ExternalObjects, referenced: set[str], fallback: bool,
|
|
114
|
+
named: set[str] = frozenset()) -> dict[str, str]:
|
|
115
|
+
"""函数 key -> 认出它的方式(comment / main / command / handler / fallback)。只给普通函数;已经是路由、任务、
|
|
116
|
+
工作流、步骤、判断的不动。入口注释里写了标题的,标题直接记到函数图上。named:配置的 extra_entries 点了名的函数——
|
|
117
|
+
它们照配置来,这里不碰;有点名的入口时也不做兜底。"""
|
|
118
|
+
called = {k for fg in functions.values() for k in fg.call_targets}
|
|
119
|
+
plain = {k: fg for k, fg in functions.items() if fg.kind == "function" and k not in named}
|
|
120
|
+
found: dict[str, str] = {}
|
|
121
|
+
for key, fg in plain.items():
|
|
122
|
+
title = comment_mark(index.functions[key], index)
|
|
123
|
+
if title is not None:
|
|
124
|
+
found[key] = "comment"
|
|
125
|
+
if title:
|
|
126
|
+
fg.title, fg.title_full = title[:60], (title if len(title) > 60 else "")
|
|
127
|
+
if fg.nodes and fg.nodes[0].type == "start":
|
|
128
|
+
fg.nodes[0].title = fg.title
|
|
129
|
+
for key in _main_calls(index, resolver):
|
|
130
|
+
# 里面没有步骤、判断、循环的(now()、usage() 这类顺手调用的小工具)不是一条流程
|
|
131
|
+
if key in plain and not _drives_entry(key, functions) \
|
|
132
|
+
and any(n.type in ("step", "cond", "loop") for n in plain[key].nodes):
|
|
133
|
+
found.setdefault(key, "main")
|
|
134
|
+
for key, fg in plain.items():
|
|
135
|
+
fn = index.functions[key]
|
|
136
|
+
if key in found or fg.parent is not None or not fn.decorators or key in called:
|
|
137
|
+
continue
|
|
138
|
+
if _is_command(fn):
|
|
139
|
+
found[key] = "command"
|
|
140
|
+
elif fn.cls is None and _is_handler(fn, index, objects):
|
|
141
|
+
found[key] = "handler"
|
|
142
|
+
if found or named or not fallback or any(fg.kind in ENTRY_KINDS for fg in functions.values()):
|
|
143
|
+
return found
|
|
144
|
+
top = [k for k, fg in plain.items() if fg.parent is None and index.functions[k].cls is None]
|
|
145
|
+
methods = [k for k, fg in plain.items() if fg.parent is None and index.functions[k].cls is not None
|
|
146
|
+
and not fg.qualname.rsplit(".", 1)[-1].startswith("_")]
|
|
147
|
+
for pool in ([k for k in top if k not in called and k not in referenced],
|
|
148
|
+
[k for k in top if k not in called],
|
|
149
|
+
top,
|
|
150
|
+
[k for k in methods if k not in called and k not in referenced],
|
|
151
|
+
methods):
|
|
152
|
+
if pool:
|
|
153
|
+
return {k: "fallback" for k in pool}
|
|
154
|
+
return found
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def entry_notes(graph: ProjectGraph) -> list[str]:
|
|
158
|
+
"""功能线是怎么来的,值得说一句的情况:一条都没有;全靠兜底(没有人调用的顶层函数)。别的情况不说话。"""
|
|
159
|
+
if not graph.lines:
|
|
160
|
+
if not graph.functions:
|
|
161
|
+
return [("没有功能线:项目里没有函数(代码都直接写在文件顶层时画不出流程,把主要的过程放进一个函数里,"
|
|
162
|
+
"比如 def main(),再重新分析)")]
|
|
163
|
+
return [(f"没有功能线:没有认出路由、任务、工作流、命令或脚本入口;在入口函数上面加一行注释 `{ENTRY_COMMENT} <标题>`,"
|
|
164
|
+
"或者在配置的 extra_entries 里点名")]
|
|
165
|
+
roots = [graph.functions[ln.root.function] for ln in graph.lines if ln.root.function in graph.functions]
|
|
166
|
+
if roots and all(fg.rule == "fallback" for fg in roots):
|
|
167
|
+
return [(f"入口是推断的:没有认出路由、任务、工作流、命令或脚本入口,把没有人调用的 {len(roots)} 个顶层函数各当作"
|
|
168
|
+
f"一条功能线(分组「其他入口」);不对时在真正的入口函数上面加一行注释 `{ENTRY_COMMENT} <标题>`,"
|
|
169
|
+
"或者在配置的 extra_entries 里点名")]
|
|
170
|
+
return []
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def unlisted_roots(graph: ProjectGraph, limit: int | None = 8,
|
|
174
|
+
mentioned: set[str] = frozenset()) -> tuple[list[FunctionGraph], int]:
|
|
175
|
+
"""没有人直接调用、也不在任何功能线上的模块级公开函数(里面至少有一个步骤、判断或循环):可能是没认出来的入口。
|
|
176
|
+
mentioned:项目里别处提到过的函数(AnalysisNotes.mentioned:当作值交出去的回调、依赖、注册表里的函数,装饰器,
|
|
177
|
+
模块顶层调用的启动代码)——有人用它们,不是没认出来的入口,不算。返回(前 limit 个,总数),按文件和行号排。"""
|
|
178
|
+
from .query import line_functions # 避免模块之间循环导入
|
|
179
|
+
|
|
180
|
+
on_line = {k for ln in graph.lines for k in line_functions(graph, ln)}
|
|
181
|
+
called = {k for fg in graph.functions.values() for k in fg.call_targets}
|
|
182
|
+
found = [fg for k, fg in graph.functions.items()
|
|
183
|
+
if fg.kind == "function" and fg.parent is None and "." not in fg.qualname and not fg.qualname.startswith("_")
|
|
184
|
+
and k not in on_line and k not in called and k not in mentioned
|
|
185
|
+
and any(n.type in ("step", "cond", "loop") for n in fg.nodes)]
|
|
186
|
+
found.sort(key=lambda fg: (fg.file, fg.line))
|
|
187
|
+
return found[:limit], len(found)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def unlisted_notes(graph: ProjectGraph, mentioned: set[str] = frozenset()) -> list[str]:
|
|
191
|
+
shown, total = unlisted_roots(graph, mentioned=mentioned)
|
|
192
|
+
if not total:
|
|
193
|
+
return []
|
|
194
|
+
rows = "、".join(f"{fg.qualname}({fg.file}:{fg.line})" for fg in shown)
|
|
195
|
+
return [(f"不在任何功能线上、项目里也没有别处用到的函数 {total} 个:{rows}{'……' if total > len(shown) else ''}。其中是业务入口的,"
|
|
196
|
+
f"在它的 def(有装饰器时是第一个装饰器)上面加一行注释 `{ENTRY_COMMENT} <标题>` 再重新分析,就会成一条功能线")]
|
pystepmap/external.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""项目外对象上的调用:没有 await 的调用里,哪些是"对外干活"(读写数据库、发请求、发邮件、调第三方服务),要画成步骤。
|
|
2
|
+
|
|
3
|
+
解析器只认得项目内的函数;被 await 的目标不明调用一向算步骤(await 多半是在等外部),同步写法的代码没有这个信号——
|
|
4
|
+
`db.execute(...)`、`requests.post(...)`、`session.add(...)` 全都不出节点,只包着它们的 if 也跟着消失,图上少掉的正是
|
|
5
|
+
业务规则。这里按"调用落在谁身上"补上这一类,不看方法名猜它做什么:
|
|
6
|
+
|
|
7
|
+
- 模块级的外部对象:从项目外、又不是纯计算的库导入的名字(`requests`、`smtplib`、`from flask_mail import mail`),
|
|
8
|
+
用这类库的调用建出来的模块级变量(`db = sqlite3.connect(...)`、`client = OpenAI()`),以及从项目里别的模块导入的
|
|
9
|
+
这种变量(`from app.db import db`);
|
|
10
|
+
- 函数里的外部对象:注解是这类库里的类的参数(`db: Session`)、默认值是 `Depends(...)` 又没有注解的参数,以及用上面
|
|
11
|
+
任何一种对象的调用结果赋值的局部变量(`cur = db.cursor()`、`with smtplib.SMTP(...) as s`);
|
|
12
|
+
- 方法里 `self.某属性.方法(...)`:类型多半不知道的协作对象(`self.session.commit()`、`self.client.post(...)`)。
|
|
13
|
+
|
|
14
|
+
不算的:构造对象(被调用的名字以大写字母开头,同项目内的构造调用);纯计算的库(PURE_TOPS:json、re、datetime……);
|
|
15
|
+
读数据、摆弄容器和字符串的方法(QUIET_METHODS:get、append、fetchone、json……,只对"对象上的对象"和局部变量生效,
|
|
16
|
+
`requests.get` 这种直接落在库上的不受影响);只是取请求、拼响应的框架函数(QUIET_IMPORTS);接在另一个调用结果后面的
|
|
17
|
+
调用(`db.execute(sql).fetchone()` 由 `db.execute` 代表)。配置 `external_calls: false` 关掉整个识别。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import ast
|
|
23
|
+
import builtins
|
|
24
|
+
|
|
25
|
+
from .index import FunctionInfo, ModuleInfo, ProjectIndex
|
|
26
|
+
|
|
27
|
+
# 纯计算、取时间、类型和数据结构的库:上面的调用不是"对外干活"
|
|
28
|
+
PURE_TOPS = frozenset({
|
|
29
|
+
"abc", "array", "base64", "binascii", "bisect", "builtins", "calendar", "cmath", "collections", "contextlib",
|
|
30
|
+
"copy", "dataclasses", "datetime", "decimal", "difflib", "enum", "fnmatch", "fractions", "functools", "glob",
|
|
31
|
+
"hashlib", "heapq", "hmac", "html", "inspect", "io", "itertools", "json", "keyword", "locale", "logging", "math",
|
|
32
|
+
"numbers", "operator", "os", "pathlib", "posixpath", "pprint", "random", "re", "secrets", "shlex", "statistics",
|
|
33
|
+
"string", "struct", "sys", "textwrap", "time", "traceback", "types", "typing", "unicodedata", "uuid", "warnings",
|
|
34
|
+
"weakref", "zoneinfo",
|
|
35
|
+
# 解析、压缩、并发原语、命令行参数:不是业务上的"对外"
|
|
36
|
+
"argparse", "ast", "asyncio", "codecs", "concurrent", "contextvars", "csv", "dis", "email", "gzip", "importlib", "ipaddress",
|
|
37
|
+
"platform", "signal", "threading", "tokenize", "xml", "zlib",
|
|
38
|
+
"annotated_types", "attr", "attrs", "bs4", "croniter", "dateutil", "jinja2", "jwt", "loguru", "lxml", "markdown",
|
|
39
|
+
"numpy", "opentelemetry", "orjson", "prometheus_client", "pydantic", "pydantic_core", "pydantic_settings",
|
|
40
|
+
"pystepkit", "pytz", "simplejson", "structlog", "tenacity", "typing_extensions", "ujson", "yaml",
|
|
41
|
+
})
|
|
42
|
+
PURE_PREFIXES = ("urllib.parse",)
|
|
43
|
+
|
|
44
|
+
# 拼查询语句的库:库里的函数(select、text、and_)只是在拼语句,不算步骤;但这些库的类当注解的参数(db: Session)、
|
|
45
|
+
# 用它们建出来的模块级对象(engine = create_engine(...))是真的在读写数据库
|
|
46
|
+
BUILDER_TOPS = frozenset({"sqlalchemy", "sqlmodel"})
|
|
47
|
+
|
|
48
|
+
# 日志、打点、命令行参数声明的方法名:落在什么对象上都不算步骤
|
|
49
|
+
NEVER_STEPS = frozenset({
|
|
50
|
+
"add_argument", "add_parser", "add_subparsers", "bind", "critical", "debug", "dec", "error", "exception", "inc",
|
|
51
|
+
"info", "labels", "log", "observe", "parse_args", "set_attribute", "set_defaults", "warn", "warning",
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
# 读数据、摆弄容器 / 字符串 / 查询结果的方法名:落在局部变量或"对象上的对象"上时不算步骤
|
|
55
|
+
QUIET_METHODS = frozenset({
|
|
56
|
+
"add_argument", "all", "append", "appendleft", "as_posix", "capitalize", "casefold", "clear", "close", "copy",
|
|
57
|
+
"count", "decode", "dict", "difference", "discard", "encode", "endswith", "extend", "fetchall", "fetchmany",
|
|
58
|
+
"fetchone", "find", "first", "format", "get", "get_json", "getlist", "group", "groupdict", "groups", "index",
|
|
59
|
+
"insert", "intersection", "isdigit", "isoformat", "items", "join", "json", "keys", "lower", "lstrip", "mappings",
|
|
60
|
+
"model_dump", "model_dump_json", "model_validate", "one", "one_or_none", "pop", "popleft", "raise_for_status",
|
|
61
|
+
"remove", "replace", "reverse", "rsplit", "rstrip", "scalar", "scalar_one", "scalar_one_or_none", "scalars",
|
|
62
|
+
"setdefault", "sort", "split", "splitlines", "startswith", "strftime", "strip", "timestamp", "title", "to_dict",
|
|
63
|
+
"tolist", "total_seconds", "union", "unique", "update", "upper", "values",
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
# 取请求、拼响应、声明参数的框架名字:不是业务步骤
|
|
67
|
+
QUIET_IMPORTS = frozenset({
|
|
68
|
+
"flask.request", "flask.g", "flask.session", "flask.current_app", "flask.jsonify", "flask.render_template",
|
|
69
|
+
"flask.render_template_string", "flask.redirect", "flask.url_for", "flask.abort", "flask.make_response",
|
|
70
|
+
"flask.flash", "flask.send_file", "flask.send_from_directory",
|
|
71
|
+
"fastapi.Depends", "fastapi.Query", "fastapi.Path", "fastapi.Body", "fastapi.Header", "fastapi.Cookie",
|
|
72
|
+
"fastapi.Form", "fastapi.File", "fastapi.Security",
|
|
73
|
+
"django.shortcuts.render", "django.shortcuts.redirect", "django.urls.reverse",
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _root(e: ast.expr) -> tuple[str | None, int, bool]:
|
|
78
|
+
"""表达式最左边的名字、名字后面跟了几段属性、中间有没有穿过调用或下标(`a.b().c`、`a[0].c`)。"""
|
|
79
|
+
depth, through = 0, False
|
|
80
|
+
while True:
|
|
81
|
+
if isinstance(e, ast.Name):
|
|
82
|
+
return e.id, depth, through
|
|
83
|
+
if isinstance(e, ast.Attribute):
|
|
84
|
+
depth, e = depth + 1, e.value
|
|
85
|
+
elif isinstance(e, ast.Call):
|
|
86
|
+
through, e = True, e.func
|
|
87
|
+
elif isinstance(e, ast.Subscript):
|
|
88
|
+
through, e = True, e.value
|
|
89
|
+
elif isinstance(e, ast.Await):
|
|
90
|
+
e = e.value
|
|
91
|
+
else:
|
|
92
|
+
return None, depth, through
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _attr_names(e: ast.expr) -> list[str]:
|
|
96
|
+
"""属性链上的各段名字(最左边的名字在内)。"""
|
|
97
|
+
out: list[str] = []
|
|
98
|
+
while isinstance(e, ast.Attribute | ast.Call | ast.Subscript):
|
|
99
|
+
if isinstance(e, ast.Attribute):
|
|
100
|
+
out.append(e.attr)
|
|
101
|
+
e = e.value
|
|
102
|
+
else:
|
|
103
|
+
e = e.func if isinstance(e, ast.Call) else e.value
|
|
104
|
+
if isinstance(e, ast.Name):
|
|
105
|
+
out.append(e.id)
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _called_name(call: ast.Call) -> str:
|
|
110
|
+
f = call.func
|
|
111
|
+
return f.id if isinstance(f, ast.Name) else f.attr if isinstance(f, ast.Attribute) else ""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _is_constructor(call: ast.Call) -> bool:
|
|
115
|
+
return _called_name(call)[:1].isupper()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class ExternalObjects:
|
|
119
|
+
"""整个项目共用:哪些点分名、哪些模块级名字是外部对象。"""
|
|
120
|
+
|
|
121
|
+
def __init__(self, index: ProjectIndex, noise_receivers: list[str]):
|
|
122
|
+
self.index = index
|
|
123
|
+
self.noise = set(noise_receivers)
|
|
124
|
+
self._tops = {d.split(".")[0] for d in [*index.by_dotted, *index.ambiguous]}
|
|
125
|
+
self._module_roots: dict[str, set[str]] = {}
|
|
126
|
+
self._plain: dict[tuple[str, str], set[str]] = {}
|
|
127
|
+
|
|
128
|
+
def external(self, dotted: str | None, builders: bool = True) -> bool:
|
|
129
|
+
"""点分全名在项目外、又不是纯计算的库里。builders=False 时拼查询语句的库(BUILDER_TOPS)也不算。"""
|
|
130
|
+
if not dotted or dotted.startswith(".") or dotted in QUIET_IMPORTS or dotted.startswith(PURE_PREFIXES):
|
|
131
|
+
return False
|
|
132
|
+
top = dotted.split(".")[0]
|
|
133
|
+
return top not in self._tops and top not in PURE_TOPS and (builders or top not in BUILDER_TOPS)
|
|
134
|
+
|
|
135
|
+
def plain_attrs(self, mod: ModuleInfo, cls_name: str) -> set[str]:
|
|
136
|
+
"""类的方法里用字面量、推导式、内置函数或纯计算库的调用赋过值的 self 属性(self.seen = set()、self.rows = []):
|
|
137
|
+
它们是普通的数据,上面的方法调用不是对外干活。"""
|
|
138
|
+
key = (mod.rel, cls_name)
|
|
139
|
+
found = self._plain.get(key)
|
|
140
|
+
if found is None:
|
|
141
|
+
found = self._plain[key] = set()
|
|
142
|
+
cls = mod.classes.get(cls_name)
|
|
143
|
+
for fkey in (cls.methods.values() if cls else ()):
|
|
144
|
+
fn = self.index.functions.get(fkey)
|
|
145
|
+
for n in (ast.walk(fn.node) if fn else ()):
|
|
146
|
+
if isinstance(n, ast.Assign | ast.AnnAssign) and n.value is not None and self._plain_value(n.value, mod):
|
|
147
|
+
targets = n.targets if isinstance(n, ast.Assign) else [n.target]
|
|
148
|
+
found |= {t.attr for t in targets if isinstance(t, ast.Attribute) and isinstance(t.value, ast.Name)}
|
|
149
|
+
return found
|
|
150
|
+
|
|
151
|
+
def _plain_value(self, value: ast.expr, mod: ModuleInfo) -> bool:
|
|
152
|
+
if isinstance(value, ast.Constant | ast.JoinedStr | ast.List | ast.Dict | ast.Set | ast.Tuple | ast.ListComp
|
|
153
|
+
| ast.DictComp | ast.SetComp | ast.BinOp | ast.Compare | ast.BoolOp):
|
|
154
|
+
return True
|
|
155
|
+
if isinstance(value, ast.Call):
|
|
156
|
+
name, _, _ = _root(value.func)
|
|
157
|
+
if name is None:
|
|
158
|
+
return False
|
|
159
|
+
if name in mod.imports:
|
|
160
|
+
return not self.external(mod.imports[name])
|
|
161
|
+
return hasattr(builtins, name)
|
|
162
|
+
return False
|
|
163
|
+
|
|
164
|
+
def _own_roots(self, mod: ModuleInfo) -> set[str]:
|
|
165
|
+
"""本模块自己绑定的外部对象:外部导入的名字、用外部库的调用建出来的模块级变量。"""
|
|
166
|
+
roots = {name for name, dotted in mod.imports.items() if self.external(dotted, builders=False)}
|
|
167
|
+
roots |= {name for name, dotted in mod.instances.items() if self.external(dotted)}
|
|
168
|
+
return roots
|
|
169
|
+
|
|
170
|
+
def module_roots(self, mod: ModuleInfo) -> set[str]:
|
|
171
|
+
found = self._module_roots.get(mod.rel)
|
|
172
|
+
if found is None:
|
|
173
|
+
found = self._own_roots(mod)
|
|
174
|
+
for name, dotted in mod.imports.items(): # from app.db import db:别的项目模块里的外部对象
|
|
175
|
+
owner, _, attr = dotted.rpartition(".")
|
|
176
|
+
rel = self.index.by_dotted.get(owner)
|
|
177
|
+
other = self.index.modules.get(rel) if rel else None
|
|
178
|
+
if other is not None and attr in other.instances and self.external(other.instances[attr]):
|
|
179
|
+
found.add(name)
|
|
180
|
+
self._module_roots[mod.rel] = found
|
|
181
|
+
return found
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class ExternalCalls:
|
|
185
|
+
"""一个函数里:哪些没有 await 的调用落在外部对象上。"""
|
|
186
|
+
|
|
187
|
+
def __init__(self, fn: FunctionInfo, objects: ExternalObjects):
|
|
188
|
+
self.objects = objects
|
|
189
|
+
self.mod = objects.index.modules[fn.file]
|
|
190
|
+
node = fn.node
|
|
191
|
+
a = node.args
|
|
192
|
+
params = [*a.posonlyargs, *a.args, *a.kwonlyargs]
|
|
193
|
+
decorators = {d.id for d in fn.decorators if isinstance(d, ast.Name)}
|
|
194
|
+
self.me = params[0].arg if fn.cls and params and "staticmethod" not in decorators else None
|
|
195
|
+
self.plain = objects.plain_attrs(self.mod, fn.cls) if self.me else set()
|
|
196
|
+
bound = {p.arg for p in [*params, a.vararg, a.kwarg] if p is not None}
|
|
197
|
+
stores = [n for st in node.body for n in self._walk(st) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)]
|
|
198
|
+
bound |= {n.id for n in stores}
|
|
199
|
+
self.globals = objects.module_roots(self.mod) - bound # 被局部名盖住的不算
|
|
200
|
+
self.locals: set[str] = set()
|
|
201
|
+
defaults = dict(zip([p.arg for p in [*a.posonlyargs, *a.args][::-1]], a.defaults[::-1]))
|
|
202
|
+
defaults |= {p.arg: d for p, d in zip(a.kwonlyargs, a.kw_defaults) if d is not None}
|
|
203
|
+
for p in params:
|
|
204
|
+
if p.annotation is not None:
|
|
205
|
+
if self._external_annotation(p.annotation):
|
|
206
|
+
self.locals.add(p.arg)
|
|
207
|
+
elif isinstance(defaults.get(p.arg), ast.Call) and _called_name(defaults[p.arg]) == "Depends":
|
|
208
|
+
self.locals.add(p.arg)
|
|
209
|
+
for _ in range(2): # 第二遍接住"先用后赋值"的写法(循环里)
|
|
210
|
+
for st in node.body:
|
|
211
|
+
for n in self._walk(st):
|
|
212
|
+
self._bind(n)
|
|
213
|
+
|
|
214
|
+
@staticmethod
|
|
215
|
+
def _walk(root: ast.AST):
|
|
216
|
+
stack = [root]
|
|
217
|
+
while stack:
|
|
218
|
+
n = stack.pop()
|
|
219
|
+
yield n
|
|
220
|
+
for c in ast.iter_child_nodes(n):
|
|
221
|
+
if not isinstance(c, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef | ast.Lambda):
|
|
222
|
+
stack.append(c)
|
|
223
|
+
|
|
224
|
+
def _external_annotation(self, ann: ast.expr) -> bool:
|
|
225
|
+
if isinstance(ann, ast.Constant) and isinstance(ann.value, str):
|
|
226
|
+
try:
|
|
227
|
+
ann = ast.parse(ann.value, mode="eval").body
|
|
228
|
+
except SyntaxError:
|
|
229
|
+
return False
|
|
230
|
+
if isinstance(ann, ast.Subscript): # Optional[Session]、Annotated[Session, Depends(...)]
|
|
231
|
+
inner = ann.slice.elts[0] if isinstance(ann.slice, ast.Tuple) and ann.slice.elts else ann.slice
|
|
232
|
+
return self._external_annotation(inner)
|
|
233
|
+
if isinstance(ann, ast.BinOp): # Session | None
|
|
234
|
+
return self._external_annotation(ann.left) or self._external_annotation(ann.right)
|
|
235
|
+
if isinstance(ann, ast.Name | ast.Attribute):
|
|
236
|
+
name, _, through = _root(ann)
|
|
237
|
+
return not through and name in self.mod.imports and self.objects.external(self.mod.imports[name])
|
|
238
|
+
return False
|
|
239
|
+
|
|
240
|
+
def _from_external(self, value: ast.expr | None) -> bool:
|
|
241
|
+
"""value 是落在外部对象上的调用(或对它的 await):它的结果也当外部对象。"""
|
|
242
|
+
if isinstance(value, ast.Await):
|
|
243
|
+
value = value.value
|
|
244
|
+
if not isinstance(value, ast.Call):
|
|
245
|
+
return False
|
|
246
|
+
name, _, _ = _root(value.func)
|
|
247
|
+
return name is not None and (name in self.globals or name in self.locals)
|
|
248
|
+
|
|
249
|
+
def _bind(self, n: ast.AST) -> None:
|
|
250
|
+
targets: list[ast.expr] = []
|
|
251
|
+
value: ast.expr | None = None
|
|
252
|
+
if isinstance(n, ast.Assign):
|
|
253
|
+
targets, value = n.targets, n.value
|
|
254
|
+
elif isinstance(n, ast.AnnAssign | ast.NamedExpr):
|
|
255
|
+
targets, value = [n.target], n.value
|
|
256
|
+
elif isinstance(n, ast.withitem) and n.optional_vars is not None:
|
|
257
|
+
targets, value = [n.optional_vars], n.context_expr
|
|
258
|
+
if self._from_external(value):
|
|
259
|
+
self.locals |= {t.id for t in targets if isinstance(t, ast.Name)}
|
|
260
|
+
|
|
261
|
+
def is_step(self, call: ast.Call) -> bool:
|
|
262
|
+
"""call(没有 await、没有解析到项目内函数)是不是落在外部对象上的干活的调用。"""
|
|
263
|
+
if _is_constructor(call) or _called_name(call) in NEVER_STEPS:
|
|
264
|
+
return False
|
|
265
|
+
func = call.func
|
|
266
|
+
if isinstance(func, ast.Name):
|
|
267
|
+
return func.id in self.globals
|
|
268
|
+
if not isinstance(func, ast.Attribute):
|
|
269
|
+
return False
|
|
270
|
+
name, depth, through = _root(func.value)
|
|
271
|
+
if name is None or through or set(_attr_names(func.value)) & self.objects.noise:
|
|
272
|
+
return False
|
|
273
|
+
quiet = func.attr in QUIET_METHODS or func.attr.startswith("__")
|
|
274
|
+
if name in self.globals:
|
|
275
|
+
return depth == 0 or not quiet
|
|
276
|
+
if name in self.locals:
|
|
277
|
+
return not quiet
|
|
278
|
+
if name != self.me or depth < 1 or quiet:
|
|
279
|
+
return False
|
|
280
|
+
return _attr_names(func.value)[-2] not in self.plain # self.<属性>.….方法():属性是普通数据时不算
|