codefactory-cli 0.20.1__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.
- codefactory/__init__.py +3 -0
- codefactory/__main__.py +5 -0
- codefactory/accept.py +68 -0
- codefactory/analyzers/__init__.py +55 -0
- codefactory/analyzers/generic.py +392 -0
- codefactory/analyzers/parallel.py +113 -0
- codefactory/analyzers/python.py +279 -0
- codefactory/analyzers/python_parse.py +402 -0
- codefactory/analyzers/treewalk.py +299 -0
- codefactory/analyzers/ts_helper.js +483 -0
- codefactory/analyzers/typescript.py +118 -0
- codefactory/apple.py +80 -0
- codefactory/audit.py +227 -0
- codefactory/baseline.py +58 -0
- codefactory/brief.py +330 -0
- codefactory/cache.py +93 -0
- codefactory/checks.py +608 -0
- codefactory/cli.py +782 -0
- codefactory/config.py +157 -0
- codefactory/coverage.py +104 -0
- codefactory/deps.py +182 -0
- codefactory/diff.py +197 -0
- codefactory/efficiency.py +250 -0
- codefactory/flags.py +263 -0
- codefactory/graph.py +95 -0
- codefactory/hotspots.py +344 -0
- codefactory/infra.py +242 -0
- codefactory/intent.py +106 -0
- codefactory/layers.py +143 -0
- codefactory/org.py +131 -0
- codefactory/owners.py +72 -0
- codefactory/patch.py +81 -0
- codefactory/paths.py +93 -0
- codefactory/plan.py +476 -0
- codefactory/privacy.py +221 -0
- codefactory/profile.py +667 -0
- codefactory/rerank.py +161 -0
- codefactory/review.py +1504 -0
- codefactory/rules.py +50 -0
- codefactory/sarif.py +661 -0
- codefactory/sbom.py +78 -0
- codefactory/security.py +537 -0
- codefactory/similar.py +199 -0
- codefactory/skill.py +144 -0
- codefactory/skill_template/SKILL.md +68 -0
- codefactory/skill_template/__init__.py +0 -0
- codefactory/sqlgraph.py +109 -0
- codefactory/suppress.py +92 -0
- codefactory/taint.py +439 -0
- codefactory/trace.py +72 -0
- codefactory/viewer/__init__.py +19 -0
- codefactory/viewer/dashboard.html +43 -0
- codefactory/viewer/factory.css +61 -0
- codefactory/viewer/factory.js +665 -0
- codefactory/viewer/template.html +47 -0
- codefactory_cli-0.20.1.dist-info/METADATA +250 -0
- codefactory_cli-0.20.1.dist-info/RECORD +61 -0
- codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
- codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
- codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
- codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/brief.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Text views of the graph for AI coding agents (Claude Code) and terminals: a whole-repo brief, and the context of one
|
|
2
|
+
file or function before changing it. Markdown, with `file:line` references, kept short enough to read in one go."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from collections import Counter, defaultdict, deque
|
|
8
|
+
|
|
9
|
+
from .paths import is_test
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class View:
|
|
13
|
+
"""Indexes over a graph dict (from build(...).to_dict() or a saved .json)."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, g: dict):
|
|
16
|
+
self.g = g
|
|
17
|
+
self.fn = {f["id"]: f for f in g["functions"]}
|
|
18
|
+
self.file = {f["id"]: f for f in g["files"]}
|
|
19
|
+
self.callers = defaultdict(list)
|
|
20
|
+
self.callees = defaultdict(list)
|
|
21
|
+
self.refs_in = defaultdict(list)
|
|
22
|
+
self.importers = defaultdict(set)
|
|
23
|
+
self.imports = defaultdict(set)
|
|
24
|
+
for e in g["edges"]:
|
|
25
|
+
if e["kind"] == "call":
|
|
26
|
+
self.callers[e["dst"]].append(e)
|
|
27
|
+
self.callees[e["src"]].append(e)
|
|
28
|
+
elif e["kind"] == "ref":
|
|
29
|
+
self.refs_in[e["dst"]].append(e)
|
|
30
|
+
else:
|
|
31
|
+
self.importers[e["dst"]].add(e["src"])
|
|
32
|
+
self.imports[e["src"]].add(e["dst"])
|
|
33
|
+
self.flags_on = defaultdict(list)
|
|
34
|
+
for fl in g["flags"]:
|
|
35
|
+
self.flags_on[fl["target"]].append(fl)
|
|
36
|
+
self.fns_in = defaultdict(list)
|
|
37
|
+
for f in g["functions"]:
|
|
38
|
+
if f["kind"] != "module":
|
|
39
|
+
self.fns_in[f["file"]].append(f)
|
|
40
|
+
|
|
41
|
+
def where(self, fid: str) -> str:
|
|
42
|
+
f = self.fn.get(fid)
|
|
43
|
+
return f"{f['file']}:{f['line']}" if f else fid
|
|
44
|
+
|
|
45
|
+
def dependents(self, start: list[str]) -> set[str]:
|
|
46
|
+
"""Everything that calls these, directly or through others (who could break if they change)."""
|
|
47
|
+
seen, q = set(start), deque(start)
|
|
48
|
+
while q:
|
|
49
|
+
cur = q.popleft()
|
|
50
|
+
for e in self.callers[cur] + self.refs_in[cur]:
|
|
51
|
+
if e["src"] not in seen:
|
|
52
|
+
seen.add(e["src"])
|
|
53
|
+
q.append(e["src"])
|
|
54
|
+
return seen - set(start)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
ADVICE = re.compile(r"^(.*?(?:loop \(line[^)]*\)(?:, and that reaches [^:]+\(\))?|loop \(line \d+\)))[:.].*$", re.S)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _flag_line(v: View, fl: dict) -> str:
|
|
61
|
+
"""One issue on one line. For loop checks the advice is said once in the section's note, not on every line."""
|
|
62
|
+
target = fl["target"]
|
|
63
|
+
if target in v.fn:
|
|
64
|
+
f = v.fn[target]
|
|
65
|
+
loc = f"{f['file']}:{fl.get('line') or f['line']}"
|
|
66
|
+
else:
|
|
67
|
+
loc = target
|
|
68
|
+
msg = fl["message"]
|
|
69
|
+
if fl["kind"] in ("io_in_loop", "quadratic_scan", "sequential_await"):
|
|
70
|
+
m = ADVICE.match(msg)
|
|
71
|
+
msg = m.group(1) if m else msg
|
|
72
|
+
return f"- `{loc}` {msg}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def brief_markdown(g: dict, limit: int = 12) -> str:
|
|
76
|
+
v = View(g)
|
|
77
|
+
name = g["root"].replace("\\", "/").rstrip("/").split("/")[-1]
|
|
78
|
+
code_files = [f for f in g["files"] if not is_test(f["id"])]
|
|
79
|
+
fns = [f for f in g["functions"] if f["kind"] != "module"]
|
|
80
|
+
lines = [
|
|
81
|
+
f"# Code map: {name}",
|
|
82
|
+
f"{g['language']} · {len(g['files'])} files ({len(g['files']) - len(code_files)} tests) · {len(fns)} functions · "
|
|
83
|
+
f"{sum(f['loc'] for f in g['files']):,} lines. Generated by codefactory (static analysis: calls through "
|
|
84
|
+
"dynamic dispatch may be missing). `file:line` points at code.",
|
|
85
|
+
"",
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
# layers and how they depend on each other
|
|
89
|
+
layer_of = {f["id"]: f["layer"] for f in g["files"]}
|
|
90
|
+
fn_file = {f["id"]: f["file"] for f in g["functions"]}
|
|
91
|
+
deps: dict[str, Counter] = defaultdict(Counter)
|
|
92
|
+
for e in g["edges"]:
|
|
93
|
+
if e["kind"] == "call":
|
|
94
|
+
a, b = layer_of.get(fn_file.get(e["src"])), layer_of.get(fn_file.get(e["dst"]))
|
|
95
|
+
if a and b and a != b:
|
|
96
|
+
deps[a][b] += e["count"]
|
|
97
|
+
sev_by_layer: dict[str, Counter] = defaultdict(Counter)
|
|
98
|
+
for fl in g["flags"]:
|
|
99
|
+
file = fn_file.get(fl["target"], fl["target"])
|
|
100
|
+
sev_by_layer[layer_of.get(file, "?")][fl["severity"]] += 1
|
|
101
|
+
lines += [
|
|
102
|
+
"## Layers (left to right: uses others → used by others)",
|
|
103
|
+
"",
|
|
104
|
+
"| Layer | Files | Lines | Calls into | Issues (high/warn/info) |",
|
|
105
|
+
"|---|---|---|---|---|",
|
|
106
|
+
]
|
|
107
|
+
for layer in g["layers"]:
|
|
108
|
+
members = [f for f in g["files"] if f["layer"] == layer]
|
|
109
|
+
into = ", ".join(f"{k} ({n})" for k, n in deps[layer].most_common(4)) or "-"
|
|
110
|
+
s = sev_by_layer[layer]
|
|
111
|
+
lines.append(
|
|
112
|
+
f"| {layer} | {len(members)} | {sum(f['loc'] for f in members):,} | {into} | {s['high']}/{s['warn']}/{s['info']} |"
|
|
113
|
+
)
|
|
114
|
+
if g.get("rules"):
|
|
115
|
+
lines += ["", "Forbidden layer imports (factory.toml): " + ", ".join(g["rules"])]
|
|
116
|
+
|
|
117
|
+
# most-used code
|
|
118
|
+
caller_files = {fid: {fn_file.get(e["src"]) for e in v.callers[fid]} - {f["file"]} for fid, f in v.fn.items()}
|
|
119
|
+
top = sorted((f for f in fns if not is_test(f["file"])), key=lambda f: -len(caller_files[f["id"]]))[:8]
|
|
120
|
+
lines += ["", "## Most-used code (a change here ripples; check callers first)", ""]
|
|
121
|
+
lines += [
|
|
122
|
+
f"- `{f['file']}:{f['line']}` {f['qualname']}: called from {len(caller_files[f['id']])} files"
|
|
123
|
+
for f in top
|
|
124
|
+
if caller_files[f["id"]]
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
# issues, grouped by what to do about them
|
|
128
|
+
by_kind: dict[str, list] = defaultdict(list)
|
|
129
|
+
for fl in g["flags"]:
|
|
130
|
+
by_kind[fl["kind"]].append(fl)
|
|
131
|
+
|
|
132
|
+
def section(title: str, kinds: list[str], note: str = "") -> None:
|
|
133
|
+
items = [fl for k in kinds for fl in by_kind.get(k, [])]
|
|
134
|
+
items = [fl for fl in items if not is_test(fn_file.get(fl["target"], fl["target"]))] or items
|
|
135
|
+
if not items:
|
|
136
|
+
return
|
|
137
|
+
items.sort(key=lambda fl: ({"high": 0, "warn": 1, "info": 2}[fl["severity"]], fl["target"]))
|
|
138
|
+
lines.extend(["", f"## {title} ({len(items)})"] + ([note] if note else []) + [""])
|
|
139
|
+
lines.extend(_flag_line(v, fl) for fl in items[:limit])
|
|
140
|
+
if len(items) > limit:
|
|
141
|
+
lines.append(f"- … {len(items) - limit} more: `codefactory flags --json` lists all")
|
|
142
|
+
|
|
143
|
+
section("Import loops and layer violations", ["cycle", "layer_violation"])
|
|
144
|
+
section(
|
|
145
|
+
"Database, file or network calls inside loops",
|
|
146
|
+
["io_in_loop"],
|
|
147
|
+
"Reads and network calls first (the N+1 pattern: replace with one batched query, WHERE id IN (…) or a JOIN, "
|
|
148
|
+
"or one request); then writes and files (usually fine inside one transaction; batch them if there are many).",
|
|
149
|
+
)
|
|
150
|
+
# duplicates as clusters, with what merging would save
|
|
151
|
+
clusters = []
|
|
152
|
+
seen = set()
|
|
153
|
+
for fl in by_kind.get("duplicate", []) + by_kind.get("similar", []):
|
|
154
|
+
group = frozenset([fl["target"], *fl.get("related", [])])
|
|
155
|
+
if group in seen:
|
|
156
|
+
continue
|
|
157
|
+
seen.add(group)
|
|
158
|
+
members = [v.fn[i] for i in group if i in v.fn]
|
|
159
|
+
if len(members) < 2:
|
|
160
|
+
continue
|
|
161
|
+
saved = sum(m["loc"] for m in members) - max(m["loc"] for m in members)
|
|
162
|
+
pct = "same" if fl["kind"] == "duplicate" else f"{round(fl.get('score', 0.8) * 100)}% similar"
|
|
163
|
+
clusters.append((saved, pct, members))
|
|
164
|
+
if clusters:
|
|
165
|
+
clusters.sort(key=lambda c: -c[0])
|
|
166
|
+
lines += ["", f"## Copied code ({len(clusters)} groups; merging each into one function saves the lines shown)", ""]
|
|
167
|
+
for saved, pct, members in clusters[:limit]:
|
|
168
|
+
lines.append(f"- {pct}, ~{saved} lines: " + " · ".join(f"`{m['file']}:{m['line']}` {m['qualname']}" for m in members))
|
|
169
|
+
section(
|
|
170
|
+
"Searches inside loops",
|
|
171
|
+
["quadratic_scan"],
|
|
172
|
+
"Fine for short lists; for long ones build a Map or Set once before the loop.",
|
|
173
|
+
)
|
|
174
|
+
section(
|
|
175
|
+
"Awaits inside loops",
|
|
176
|
+
["sequential_await"],
|
|
177
|
+
"Each round waits for the last; if they're independent, run "
|
|
178
|
+
"them together (Promise.all / asyncio.gather). Not for writes that must stay in order.",
|
|
179
|
+
)
|
|
180
|
+
section("Unused code (verify before deleting: frameworks may call it by name)", ["unused"])
|
|
181
|
+
section("Only called from tests", ["test_only"])
|
|
182
|
+
longest = sorted((f for f in fns if not is_test(f["file"])), key=lambda f: -f["loc"])[:limit]
|
|
183
|
+
if longest:
|
|
184
|
+
lines += ["", "## Longest functions", ""]
|
|
185
|
+
lines += [f"- `{f['file']}:{f['line']}` {f['qualname']}: {f['loc']} lines" for f in longest]
|
|
186
|
+
lines += [
|
|
187
|
+
"",
|
|
188
|
+
"## Next",
|
|
189
|
+
"",
|
|
190
|
+
"- Before changing a function or file: `codefactory context <name|file>` (callers, impact, tests to run).",
|
|
191
|
+
"- What it eventually calls: `codefactory trace <function>`; how A reaches B: `codefactory path A B`.",
|
|
192
|
+
'- Anything else: `codefactory query "SELECT …"` '
|
|
193
|
+
"(tables files, functions, edges, flags; views function_stats, file_deps).",
|
|
194
|
+
]
|
|
195
|
+
return "\n".join(lines) + "\n"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def resolve_target(g: dict, query: str) -> tuple[str, list[dict]]:
|
|
199
|
+
"""("file", [file]) or ("function", [fn]) for a path or a name; several matches -> all of them."""
|
|
200
|
+
q = query.replace("\\", "/").lstrip("./")
|
|
201
|
+
files = [f for f in g["files"] if f["id"] == q] or [f for f in g["files"] if f["id"].endswith("/" + q) or f["id"].endswith(q)]
|
|
202
|
+
if files and ("/" in q or "." in q.split("/")[-1]):
|
|
203
|
+
return "file", files
|
|
204
|
+
fns = [f for f in g["functions"] if f["kind"] != "module"]
|
|
205
|
+
for key in ("id", "qualname", "name"):
|
|
206
|
+
hits = [f for f in fns if f[key] == query]
|
|
207
|
+
if hits:
|
|
208
|
+
return "function", hits
|
|
209
|
+
hits = [f for f in fns if f["id"].endswith(query)]
|
|
210
|
+
if hits:
|
|
211
|
+
return "function", hits
|
|
212
|
+
return ("file", files) if files else ("none", [])
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def context_data(g: dict, query: str, limit: int = 20) -> dict:
|
|
216
|
+
v = View(g)
|
|
217
|
+
kind, hits = resolve_target(g, query)
|
|
218
|
+
if kind == "none":
|
|
219
|
+
return {"error": f"no file or function matches {query!r}"}
|
|
220
|
+
if len(hits) > 1:
|
|
221
|
+
return {"error": f"{query!r} matches {len(hits)} {kind}s; use one of these", "matches": [h["id"] for h in hits[:30]]}
|
|
222
|
+
t = hits[0]
|
|
223
|
+
if kind == "function":
|
|
224
|
+
ids = [t["id"]]
|
|
225
|
+
callers = sorted({e["src"] for e in v.callers[t["id"]]})
|
|
226
|
+
callees = sorted({e["dst"] for e in v.callees[t["id"]]})
|
|
227
|
+
refs = sorted({e["src"] for e in v.refs_in[t["id"]]} - set(callers))
|
|
228
|
+
base = {
|
|
229
|
+
"kind": "function",
|
|
230
|
+
"id": t["id"],
|
|
231
|
+
"file": t["file"],
|
|
232
|
+
"line": t["line"],
|
|
233
|
+
"end": t["end"],
|
|
234
|
+
"loc": t["loc"],
|
|
235
|
+
"layer": v.file.get(t["file"], {}).get("layer"),
|
|
236
|
+
"io": t.get("io", []),
|
|
237
|
+
"callers": [{"id": c, "at": v.where(c)} for c in callers[:limit]],
|
|
238
|
+
"callers_total": len(callers),
|
|
239
|
+
"referenced_by": [{"id": c, "at": v.where(c)} for c in refs[:limit]],
|
|
240
|
+
"calls": [{"id": c, "at": v.where(c)} for c in callees[:limit]],
|
|
241
|
+
"calls_total": len(callees),
|
|
242
|
+
}
|
|
243
|
+
else:
|
|
244
|
+
ids = [f["id"] for f in v.fns_in[t["id"]]] + [f"{t['id']}::<module>"]
|
|
245
|
+
base = {
|
|
246
|
+
"kind": "file",
|
|
247
|
+
"id": t["id"],
|
|
248
|
+
"loc": t["loc"],
|
|
249
|
+
"layer": t["layer"],
|
|
250
|
+
"functions": [
|
|
251
|
+
{
|
|
252
|
+
"name": f["qualname"],
|
|
253
|
+
"line": f["line"],
|
|
254
|
+
"loc": f["loc"],
|
|
255
|
+
"callers": len(v.callers[f["id"]]),
|
|
256
|
+
"calls": len(v.callees[f["id"]]),
|
|
257
|
+
"issues": [fl["kind"] for fl in v.flags_on[f["id"]]],
|
|
258
|
+
}
|
|
259
|
+
for f in sorted(v.fns_in[t["id"]], key=lambda f: f["line"])
|
|
260
|
+
],
|
|
261
|
+
"imported_by": sorted(v.importers[t["id"]])[:limit],
|
|
262
|
+
"imported_by_total": len(v.importers[t["id"]]),
|
|
263
|
+
"imports": sorted(v.imports[t["id"]])[:limit],
|
|
264
|
+
}
|
|
265
|
+
dependents = v.dependents(ids)
|
|
266
|
+
dep_files = {v.fn[d]["file"] for d in dependents if d in v.fn}
|
|
267
|
+
base["impact"] = {
|
|
268
|
+
"functions": len(dependents),
|
|
269
|
+
"files": len(dep_files),
|
|
270
|
+
"layers": sorted({v.file[f]["layer"] for f in dep_files if f in v.file}),
|
|
271
|
+
}
|
|
272
|
+
base["tests"] = sorted(f for f in dep_files | set(v.importers.get(t.get("file", t["id"]), set())) if is_test(f))[:limit]
|
|
273
|
+
issues = [fl for i in dict.fromkeys(ids + [t["id"]]) for fl in v.flags_on.get(i, [])]
|
|
274
|
+
base["issues"] = [
|
|
275
|
+
{
|
|
276
|
+
"kind": fl["kind"],
|
|
277
|
+
"severity": fl["severity"],
|
|
278
|
+
"at": f"{v.fn[fl['target']]['file']}:{fl.get('line') or v.fn[fl['target']]['line']}"
|
|
279
|
+
if fl["target"] in v.fn
|
|
280
|
+
else fl["target"],
|
|
281
|
+
"message": fl["message"],
|
|
282
|
+
"related": [v.where(r) for r in fl.get("related", [])],
|
|
283
|
+
}
|
|
284
|
+
for fl in issues
|
|
285
|
+
]
|
|
286
|
+
return base
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def context_markdown(g: dict, query: str, limit: int = 20) -> str:
|
|
290
|
+
c = context_data(g, query, limit)
|
|
291
|
+
if "error" in c:
|
|
292
|
+
return c["error"] + ("\n" + "\n".join(f"- {m}" for m in c.get("matches", [])) if c.get("matches") else "") + "\n"
|
|
293
|
+
out = []
|
|
294
|
+
if c["kind"] == "function":
|
|
295
|
+
out += [f"# {c['id'].split('::')[1]} (`{c['file']}:{c['line']}`–{c['end']}, {c['loc']} lines, layer {c['layer']})", ""]
|
|
296
|
+
if c["io"]:
|
|
297
|
+
out.append(f"Does I/O itself: {', '.join(c['io'])}")
|
|
298
|
+
out += ["", f"## Called by ({c['callers_total']})"] + [f"- `{x['at']}` {x['id'].split('::')[1]}" for x in c["callers"]]
|
|
299
|
+
if c["referenced_by"]:
|
|
300
|
+
out += ["", "## Passed around by (callbacks, returned from hooks)"] + [
|
|
301
|
+
f"- `{x['at']}` {x['id'].split('::')[1]}" for x in c["referenced_by"]
|
|
302
|
+
]
|
|
303
|
+
out += ["", f"## Calls ({c['calls_total']})"] + [f"- `{x['at']}` {x['id'].split('::')[1]}" for x in c["calls"]]
|
|
304
|
+
else:
|
|
305
|
+
out += [
|
|
306
|
+
f"# {c['id']} ({c['loc']} lines, layer {c['layer']})",
|
|
307
|
+
"",
|
|
308
|
+
"## Functions",
|
|
309
|
+
"",
|
|
310
|
+
"| Function | Line | Lines | Callers | Calls | Issues |",
|
|
311
|
+
"|---|---|---|---|---|---|",
|
|
312
|
+
]
|
|
313
|
+
out += [
|
|
314
|
+
f"| {f['name']} | {f['line']} | {f['loc']} | {f['callers']} | {f['calls']} | {', '.join(f['issues']) or '-'} |"
|
|
315
|
+
for f in c["functions"]
|
|
316
|
+
]
|
|
317
|
+
out += ["", f"## Imported by ({c['imported_by_total']})"] + [f"- {x}" for x in c["imported_by"]]
|
|
318
|
+
out += ["", "## Imports"] + [f"- {x}" for x in c["imports"]]
|
|
319
|
+
imp = c["impact"]
|
|
320
|
+
out += [
|
|
321
|
+
"",
|
|
322
|
+
"## Impact of changing it",
|
|
323
|
+
f"{imp['functions']} functions in {imp['files']} files depend on it, directly or not"
|
|
324
|
+
+ (f" (layers: {', '.join(imp['layers'])})." if imp["layers"] else "."),
|
|
325
|
+
]
|
|
326
|
+
if c["tests"]:
|
|
327
|
+
out += ["", "## Tests that exercise it (run these after a change)"] + [f"- {t}" for t in c["tests"]]
|
|
328
|
+
if c["issues"]:
|
|
329
|
+
out += ["", "## Issues"] + [f"- `{i['at']}` {i['kind']} ({i['severity']}): {i['message']}" for i in c["issues"]]
|
|
330
|
+
return "\n".join(out) + "\n"
|
codefactory/cache.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Reuse the last analysis while no source file changed: <repo>/.codefactory/graph.json, keyed by a fingerprint of
|
|
2
|
+
every analyzable file's path, size and modification time (every language an analyzer reads), the settings files,
|
|
3
|
+
codefactory's own code, and which parsers are installed (installing the language pack or TypeScript later must
|
|
4
|
+
re-analyze, or the languages they add would stay missing). An AI agent asking for context many times in a row then
|
|
5
|
+
waits once, not every time."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _source_ext() -> tuple[str, ...]:
|
|
18
|
+
"""Every extension an analyzer reads: Python, TypeScript/JavaScript, and each tree-sitter language."""
|
|
19
|
+
from .analyzers.generic import JS_LANGS, LANGS
|
|
20
|
+
|
|
21
|
+
return tuple(sorted({".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", *LANGS, *JS_LANGS}))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _parsers() -> str:
|
|
25
|
+
"""Which optional parsers this machine has: the language pack, Node.js, and a TypeScript package where codefactory
|
|
26
|
+
looks for one (cheap checks, no subprocess: this runs on every command)."""
|
|
27
|
+
import shutil
|
|
28
|
+
|
|
29
|
+
from .analyzers.generic import available
|
|
30
|
+
|
|
31
|
+
node = shutil.which("node") or ""
|
|
32
|
+
candidates = [os.environ.get("CODEFACTORY_TYPESCRIPT", "")]
|
|
33
|
+
if node:
|
|
34
|
+
bin_dir = Path(node).resolve().parent
|
|
35
|
+
candidates += [str(bin_dir.parent / "lib" / "node_modules" / "typescript"), str(bin_dir / "node_modules" / "typescript")]
|
|
36
|
+
ts = next((c for c in candidates if c and (Path(c) / "package.json").is_file()), "")
|
|
37
|
+
return f"pack={available()}|node={bool(node)}|ts={ts}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
SETTINGS = ("factory.toml", "tsconfig.json", "jsconfig.json", "pyproject.toml")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _tool_stamp() -> str:
|
|
44
|
+
"""codefactory's own files: a new analyzer or check (even between releases) means the old graph is stale."""
|
|
45
|
+
here = Path(__file__).parent
|
|
46
|
+
parts = [__version__]
|
|
47
|
+
for p in sorted(here.rglob("*")):
|
|
48
|
+
if p.suffix in (".py", ".js") and "__pycache__" not in p.parts:
|
|
49
|
+
st = p.stat()
|
|
50
|
+
parts.append(f"{p.relative_to(here)}|{st.st_size}|{st.st_mtime_ns}")
|
|
51
|
+
return "\n".join(parts)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def fingerprint(root: Path, ignore: list[str]) -> str:
|
|
55
|
+
skip = set(ignore)
|
|
56
|
+
h = hashlib.sha1((_tool_stamp() + "\n" + _parsers()).encode("utf-8", "surrogatepass"))
|
|
57
|
+
source = _source_ext()
|
|
58
|
+
local_ts = root / "node_modules" / "typescript" / "package.json" # a project-local compiler appearing counts too
|
|
59
|
+
h.update(f"local_ts={local_ts.is_file()}\n".encode())
|
|
60
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
61
|
+
dirnames[:] = sorted(d for d in dirnames if d not in skip and not d.endswith(".egg-info"))
|
|
62
|
+
for name in sorted(filenames):
|
|
63
|
+
if name.endswith(source) or name in SETTINGS:
|
|
64
|
+
p = os.path.join(dirpath, name)
|
|
65
|
+
try:
|
|
66
|
+
st = os.stat(p)
|
|
67
|
+
except OSError:
|
|
68
|
+
continue
|
|
69
|
+
h.update(f"{os.path.relpath(p, root)}|{st.st_size}|{st.st_mtime_ns}\n".encode("utf-8", "surrogatepass"))
|
|
70
|
+
return h.hexdigest()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _dir(root: Path) -> Path:
|
|
74
|
+
return root / ".codefactory"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def load_cached(root: Path, ignore: list[str]) -> dict | None:
|
|
78
|
+
path = _dir(root) / "graph.json"
|
|
79
|
+
try:
|
|
80
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
81
|
+
except (OSError, ValueError):
|
|
82
|
+
return None
|
|
83
|
+
return data.get("graph") if data.get("fingerprint") == fingerprint(root, ignore) else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def save_cache(root: Path, ignore: list[str], graph: dict) -> None:
|
|
87
|
+
d = _dir(root)
|
|
88
|
+
try:
|
|
89
|
+
d.mkdir(exist_ok=True)
|
|
90
|
+
(d / ".gitignore").write_text("# codefactory's cache: never committed\n*\n", encoding="utf-8")
|
|
91
|
+
(d / "graph.json").write_text(json.dumps({"fingerprint": fingerprint(root, ignore), "graph": graph}), encoding="utf-8")
|
|
92
|
+
except OSError:
|
|
93
|
+
pass # read-only checkout: just analyze each time
|