query_codegraph.py
6.2 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
"""查询 codegraph(见 build_codegraph.py)。探索这个项目代码时优先用它,而不是大范围 grep。
用法:
python tools/codegraph/query_codegraph.py stats
python tools/codegraph/query_codegraph.py file app/api/documents.py
python tools/codegraph/query_codegraph.py symbol run_extract
python tools/codegraph/query_codegraph.py search extract
python tools/codegraph/query_codegraph.py callers parse_file
python tools/codegraph/query_codegraph.py importers web/src/lib/api.ts
索引可能落后于最新代码(没有自动 watch);改动较大后先重建:
python tools/codegraph/build_codegraph.py
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
GRAPH_PATH = Path(__file__).resolve().parent / "graph.json"
def load() -> dict:
if not GRAPH_PATH.exists():
print("graph.json 不存在,先运行: python tools/codegraph/build_codegraph.py", file=sys.stderr)
sys.exit(1)
return json.loads(GRAPH_PATH.read_text(encoding="utf-8"))
def cmd_stats(g: dict, _args: list[str]) -> None:
py = sum(1 for f in g["files"].values() if f.get("lang") == "python")
ts = g["file_count"] - py
print(f"生成时间: {g['generated_at']}")
print(f"文件: {g['file_count']}(python {py} / ts+tsx {ts})")
print(f"符号: {len(g['symbol_index'])}")
def cmd_file(g: dict, args: list[str]) -> None:
if not args:
print("用法: file <path>,如 app/api/documents.py", file=sys.stderr)
return
path = args[0].replace("\\", "/")
info = g["files"].get(path)
if not info:
matches = [p for p in g["files"] if path in p]
print(f"未找到 {path}" + (f",相似路径:\n " + "\n ".join(matches[:10]) if matches else ""))
return
print(f"{path} [{info.get('lang')}] {info.get('loc')} 行")
if info.get("doc"):
print(f" 文档: {info['doc']}")
if info.get("error"):
print(f" 解析错误: {info['error']}")
imports = info.get("imports") or []
if imports:
print(f" imports ({len(imports)}):")
for imp in imports[:30]:
if isinstance(imp, dict):
print(f" - {imp['from']} ({', '.join(imp['names']) or '*'})")
else:
print(f" - {imp}")
importers = g.get("imported_by", {}).get(path)
if importers:
print(f" 被这些文件 import: {', '.join(importers)}")
symbols = info.get("symbols") or []
if symbols:
print(f" 符号 ({len(symbols)}):")
for s in symbols:
print(f" L{s['line']:<5} {s['kind']:<14} {s['name']}" + (f" # {s['doc']}" if s.get("doc") else ""))
for m in s.get("methods", []):
print(f" L{m['line']:<5} {m['kind']:<14} {s['name']}.{m['name']}")
def cmd_symbol(g: dict, args: list[str]) -> None:
if not args:
print("用法: symbol <name>", file=sys.stderr)
return
name = args[0]
hits = g["symbol_index"].get(name)
if not hits:
cmd_search(g, args)
return
print(f"「{name}」定义于 {len(hits)} 处:")
for h in hits:
print(f" {h['file']}:{h['line']} [{h['kind']}]")
callers = sorted({rel for rel, info in g["files"].items()
for s in info.get("symbols", [])
for c in (s.get("calls") or []) if c == name}
| {rel for rel, info in g["files"].items()
for s in info.get("symbols", [])
for m in s.get("methods", [])
for c in (m.get("calls") or []) if c == name})
if callers:
print(f" 被调用于(文件级,粒度较粗): {', '.join(callers)}")
def cmd_search(g: dict, args: list[str]) -> None:
if not args:
print("用法: search <keyword>", file=sys.stderr)
return
kw = args[0].lower()
names = sorted(n for n in g["symbol_index"] if kw in n.lower())
if not names:
print(f"没有符号名包含「{args[0]}」")
return
print(f"匹配的符号({len(names)}):")
for n in names[:60]:
hits = g["symbol_index"][n]
loc = hits[0]
extra = f" 等{len(hits)}处" if len(hits) > 1 else ""
print(f" {n:<30} {loc['file']}:{loc['line']}{extra}")
def cmd_callers(g: dict, args: list[str]) -> None:
if not args:
print("用法: callers <name>(只覆盖 Python,基于 ast.Call 的粗粒度识别)", file=sys.stderr)
return
name = args[0]
hits = []
for rel, info in g["files"].items():
for s in info.get("symbols", []):
if name in (s.get("calls") or []):
hits.append((rel, s["name"], s["line"]))
for m in s.get("methods", []):
if name in (m.get("calls") or []):
hits.append((rel, f"{s['name']}.{m['name']}", m["line"]))
if not hits:
print(f"没有找到调用「{name}」的函数(可能是间接调用/属性调用未被识别,或跨语言调用)")
return
print(f"调用「{name}」的函数({len(hits)}):")
for rel, fn, line in hits:
print(f" {fn:<30} {rel}:{line}")
def cmd_importers(g: dict, args: list[str]) -> None:
if not args:
print("用法: importers <path>(仅 TS/TSX,用 @/ 别名或相对路径识别)", file=sys.stderr)
return
path = args[0].replace("\\", "/")
hits = g.get("imported_by", {}).get(path)
if not hits:
print(f"没有记录到谁 import 了 {path}(也可能是路径没对上,试试 file 命令确认真实路径)")
return
print(f"import 了 {path} 的文件({len(hits)}):")
for h in hits:
print(f" {h}")
COMMANDS = {
"stats": cmd_stats, "file": cmd_file, "symbol": cmd_symbol,
"search": cmd_search, "callers": cmd_callers, "importers": cmd_importers,
}
def main() -> None:
if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS:
print(__doc__)
sys.exit(0 if len(sys.argv) < 2 else 1)
g = load()
COMMANDS[sys.argv[1]](g, sys.argv[2:])
if __name__ == "__main__":
main()