build_codegraph.py
9.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""构建轻量代码图索引(app/ 的 Python + web/src 的 TS/TSX),供 query_codegraph.py 查询。
设计目标:探索代码时先查这个索引,而不是满仓 grep/整篇读文件 —— 省 token、省时间。
不追求完整的类型推断或跨语言精确调用图:Python 用标准库 ast 做到函数/类/调用/导入级别;
TS/TSX 用正则做到 import/export 级别(够用于「这个符号在哪定义」「这个文件依赖谁」)。
用法:
python tools/codegraph/build_codegraph.py
输出:tools/codegraph/graph.json(改动较大的代码后重新跑一次即可,没有自动 watch)。
"""
from __future__ import annotations
import ast
import json
import re
import sys
from pathlib import Path
from typing import Any
if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
ROOT = Path(__file__).resolve().parents[2]
OUT_PATH = Path(__file__).resolve().parent / "graph.json"
PY_ROOTS = ["app", "scripts", "tests"]
TS_ROOT = "web/src"
TS_EXTS = {".ts", ".tsx"}
# ---------------------------------------------------------------- Python ----
def _call_name(node: ast.Call) -> str | None:
f = node.func
if isinstance(f, ast.Name):
return f.id
if isinstance(f, ast.Attribute):
return f.attr
return None
def _decorator_src(dec: ast.expr, src: str) -> str:
seg = ast.get_source_segment(src, dec)
return seg or ""
def _first_doc_line(node: ast.AST) -> str:
doc = ast.get_docstring(node) or ""
return doc.strip().splitlines()[0].strip() if doc.strip() else ""
def _collect_calls(node: ast.AST) -> list[str]:
names: list[str] = []
for child in ast.walk(node):
if isinstance(child, ast.Call):
name = _call_name(child)
if name and not name.startswith("_"):
names.append(name)
# 去重但保序,最多留 40 个,避免超长函数把索引撑爆
seen: list[str] = []
for n in names:
if n not in seen:
seen.append(n)
return seen[:40]
def _def_entry(node: ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef, src: str, kind: str) -> dict[str, Any]:
entry: dict[str, Any] = {
"name": node.name,
"kind": kind,
"line": node.lineno,
"end_line": getattr(node, "end_lineno", node.lineno),
"doc": _first_doc_line(node),
}
decs = [_decorator_src(d, src) for d in getattr(node, "decorator_list", [])]
if decs:
entry["decorators"] = decs
if kind in ("function", "async function", "method", "async method"):
entry["calls"] = _collect_calls(node)
args = node.args
entry["params"] = [a.arg for a in args.args]
return entry
def parse_python_file(path: Path) -> dict[str, Any] | None:
src = path.read_text(encoding="utf-8", errors="replace")
try:
tree = ast.parse(src, filename=str(path))
except SyntaxError as e:
return {"lang": "python", "loc": src.count("\n") + 1, "error": f"parse error: {e}"}
imports: list[str] = []
symbols: list[dict[str, Any]] = []
for node in tree.body:
if isinstance(node, ast.Import):
imports.extend(a.name for a in node.names)
elif isinstance(node, ast.ImportFrom):
mod = ("." * node.level) + (node.module or "")
imports.extend(f"{mod}.{a.name}" if mod else a.name for a in node.names)
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
kind = "async function" if isinstance(node, ast.AsyncFunctionDef) else "function"
symbols.append(_def_entry(node, src, kind))
elif isinstance(node, ast.ClassDef):
cls_entry = _def_entry(node, src, "class")
bases = [ast.get_source_segment(src, b) or "" for b in node.bases]
if bases:
cls_entry["bases"] = bases
methods = []
for sub in node.body:
if isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef)):
mkind = "async method" if isinstance(sub, ast.AsyncFunctionDef) else "method"
methods.append(_def_entry(sub, src, mkind))
cls_entry["methods"] = methods
symbols.append(cls_entry)
return {
"lang": "python",
"loc": src.count("\n") + 1,
"doc": _first_doc_line(tree),
"imports": sorted(set(imports)),
"symbols": symbols,
}
# ---------------------------------------------------------------------------- TS/TSX ----
# 正则近似解析:足够定位「导出了什么 / 依赖了谁」,不做类型检查级别的精确度。
_IMPORT_RE = re.compile(
r'^\s*import\s+(?:type\s+)?(?P<clause>[^;]+?)\s+from\s+[\'"](?P<from>[^\'"]+)[\'"]', re.MULTILINE)
_EXPORT_FN_RE = re.compile(
r'^\s*export\s+(?:default\s+)?(?:async\s+)?function\s+(?P<name>\w+)', re.MULTILINE)
_EXPORT_CONST_RE = re.compile(
r'^\s*export\s+(?:default\s+)?const\s+(?P<name>\w+)', re.MULTILINE)
_EXPORT_CLASS_RE = re.compile(
r'^\s*export\s+(?:default\s+)?class\s+(?P<name>\w+)', re.MULTILINE)
_EXPORT_TYPE_RE = re.compile(
r'^\s*export\s+(?:interface|type)\s+(?P<name>\w+)', re.MULTILINE)
def parse_ts_file(path: Path) -> dict[str, Any]:
src = path.read_text(encoding="utf-8", errors="replace")
imports = []
for m in _IMPORT_RE.finditer(src):
clause = m.group("clause").strip()
names: list[str] = []
if clause.startswith("{"):
inner = clause.strip("{} ")
names = [n.strip().split(" as ")[0].strip() for n in inner.split(",") if n.strip()]
elif clause.startswith("*"):
names = [clause]
else:
head = clause.split(",")[0].strip()
if head:
names.append(head)
brace = re.search(r"\{([^}]*)\}", clause)
if brace:
names.extend(n.strip().split(" as ")[0].strip() for n in brace.group(1).split(",") if n.strip())
imports.append({"from": m.group("from"), "names": [n for n in names if n]})
symbols: list[dict[str, Any]] = []
for rx, kind in (
(_EXPORT_FN_RE, "function"),
(_EXPORT_CONST_RE, "const"),
(_EXPORT_CLASS_RE, "class"),
(_EXPORT_TYPE_RE, "type"),
):
for m in rx.finditer(src):
line = src.count("\n", 0, m.start()) + 1
symbols.append({"name": m.group("name"), "kind": kind, "line": line})
symbols.sort(key=lambda s: s["line"])
return {
"lang": "tsx" if path.suffix == ".tsx" else "ts",
"loc": src.count("\n") + 1,
"imports": imports,
"symbols": symbols,
}
# ---------------------------------------------------------------------------- driver ----
def build() -> dict[str, Any]:
files: dict[str, Any] = {}
for root_name in PY_ROOTS:
root = ROOT / root_name
if not root.exists():
continue
for p in sorted(root.rglob("*.py")):
if "__pycache__" in p.parts:
continue
rel = p.relative_to(ROOT).as_posix()
parsed = parse_python_file(p)
if parsed:
files[rel] = parsed
ts_root = ROOT / TS_ROOT
if ts_root.exists():
for p in sorted(ts_root.rglob("*")):
if p.suffix in TS_EXTS and p.is_file():
rel = p.relative_to(ROOT).as_posix()
files[rel] = parse_ts_file(p)
# 符号名 -> 定义位置(含类方法,命名为 Class.method)
symbol_index: dict[str, list[dict[str, Any]]] = {}
def index_symbol(name: str, file: str, line: int, kind: str) -> None:
symbol_index.setdefault(name, []).append({"file": file, "line": line, "kind": kind})
for rel, info in files.items():
for sym in info.get("symbols", []):
index_symbol(sym["name"], rel, sym["line"], sym["kind"])
for meth in sym.get("methods", []):
qualified = f"{sym['name']}.{meth['name']}"
index_symbol(qualified, rel, meth["line"], meth["kind"])
index_symbol(meth["name"], rel, meth["line"], meth["kind"])
# 反向依赖:谁 import 了这个文件(TS 用 @/ 别名指向 web/src,Python 用点号相对/绝对模块名)
imported_by: dict[str, list[str]] = {}
for rel, info in files.items():
if info.get("lang") == "python":
continue
for imp in info.get("imports", []):
frm = imp["from"]
if frm.startswith("@/"):
target = f"web/src/{frm[2:]}"
elif frm.startswith("."):
target = (Path(rel).parent / frm).as_posix()
else:
continue
for ext in ("", ".ts", ".tsx", "/index.ts", "/index.tsx"):
cand = target + ext
if cand in files:
imported_by.setdefault(cand, []).append(rel)
break
return {
"generated_at": __import__("datetime").datetime.now().isoformat(timespec="seconds"),
"file_count": len(files),
"files": files,
"symbol_index": symbol_index,
"imported_by": imported_by,
}
def main() -> None:
graph = build()
OUT_PATH.write_text(json.dumps(graph, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"codegraph: {graph['file_count']} 个文件, {len(graph['symbol_index'])} 个符号 -> {OUT_PATH}",
file=sys.stderr)
if __name__ == "__main__":
main()