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/index.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
"""项目索引:用 ast 扫描目录,建立模块、函数、类、导入与模块级实例的索引。只读,不执行被分析代码。
|
|
2
|
+
|
|
3
|
+
模块的点分名相对"源码根"计算(运行时 sys.path 上的目录)。源码根:
|
|
4
|
+
- 分析的目录本身;
|
|
5
|
+
- 名叫 src、本身不是包(没有 __init__.py)的目录;
|
|
6
|
+
- 本身不是包、上一级也不是包的目录,并且它直接包含一个包(有 __init__.py 的子目录,如仓库根下 backend/app 里的
|
|
7
|
+
backend),或者它直接包含的某个模块在项目里别的文件中被按顶层名绝对导入(脚本目录里的 import common)。
|
|
8
|
+
配置里给了 source_roots(相对分析目录的路径)时只用它们,不再检测。
|
|
9
|
+
每个模块按它所在的每个源码根各登记一个点分名(backend/app/x.py 同时是 app.x 和 backend.app.x),都指向同一个文件;
|
|
10
|
+
函数的 key 仍按相对分析目录的路径,不受影响。模块自己的点分名(相对导入按它展开)取包含它的最内层源码根。
|
|
11
|
+
分析的目录本身是包(含 __init__.py,如直接分析 backend/app)且是源码根时,它下面的模块还登记在"包名.相对点分名"
|
|
12
|
+
下(app.x;目录自己的 __init__.py 就是 app);包名是目录名,上级目录也含 __init__.py 时继续向上拼(backend.app),
|
|
13
|
+
这时包名链的每一段后缀都登记(app.x 和 backend.app.x:运行时 sys.path 上可以是 backend 的上级,也可以是 backend)。
|
|
14
|
+
同一个点分名在不同源码根下指向不同文件时:只有一个是所在文件自己的点分名的,登记那一个;否则不登记(记进
|
|
15
|
+
ambiguous,解析时记为无法判断,宁可不连线也不连错)。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import ast
|
|
21
|
+
import hashlib
|
|
22
|
+
import io
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import stat
|
|
26
|
+
import tokenize
|
|
27
|
+
from collections.abc import Iterator
|
|
28
|
+
from dataclasses import dataclass, field
|
|
29
|
+
from pathlib import Path, PurePosixPath
|
|
30
|
+
|
|
31
|
+
from .config import ConfigError, ProjectConfig
|
|
32
|
+
from .model import fn_key
|
|
33
|
+
|
|
34
|
+
FuncNode = ast.FunctionDef | ast.AsyncFunctionDef
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class FunctionInfo:
|
|
39
|
+
key: str
|
|
40
|
+
file: str
|
|
41
|
+
qualname: str
|
|
42
|
+
line: int
|
|
43
|
+
end_line: int
|
|
44
|
+
node: FuncNode
|
|
45
|
+
cls: str | None # 所属类名
|
|
46
|
+
parent: str | None # 外层函数的 key
|
|
47
|
+
decorators: list[ast.expr]
|
|
48
|
+
doc_title: str # 文档注释第一行,去掉反引号和 **
|
|
49
|
+
is_async: bool
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class ClassInfo:
|
|
54
|
+
name: str
|
|
55
|
+
file: str
|
|
56
|
+
line: int
|
|
57
|
+
bases: list[str]
|
|
58
|
+
decorators: list[ast.expr]
|
|
59
|
+
methods: dict[str, str] = field(default_factory=dict) # 方法名 -> key
|
|
60
|
+
aliases: dict[str, str] = field(default_factory=dict) # 类体里 m2 = m1 的别名 -> m1 的 key
|
|
61
|
+
other_bindings: set[str] = field(default_factory=set) # 类体里除了顶层 def 之外还有别的绑定(赋值、if 里的 def 等)的名字
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class ModuleInfo:
|
|
66
|
+
rel: str
|
|
67
|
+
dotted: str
|
|
68
|
+
tree: ast.Module
|
|
69
|
+
lines: list[str]
|
|
70
|
+
imports: dict[str, str] = field(default_factory=dict) # 本地名 -> 点分全名
|
|
71
|
+
functions: dict[str, str] = field(default_factory=dict) # 模块级函数名 -> key
|
|
72
|
+
classes: dict[str, ClassInfo] = field(default_factory=dict)
|
|
73
|
+
instances: dict[str, str] = field(default_factory=dict) # 模块级变量名 -> 类的点分全名
|
|
74
|
+
# 模块级 name = 名字 / 属性 的候选别名 -> 右边(name 在模块里的每次绑定都是这样、右边都一样;其余条件见
|
|
75
|
+
# _module_aliases);右边是不是项目内函数由解析器判断
|
|
76
|
+
aliases: dict[str, ast.expr] = field(default_factory=dict)
|
|
77
|
+
source_root: str = "" # 包含它的最内层源码根(相对路径,"" 是分析的目录本身)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class ProjectIndex:
|
|
82
|
+
root: Path
|
|
83
|
+
modules: dict[str, ModuleInfo] = field(default_factory=dict) # 以相对路径为键
|
|
84
|
+
by_dotted: dict[str, str] = field(default_factory=dict) # 点分模块名(每个源码根下各一个)-> 相对路径
|
|
85
|
+
functions: dict[str, FunctionInfo] = field(default_factory=dict) # 以 key 为键
|
|
86
|
+
skipped: list[tuple[str, str]] = field(default_factory=list)
|
|
87
|
+
hashes: dict[str, str] = field(default_factory=dict) # 相对路径 -> 内容 sha256
|
|
88
|
+
source_roots: list[str] = field(default_factory=list) # 相对路径,"" 是分析的目录本身;排序
|
|
89
|
+
ambiguous: set[str] = field(default_factory=set) # 在不同源码根下指向不同文件、没有登记的点分名
|
|
90
|
+
excluded: dict[str, int] = field(default_factory=dict) # 实际排除掉的目录名 -> 个数
|
|
91
|
+
package: str = "" # 分析的目录本身是包、且是源码根时它的点分名(app、pkg.app),否则为空
|
|
92
|
+
classes: list[ClassInfo] = field(default_factory=list) # 全部类,含嵌套在函数、类里的
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _doc_title(node: FuncNode) -> str:
|
|
96
|
+
doc = ast.get_docstring(node)
|
|
97
|
+
if not doc:
|
|
98
|
+
return ""
|
|
99
|
+
first = doc.strip().splitlines()[0] if doc.strip() else ""
|
|
100
|
+
return first.replace("`", "").replace("**", "").strip()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _dotted_name(rel: str, source_root: str = "") -> str:
|
|
104
|
+
"""rel 相对源码根 source_root 的点分名(source_root 为 "" 时相对分析的目录)。"""
|
|
105
|
+
parts = rel[len(source_root) + 1 if source_root else 0: -3].split("/")
|
|
106
|
+
if parts[-1] == "__init__":
|
|
107
|
+
parts = parts[:-1]
|
|
108
|
+
return ".".join(parts)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _under(rel: str, source_root: str) -> bool:
|
|
112
|
+
return not source_root or rel.startswith(source_root + "/")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _parent(d: str) -> str:
|
|
116
|
+
return d.rpartition("/")[0]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _absolute_import_tops(tree: ast.Module) -> set[str]:
|
|
120
|
+
"""模块里(含函数体里)绝对导入的顶层名:import a.b → a,from a.b import c → a。"""
|
|
121
|
+
tops: set[str] = set()
|
|
122
|
+
for n in ast.walk(tree):
|
|
123
|
+
if isinstance(n, ast.Import):
|
|
124
|
+
tops.update(a.name.split(".")[0] for a in n.names)
|
|
125
|
+
elif isinstance(n, ast.ImportFrom) and not n.level and n.module:
|
|
126
|
+
tops.add(n.module.split(".")[0])
|
|
127
|
+
return tops
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _detect_source_roots(files: list[str], trees: dict[str, ast.Module]) -> list[str]:
|
|
131
|
+
"""按模块说明里的规则检测源码根。files:全部 .py 文件(含解析失败的);trees:解析成功的。"""
|
|
132
|
+
packages = {_parent(f) for f in files if f.rpartition("/")[2] == "__init__.py"}
|
|
133
|
+
modules_in: dict[str, list[str]] = {} # 目录 -> 直接在其中的模块文件(不含 __init__.py)
|
|
134
|
+
dirs: set[str] = set()
|
|
135
|
+
for f in files:
|
|
136
|
+
d, name = f.rpartition("/")[::2]
|
|
137
|
+
if name != "__init__.py":
|
|
138
|
+
modules_in.setdefault(d, []).append(f)
|
|
139
|
+
while d and d not in dirs:
|
|
140
|
+
dirs.add(d)
|
|
141
|
+
d = _parent(d)
|
|
142
|
+
importers: dict[str, set[str]] = {} # 顶层名 -> 按这个名字绝对导入它的文件
|
|
143
|
+
for rel, tree in trees.items():
|
|
144
|
+
for top in _absolute_import_tops(tree):
|
|
145
|
+
importers.setdefault(top, set()).add(rel)
|
|
146
|
+
roots = {""}
|
|
147
|
+
for d in dirs:
|
|
148
|
+
if d in packages:
|
|
149
|
+
continue
|
|
150
|
+
if d.rpartition("/")[2] == "src":
|
|
151
|
+
roots.add(d)
|
|
152
|
+
continue
|
|
153
|
+
if _parent(d) in packages: # 包里没有 __init__.py 的子目录是命名空间子包,不是源码根
|
|
154
|
+
continue
|
|
155
|
+
has_package = any(_parent(p) == d for p in packages)
|
|
156
|
+
imported = any(importers.get(f.rpartition("/")[2][:-3], set()) - {f} for f in modules_in.get(d, ()))
|
|
157
|
+
if has_package or imported:
|
|
158
|
+
roots.add(d)
|
|
159
|
+
return sorted(roots)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _configured_source_roots(root: Path, given: list[str]) -> list[str]:
|
|
163
|
+
out: set[str] = set()
|
|
164
|
+
for raw in given:
|
|
165
|
+
p = PurePosixPath(raw)
|
|
166
|
+
if p.is_absolute() or ".." in p.parts:
|
|
167
|
+
raise ConfigError(f"source_roots 里的路径必须在项目目录之内:{raw}")
|
|
168
|
+
rel = "" if str(p) == "." else str(p)
|
|
169
|
+
if not (root / rel).is_dir():
|
|
170
|
+
raise ConfigError(f"source_roots 里的目录不存在:{raw}")
|
|
171
|
+
out.add(rel)
|
|
172
|
+
return sorted(out)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _package_name(root: Path) -> str:
|
|
176
|
+
"""root 本身是包(含 __init__.py)时它的点分名:目录名,上级目录也是包时继续向上拼,直到不是包为止;不是包时为空。
|
|
177
|
+
只看文件在不在,不读内容。"""
|
|
178
|
+
parts: list[str] = []
|
|
179
|
+
d = root
|
|
180
|
+
while d.name.isidentifier() and (d / "__init__.py").is_file():
|
|
181
|
+
parts.append(d.name)
|
|
182
|
+
d = d.parent
|
|
183
|
+
return ".".join(reversed(parts))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _package_prefixes(package: str) -> list[str]:
|
|
187
|
+
"""包名链的每一段后缀,由短到长:backend.app → app、backend.app;空串没有。"""
|
|
188
|
+
parts = package.split(".") if package else []
|
|
189
|
+
return [".".join(parts[i:]) for i in reversed(range(len(parts)))]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _register(index: ProjectIndex) -> None:
|
|
193
|
+
"""按每个源码根登记点分名(见模块说明)。"""
|
|
194
|
+
names: dict[str, dict[str, bool]] = {} # 点分名 -> {相对路径: 是否是这个文件自己的点分名}
|
|
195
|
+
|
|
196
|
+
def add(name: str, rel: str, own: bool) -> None:
|
|
197
|
+
files = names.setdefault(name, {})
|
|
198
|
+
files[rel] = files.get(rel, False) or own
|
|
199
|
+
|
|
200
|
+
prefixes = _package_prefixes(index.package)
|
|
201
|
+
for rel, mod in index.modules.items():
|
|
202
|
+
for sr in index.source_roots:
|
|
203
|
+
if _under(rel, sr):
|
|
204
|
+
name = _dotted_name(rel, sr)
|
|
205
|
+
if name: # 源码根自己的 __init__.py 没有点分名
|
|
206
|
+
add(name, rel, name == mod.dotted)
|
|
207
|
+
if not sr: # 分析的目录本身是包:同时登记在包名链的每一段后缀下,它的 __init__.py 就是包本身
|
|
208
|
+
for prefix in prefixes:
|
|
209
|
+
add(f"{prefix}.{name}" if name else prefix, rel, name == mod.dotted)
|
|
210
|
+
for name, files in names.items():
|
|
211
|
+
own = [rel for rel, is_own in files.items() if is_own]
|
|
212
|
+
pool = own or list(files)
|
|
213
|
+
if len(pool) == 1:
|
|
214
|
+
index.by_dotted[name] = pool[0]
|
|
215
|
+
else:
|
|
216
|
+
index.ambiguous.add(name)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _attr_chain(node: ast.expr) -> list[str] | None:
|
|
220
|
+
parts: list[str] = []
|
|
221
|
+
while isinstance(node, ast.Attribute):
|
|
222
|
+
parts.append(node.attr)
|
|
223
|
+
node = node.value
|
|
224
|
+
if isinstance(node, ast.Name):
|
|
225
|
+
parts.append(node.id)
|
|
226
|
+
return parts[::-1]
|
|
227
|
+
return None
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def import_bindings(n: ast.Import | ast.ImportFrom, mod: ModuleInfo) -> list[tuple[str, str]]:
|
|
231
|
+
"""一条 import 语句绑定的 (本地名, 点分全名)。星号导入、越界的相对导入不绑定。"""
|
|
232
|
+
if isinstance(n, ast.Import):
|
|
233
|
+
return [(a.asname, a.name) if a.asname else (a.name.split(".")[0],) * 2 for a in n.names]
|
|
234
|
+
if n.level:
|
|
235
|
+
package = mod.dotted if mod.rel.endswith("__init__.py") else mod.dotted.rpartition(".")[0]
|
|
236
|
+
pkg_parts = package.split(".") if package else []
|
|
237
|
+
up = n.level - 1
|
|
238
|
+
if up > len(pkg_parts):
|
|
239
|
+
return []
|
|
240
|
+
base = ".".join(pkg_parts[: len(pkg_parts) - up] + ([n.module] if n.module else []))
|
|
241
|
+
else:
|
|
242
|
+
base = n.module or ""
|
|
243
|
+
return [(a.asname or a.name, f"{base}.{a.name}" if base else a.name) for a in n.names if a.name != "*"]
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _collect_imports(mod: ModuleInfo) -> None:
|
|
247
|
+
"""整个模块(含函数体里)的 import;同一个本地名只记第一次(广度优先,模块级的先到)。"""
|
|
248
|
+
for n in ast.walk(mod.tree):
|
|
249
|
+
if isinstance(n, ast.Import | ast.ImportFrom):
|
|
250
|
+
for name, target in import_bindings(n, mod):
|
|
251
|
+
mod.imports.setdefault(name, target)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _scope_bindings(stmts: list[ast.stmt]) -> dict[str, list[ast.expr | None]]:
|
|
255
|
+
"""一个作用域(模块或类体)里每个名字的全部绑定,按出现顺序:name = 名字 / 属性(可以连写 a = b = f、带注解)
|
|
256
|
+
给出右边;其余绑定(def、class、import、别的赋值、for / with / except / match 的目标、del 等)为 None。
|
|
257
|
+
进入 if / try 等复合语句,不进入嵌套函数、类、lambda 的体。"""
|
|
258
|
+
out: dict[str, list[ast.expr | None]] = {}
|
|
259
|
+
|
|
260
|
+
def add(name: str, value: ast.expr | None) -> None:
|
|
261
|
+
out.setdefault(name, []).append(value)
|
|
262
|
+
|
|
263
|
+
def visit(n: ast.AST) -> None:
|
|
264
|
+
if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
|
|
265
|
+
add(n.name, None)
|
|
266
|
+
return
|
|
267
|
+
if isinstance(n, ast.Lambda):
|
|
268
|
+
return
|
|
269
|
+
if isinstance(n, ast.Assign) and isinstance(n.value, ast.Name | ast.Attribute) \
|
|
270
|
+
and all(isinstance(t, ast.Name) for t in n.targets):
|
|
271
|
+
for t in n.targets:
|
|
272
|
+
add(t.id, n.value)
|
|
273
|
+
return
|
|
274
|
+
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
|
|
275
|
+
if n.value is not None: # 只有注解、没有值的不绑定
|
|
276
|
+
add(n.target.id, n.value if isinstance(n.value, ast.Name | ast.Attribute) else None)
|
|
277
|
+
return
|
|
278
|
+
if isinstance(n, ast.Import | ast.ImportFrom):
|
|
279
|
+
for a in n.names:
|
|
280
|
+
add(a.asname or a.name.split(".")[0], None)
|
|
281
|
+
return
|
|
282
|
+
if isinstance(n, ast.Name) and not isinstance(n.ctx, ast.Load):
|
|
283
|
+
add(n.id, None)
|
|
284
|
+
elif isinstance(n, ast.ExceptHandler | ast.MatchAs | ast.MatchStar) and n.name:
|
|
285
|
+
add(n.name, None)
|
|
286
|
+
elif isinstance(n, ast.MatchMapping) and n.rest:
|
|
287
|
+
add(n.rest, None)
|
|
288
|
+
for c in ast.iter_child_nodes(n):
|
|
289
|
+
visit(c)
|
|
290
|
+
|
|
291
|
+
for st in stmts:
|
|
292
|
+
visit(st)
|
|
293
|
+
return out
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _alias_candidates(bindings: dict[str, list[ast.expr | None]]) -> dict[str, ast.expr]:
|
|
297
|
+
"""每次绑定都是 name = 同一个名字 / 属性 的名字 -> 右边。赋值两次但右边不同、或还有别的绑定的不算。"""
|
|
298
|
+
out: dict[str, ast.expr] = {}
|
|
299
|
+
for name, values in bindings.items():
|
|
300
|
+
first = values[0]
|
|
301
|
+
if first is not None and all(v is not None and ast.dump(v) == ast.dump(first) for v in values[1:]):
|
|
302
|
+
out[name] = first
|
|
303
|
+
return out
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _root_name(e: ast.expr) -> str | None:
|
|
307
|
+
"""名字或属性链最左边的名字:f → f,mod.sub.f → mod。"""
|
|
308
|
+
while isinstance(e, ast.Attribute):
|
|
309
|
+
e = e.value
|
|
310
|
+
return e.id if isinstance(e, ast.Name) else None
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _module_aliases(tree: ast.Module) -> dict[str, ast.expr]:
|
|
314
|
+
"""模块级别名的候选(见 ModuleInfo.aliases)。有模块级的 from x import * 时一个都不算(它能绑定任何名字);
|
|
315
|
+
在函数里声明 global 的名字不算(函数里会改写);右边最左边的名字在模块里不是恰好绑定一次的不算(try 里导入、
|
|
316
|
+
except 里再定义的同名函数,定义了两次的函数)。"""
|
|
317
|
+
bindings = _scope_bindings(tree.body)
|
|
318
|
+
if "*" in bindings: # from x import * 在 _scope_bindings 里绑定的名字是 *
|
|
319
|
+
return {}
|
|
320
|
+
rebound = {name for n in ast.walk(tree) if isinstance(n, ast.Global) for name in n.names}
|
|
321
|
+
out: dict[str, ast.expr] = {}
|
|
322
|
+
for name, rhs in _alias_candidates(bindings).items():
|
|
323
|
+
root = _root_name(rhs)
|
|
324
|
+
if name not in rebound and root not in rebound and len(bindings.get(root, ())) == 1:
|
|
325
|
+
out[name] = rhs
|
|
326
|
+
return out
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _collect_class_body(info: ClassInfo, body: list[ast.stmt], def_lines: dict[str, int]) -> None:
|
|
330
|
+
"""类体里的别名和别的绑定。m2 = m1:m1 是这个类上只定义了一次、定义写在这句之前的方法(或这样的别名)时,m2
|
|
331
|
+
记为它的别名。def_lines:顶层方法名 -> def 所在行。"""
|
|
332
|
+
bindings = _scope_bindings(body)
|
|
333
|
+
top_defs: dict[str, int] = {}
|
|
334
|
+
for st in body:
|
|
335
|
+
if isinstance(st, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
336
|
+
top_defs[st.name] = top_defs.get(st.name, 0) + 1
|
|
337
|
+
info.other_bindings = {name for name, values in bindings.items() if len(values) > top_defs.get(name, 0)}
|
|
338
|
+
candidates = _alias_candidates(bindings)
|
|
339
|
+
|
|
340
|
+
def target(name: str, before: int, depth: int) -> str | None:
|
|
341
|
+
"""name 在第 before 行时指向的方法 key。"""
|
|
342
|
+
if name in info.methods:
|
|
343
|
+
ok = len(bindings.get(name, ())) == 1 and def_lines[name] < before
|
|
344
|
+
return info.methods[name] if ok else None
|
|
345
|
+
rhs = candidates.get(name)
|
|
346
|
+
if isinstance(rhs, ast.Name) and rhs.lineno < before and depth < 10:
|
|
347
|
+
return target(rhs.id, rhs.lineno, depth + 1)
|
|
348
|
+
return None
|
|
349
|
+
|
|
350
|
+
for name, rhs in candidates.items():
|
|
351
|
+
key = target(rhs.id, rhs.lineno, 0) if isinstance(rhs, ast.Name) else None
|
|
352
|
+
if key:
|
|
353
|
+
info.aliases[name] = key
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _collect_defs(mod: ModuleInfo, index: ProjectIndex) -> None:
|
|
357
|
+
def add_function(node: FuncNode, prefix: str, cls: str | None, parent: str | None, top: bool) -> str:
|
|
358
|
+
qual = prefix + node.name
|
|
359
|
+
key = fn_key(mod.rel, qual, node.lineno)
|
|
360
|
+
index.functions[key] = FunctionInfo(
|
|
361
|
+
key=key, file=mod.rel, qualname=qual, line=node.lineno,
|
|
362
|
+
end_line=node.end_lineno or node.lineno, node=node, cls=cls, parent=parent,
|
|
363
|
+
decorators=list(node.decorator_list), doc_title=_doc_title(node),
|
|
364
|
+
is_async=isinstance(node, ast.AsyncFunctionDef))
|
|
365
|
+
if top:
|
|
366
|
+
mod.functions[node.name] = key
|
|
367
|
+
walk(node.body, qual + ".<locals>.", None, key, False)
|
|
368
|
+
return key
|
|
369
|
+
|
|
370
|
+
def add_class(node: ast.ClassDef, prefix: str, parent: str | None, top: bool) -> None:
|
|
371
|
+
qual = prefix + node.name
|
|
372
|
+
info = ClassInfo(name=node.name, file=mod.rel, line=node.lineno,
|
|
373
|
+
bases=[ast.unparse(b) for b in node.bases], decorators=list(node.decorator_list))
|
|
374
|
+
index.classes.append(info)
|
|
375
|
+
if top:
|
|
376
|
+
mod.classes[node.name] = info
|
|
377
|
+
def_lines: dict[str, int] = {}
|
|
378
|
+
for st in node.body:
|
|
379
|
+
if isinstance(st, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
380
|
+
key = add_function(st, qual + ".", node.name, parent, False)
|
|
381
|
+
info.methods[st.name] = key
|
|
382
|
+
def_lines[st.name] = st.lineno
|
|
383
|
+
else:
|
|
384
|
+
walk([st], qual + ".", node.name, parent, False)
|
|
385
|
+
_collect_class_body(info, node.body, def_lines)
|
|
386
|
+
|
|
387
|
+
def walk(stmts: list[ast.stmt], prefix: str, cls: str | None, parent: str | None, top: bool) -> None:
|
|
388
|
+
for st in stmts:
|
|
389
|
+
if isinstance(st, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
390
|
+
add_function(st, prefix, cls, parent, top)
|
|
391
|
+
elif isinstance(st, ast.ClassDef):
|
|
392
|
+
add_class(st, prefix, parent, top)
|
|
393
|
+
else:
|
|
394
|
+
# if / try / with / for 等复合语句里的定义
|
|
395
|
+
for child in ast.iter_child_nodes(st):
|
|
396
|
+
if isinstance(child, ast.stmt):
|
|
397
|
+
walk([child], prefix, cls, parent, top)
|
|
398
|
+
elif isinstance(child, ast.excepthandler | ast.match_case):
|
|
399
|
+
walk(child.body, prefix, cls, parent, top)
|
|
400
|
+
|
|
401
|
+
walk(mod.tree.body, "", None, None, True)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _collect_instances(mod: ModuleInfo) -> None:
|
|
405
|
+
for st in mod.tree.body:
|
|
406
|
+
if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name):
|
|
407
|
+
target, value = st.targets[0].id, st.value
|
|
408
|
+
elif isinstance(st, ast.AnnAssign) and isinstance(st.target, ast.Name) and st.value is not None:
|
|
409
|
+
target, value = st.target.id, st.value
|
|
410
|
+
else:
|
|
411
|
+
continue
|
|
412
|
+
if not isinstance(value, ast.Call):
|
|
413
|
+
continue
|
|
414
|
+
chain = _attr_chain(value.func)
|
|
415
|
+
if not chain:
|
|
416
|
+
continue
|
|
417
|
+
head, rest = chain[0], chain[1:]
|
|
418
|
+
if not rest and head in mod.classes:
|
|
419
|
+
mod.instances[target] = f"{mod.dotted}.{head}"
|
|
420
|
+
elif head in mod.imports:
|
|
421
|
+
mod.instances[target] = ".".join([mod.imports[head], *rest])
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def source_lines(text: str) -> list[str]:
|
|
425
|
+
"""源码按解析器的规则分行:只在 \\r\\n、\\r、\\n 处分(str.splitlines 还会在换页符、\\x1c、\\u2028 等处分,行号
|
|
426
|
+
就错了);末尾的换行不多出一个空行。"""
|
|
427
|
+
lines = re.split(r"\r\n|\r|\n", text)
|
|
428
|
+
if lines[-1] == "":
|
|
429
|
+
lines.pop()
|
|
430
|
+
return lines
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def decode_source(raw: bytes) -> str:
|
|
434
|
+
"""源文件的文本:按 PEP 263 的编码声明或 BOM 解码(没有时是 UTF-8),去掉 BOM。"""
|
|
435
|
+
encoding, _ = tokenize.detect_encoding(io.BytesIO(raw).readline)
|
|
436
|
+
return raw.decode(encoding)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _iter_py_files(root: Path, exclude: set[str], excluded: dict[str, int]):
|
|
440
|
+
"""root 下的 .py 文件,按路径排序;跳过的排除目录按名字计数进 excluded。符号链接的目录不进入(os.walk 默认)。"""
|
|
441
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
442
|
+
for d in dirnames:
|
|
443
|
+
if d in exclude:
|
|
444
|
+
excluded[d] = excluded.get(d, 0) + 1
|
|
445
|
+
dirnames[:] = sorted(d for d in dirnames if d not in exclude)
|
|
446
|
+
for fn in sorted(filenames):
|
|
447
|
+
if fn.endswith(".py"):
|
|
448
|
+
yield Path(dirpath) / fn
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
LINK_OUTSIDE = "符号链接指向项目之外"
|
|
452
|
+
NOT_REGULAR = "不是普通文件"
|
|
453
|
+
LINK_NOT_PY = "符号链接指向的不是 .py 文件"
|
|
454
|
+
# 这些路径不是项目里的源文件,从不打开:pystepmap check 把它们列成警告,不算"解析不了"
|
|
455
|
+
NOT_SOURCE_REASONS = frozenset({LINK_OUTSIDE, NOT_REGULAR, LINK_NOT_PY})
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _unreadable_reason(path: Path, root: Path) -> str | None:
|
|
459
|
+
"""不能当源码读的 .py 路径的原因:符号链接指向分析目录之外(LINK_OUTSIDE);解析后不是普通文件(FIFO、设备等,
|
|
460
|
+
NOT_REGULAR);项目之内的链接指向的不是 .py 文件(LINK_NOT_PY:读源码的接口只给 .py 文件,分析了也看不到源码)。
|
|
461
|
+
这样的路径从不打开:读 FIFO 会一直等,读 /dev/zero 读不完。root 是解析过的绝对路径。项目之内指向 .py 普通文件的
|
|
462
|
+
符号链接照常读(按链接自己的路径登记);失效的链接(目标在项目之内但不存在)返回 None,交给后面的读取照常报
|
|
463
|
+
"无法解析"。"""
|
|
464
|
+
real = None
|
|
465
|
+
try:
|
|
466
|
+
st = os.lstat(path)
|
|
467
|
+
if stat.S_ISLNK(st.st_mode):
|
|
468
|
+
real = os.path.realpath(path)
|
|
469
|
+
if os.path.commonpath([real, str(root)]) != str(root):
|
|
470
|
+
return LINK_OUTSIDE
|
|
471
|
+
st = os.stat(path)
|
|
472
|
+
except OSError:
|
|
473
|
+
return None
|
|
474
|
+
if not stat.S_ISREG(st.st_mode):
|
|
475
|
+
return NOT_REGULAR
|
|
476
|
+
if real is not None and not real.endswith(".py"):
|
|
477
|
+
return LINK_NOT_PY
|
|
478
|
+
return None
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def iter_source_files(root: Path, config: ProjectConfig, excluded: dict[str, int] | None = None
|
|
482
|
+
) -> Iterator[tuple[str, Path | None, str]]:
|
|
483
|
+
"""按 build_index 的规则列出 root 下每个 .py,按路径排序:(相对路径, 可读时的路径 | None, 不读的原因)。
|
|
484
|
+
排除目录(config.exclude_dirs,任何一层)不进入,跳过的按名字计数进 excluded(给出时);符号链接的目录不进入。
|
|
485
|
+
不读的路径(见 _unreadable_reason)给 (相对路径, None, 原因),从不打开;其余给 (相对路径, 路径, ""),读不读得出来
|
|
486
|
+
由调用方处理。root 先解析成绝对路径(和 build_index 一样)。"""
|
|
487
|
+
root = Path(root).resolve()
|
|
488
|
+
for path in _iter_py_files(root, set(config.exclude_dirs), {} if excluded is None else excluded):
|
|
489
|
+
rel = path.relative_to(root).as_posix()
|
|
490
|
+
unreadable = _unreadable_reason(path, root)
|
|
491
|
+
yield (rel, None, unreadable) if unreadable else (rel, path, "")
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def build_index(root: Path, config: ProjectConfig) -> ProjectIndex:
|
|
495
|
+
root = Path(root).resolve() # 图里记的根目录总是绝对路径:核对时从别的工作目录也能找到源码
|
|
496
|
+
index = ProjectIndex(root=root)
|
|
497
|
+
configured = _configured_source_roots(root, config.source_roots) if config.source_roots is not None else None
|
|
498
|
+
files: list[str] = []
|
|
499
|
+
parsed: dict[str, tuple[ast.Module, str]] = {}
|
|
500
|
+
for rel, path, unreadable in iter_source_files(root, config, index.excluded):
|
|
501
|
+
if path is None:
|
|
502
|
+
index.skipped.append((rel, unreadable))
|
|
503
|
+
continue
|
|
504
|
+
files.append(rel)
|
|
505
|
+
try:
|
|
506
|
+
raw = path.read_bytes()
|
|
507
|
+
index.hashes[rel] = hashlib.sha256(raw).hexdigest()
|
|
508
|
+
tree = ast.parse(raw, filename=rel) # 字节:编码声明、BOM 由解析器处理
|
|
509
|
+
text = decode_source(raw)
|
|
510
|
+
except UnicodeDecodeError as e:
|
|
511
|
+
index.skipped.append((rel, f"无法按声明的编码解码:{e.reason}"))
|
|
512
|
+
continue
|
|
513
|
+
except (SyntaxError, ValueError, RecursionError, OSError) as e:
|
|
514
|
+
index.skipped.append((rel, f"无法解析:{type(e).__name__}: {e}"))
|
|
515
|
+
continue
|
|
516
|
+
parsed[rel] = (tree, text)
|
|
517
|
+
roots = configured if configured is not None else _detect_source_roots(files, {r: t for r, (t, _) in parsed.items()})
|
|
518
|
+
index.source_roots = roots
|
|
519
|
+
index.package = _package_name(root) if "" in roots else ""
|
|
520
|
+
for rel, (tree, text) in parsed.items():
|
|
521
|
+
own = max((sr for sr in roots if _under(rel, sr)), key=len, default="") # 包含它的最内层源码根
|
|
522
|
+
mod = ModuleInfo(rel=rel, dotted=_dotted_name(rel, own), tree=tree, lines=source_lines(text), source_root=own)
|
|
523
|
+
_collect_imports(mod)
|
|
524
|
+
_collect_defs(mod, index)
|
|
525
|
+
_collect_instances(mod)
|
|
526
|
+
mod.aliases = _module_aliases(tree)
|
|
527
|
+
index.modules[rel] = mod
|
|
528
|
+
_register(index)
|
|
529
|
+
return index
|