codefactory-cli 0.20.3__py3-none-any.whl → 0.21.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 +1 -1
- codefactory/analyzers/generic.py +65 -18
- codefactory/analyzers/treewalk.py +20 -2
- codefactory/checks.py +65 -22
- codefactory/cli.py +96 -8
- codefactory/config.py +7 -0
- codefactory/deps.py +1 -1
- codefactory/efficiency.py +2 -1
- codefactory/export.py +254 -0
- codefactory/flags.py +6 -1
- codefactory/hotspots.py +5 -1
- codefactory/plan.py +5 -3
- codefactory/review.py +94 -48
- codefactory/scope.py +42 -0
- codefactory/similar.py +6 -2
- codefactory/skill.py +32 -1
- codefactory/skill_template/SKILL.md +4 -1
- codefactory/viewer/__init__.py +9 -2
- codefactory/viewer/factory.css +18 -2
- codefactory/viewer/factory.js +29 -10
- codefactory/viewer/template.html +7 -2
- {codefactory_cli-0.20.3.dist-info → codefactory_cli-0.21.1.dist-info}/METADATA +9 -5
- {codefactory_cli-0.20.3.dist-info → codefactory_cli-0.21.1.dist-info}/RECORD +27 -25
- {codefactory_cli-0.20.3.dist-info → codefactory_cli-0.21.1.dist-info}/WHEEL +0 -0
- {codefactory_cli-0.20.3.dist-info → codefactory_cli-0.21.1.dist-info}/entry_points.txt +0 -0
- {codefactory_cli-0.20.3.dist-info → codefactory_cli-0.21.1.dist-info}/licenses/LICENSE +0 -0
- {codefactory_cli-0.20.3.dist-info → codefactory_cli-0.21.1.dist-info}/top_level.txt +0 -0
codefactory/__init__.py
CHANGED
codefactory/analyzers/generic.py
CHANGED
|
@@ -82,11 +82,20 @@ JS_LANGS = {
|
|
|
82
82
|
# I/O by the receiver's or callee's name: a database, the network, files. Matched on calls nothing in the codebase
|
|
83
83
|
# defines, so the codebase's own functions are followed instead.
|
|
84
84
|
IO_RECEIVER = re.compile(
|
|
85
|
-
r"(?:^|[.:>])(?:db|database|conn|connection|cursor|session|repo|repository|dao|client|
|
|
85
|
+
r"(?:^|[.:>])(?:db|database|conn|connection|cursor|session|repo|repository|dao|client|httpClient|api|"
|
|
86
86
|
r"redis|em|entityManager|jdbc|mongo|stmt|statement|pool|tx|s3|bucket|requests|"
|
|
87
|
-
r"_db|_repo|_client|_http|\$db|\$pdo|pdo|DB|
|
|
87
|
+
r"_db|_repo|_client|_http|\$db|\$pdo|pdo|DB|HttpClient)\s*(?:\.|->|::)\s*\w+$",
|
|
88
88
|
re.I,
|
|
89
89
|
)
|
|
90
|
+
# `http.` / `https.` is a package or module: only its request functions talk to the network (Go's http.SetCookie,
|
|
91
|
+
# http.HandleFunc, http.Error and http.NewRequest don't)
|
|
92
|
+
HTTP_PACKAGE = re.compile(r"(?:^|[.:>])(?:http|https|Http)\s*(?:\.|->|::)\s*(?:get|post|put|patch|delete|head|"
|
|
93
|
+
r"request|do|send|fetch|postform|urlopen)\w*$", re.I) # fmt: skip
|
|
94
|
+
# migrations step through their changes one at a time on purpose (each its own statement, in order)
|
|
95
|
+
MIGRATION = re.compile(r"(?i)migrat|schema_?lock|upgrade_?schema")
|
|
96
|
+
# startup code runs once, over what's configured (a loop per server, per registry): not a loop over data
|
|
97
|
+
STARTUP = re.compile(r"(?:^|::|\.)(?:main|init|boot\w*|setup\w*|Setup\w*|New\w*|new_\w*|Register\w*|register\w*|"
|
|
98
|
+
r"Start\w*|start\w*|Init\w*|Configure\w*|configure\w*|Bootstrap\w*|Must\w*|Load\w*Config\w*)$") # fmt: skip
|
|
90
99
|
IO_NAME = re.compile(
|
|
91
100
|
r"(?:^|[.:>])(?:query|execute|executeQuery|executeUpdate|exec_query|rawQuery|QueryRow|QueryContext|ExecContext|"
|
|
92
101
|
r"Exec|urlopen|fetch|findById|findOne|findAll|find_by|"
|
|
@@ -192,10 +201,40 @@ def _import_index(rels: list[str]) -> dict[str, list[str]]:
|
|
|
192
201
|
return idx
|
|
193
202
|
|
|
194
203
|
|
|
195
|
-
def
|
|
204
|
+
def _go_modules(root: Path) -> list[tuple[str, str]]:
|
|
205
|
+
"""(module path, its folder) for each go.mod: a Go import is the repository's own only under one of them."""
|
|
206
|
+
from ..paths import walk
|
|
207
|
+
|
|
208
|
+
out = []
|
|
209
|
+
for rel in walk(root, names=("go.mod",)):
|
|
210
|
+
try:
|
|
211
|
+
m = re.search(r"^module\s+(\S+)", (root / rel).read_text(encoding="utf-8", errors="replace"), re.M)
|
|
212
|
+
except OSError:
|
|
213
|
+
continue
|
|
214
|
+
if m:
|
|
215
|
+
out.append((m.group(1).strip('"'), rel.rsplit("/", 1)[0] if "/" in rel else ""))
|
|
216
|
+
return sorted(out, key=lambda x: -len(x[0])) # the longest (most specific) module first
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _go_package(source: str, idx: dict[str, list[str]], mods: list[tuple[str, str]]) -> list[str]:
|
|
220
|
+
"""A Go import, by its full path: `example.com/app/internal/sync` is the folder internal/sync; `sync`, or anything
|
|
221
|
+
outside the module, is the standard library or a dependency, whatever folders the repository happens to have."""
|
|
222
|
+
source = source.strip().strip('"`')
|
|
223
|
+
for mod, folder in mods:
|
|
224
|
+
if source == mod or source.startswith(mod + "/"):
|
|
225
|
+
key = "/".join(p for p in (folder, source[len(mod) :].strip("/")) if p)
|
|
226
|
+
files = [f for f in idx.get(key + "/", []) if not _is_test(f) and f.rsplit("/", 1)[0] == key]
|
|
227
|
+
return sorted(files, key=lambda f: (Path(f).stem != key.rsplit("/", 1)[-1], f))[:1]
|
|
228
|
+
return []
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _resolve_import(source: str, idx: dict[str, list[str]], lang: str, go_mods: list | None = None) -> list[str]:
|
|
196
232
|
"""The file(s) an import names: the longest path suffix that is a file (C's "net/socket.h", Java's a.b.Orders),
|
|
197
|
-
else a package folder, linked through one file (its namesake if there is one). Go imports always name packages
|
|
198
|
-
Among several equal matches the shallowest folder wins; more than
|
|
233
|
+
else a package folder, linked through one file (its namesake if there is one). Go imports always name packages
|
|
234
|
+
(by their full path, when there's a go.mod). Among several equal matches the shallowest folder wins; more than
|
|
235
|
+
three equal files is too ambiguous to link."""
|
|
236
|
+
if lang == "go" and go_mods:
|
|
237
|
+
return _go_package(source, idx, go_mods)
|
|
199
238
|
s = re.sub(r"\.(?:h|hpp|hh|rb|php|lua|dart|go|rs|java|kt|swift|cs|ex|js|ts)$", "", source.strip())
|
|
200
239
|
parts = [p for p in re.split(r"[./\\:]+", s) if p and p not in ("crate", "self", "super", "~", "@", "..")]
|
|
201
240
|
# the path as written, then without its last part: `import a.b.fn` (Kotlin, Java static) names something inside a.b
|
|
@@ -234,7 +273,7 @@ def analyze_generic(root: Path, ignore: list[str], include_js: bool = False, cac
|
|
|
234
273
|
)
|
|
235
274
|
return g
|
|
236
275
|
items = [(rel, (str(root / rel), rel, lang)) for rel, lang in found]
|
|
237
|
-
parsed = parallel.run(root, "generic", items, parse_file, tool="treewalk-
|
|
276
|
+
parsed = parallel.run(root, "generic", items, parse_file, tool="treewalk-5", cache=cache)
|
|
238
277
|
return link(g, parsed, rails_associations(root, [rel for rel, _ in found if rel.endswith(".rb")]))
|
|
239
278
|
|
|
240
279
|
|
|
@@ -280,13 +319,14 @@ def link(g: Graph, parsed: dict[str, dict], associations: re.Pattern | None = No
|
|
|
280
319
|
langs = Counter(d["lang"] for d in parsed.values())
|
|
281
320
|
g.language = "+".join(sorted(langs))
|
|
282
321
|
idx = _import_index(list(parsed))
|
|
322
|
+
go_mods = _go_modules(Path(g.root)) if g.root and any(d["lang"] == "go" for d in parsed.values()) else []
|
|
283
323
|
defs: dict[str, list[str]] = defaultdict(list) # name -> function ids
|
|
284
324
|
file_of: dict[str, str] = {}
|
|
285
325
|
kind_of: dict[str, str] = {}
|
|
286
326
|
imported: dict[str, set[str]] = {}
|
|
287
327
|
for rel, d in sorted(parsed.items()):
|
|
288
328
|
g.files.append(File(id=rel, module=rel.rsplit(".", 1)[0].replace("/", "."), loc=d["loc"]))
|
|
289
|
-
imported[rel] = {dst for src in d["imports"] for dst in _resolve_import(src, idx, d["lang"]) if dst != rel}
|
|
329
|
+
imported[rel] = {dst for src in d["imports"] for dst in _resolve_import(src, idx, d["lang"], go_mods) if dst != rel}
|
|
290
330
|
g.edges += [Edge(rel, dst, "import") for dst in sorted(imported[rel])]
|
|
291
331
|
top = Function(id=f"{rel}::<module>", file=rel, name="<module>", qualname="<module>", line=1, end=1, loc=0, kind="module")
|
|
292
332
|
g.functions.append(top)
|
|
@@ -359,30 +399,37 @@ def link(g: Graph, parsed: dict[str, dict], associations: re.Pattern | None = No
|
|
|
359
399
|
target, cands = resolve(name, src)
|
|
360
400
|
for c in [target] if target else cands if len(cands) <= 3 else ():
|
|
361
401
|
refs[(src, c)] += 1
|
|
362
|
-
|
|
402
|
+
startup = bool(STARTUP.search(src) or MIGRATION.search(src))
|
|
403
|
+
for name, line, in_loop, callee, *rest in rec["calls"]:
|
|
404
|
+
route = bool(rest and rest[0])
|
|
363
405
|
target, cands = resolve(name, src, bare=not re.search(r"\.|->|::", callee), callee=callee)
|
|
364
406
|
if target:
|
|
365
407
|
calls[(src, target)] += 1
|
|
366
408
|
if in_loop:
|
|
367
|
-
g.sites.append(Site(src, "loop_call", line, target=target))
|
|
409
|
+
g.sites.append(Site(src, "loop_call", line, target=target, bounded=startup))
|
|
368
410
|
continue
|
|
369
411
|
if len(cands) <= 3:
|
|
370
412
|
for c in cands:
|
|
371
413
|
refs[(src, c)] += 1
|
|
372
414
|
else: # called by a name many things define (String, Error, Read): any of them may be what runs
|
|
373
415
|
ambiguous.add(name)
|
|
374
|
-
if
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
416
|
+
if (
|
|
417
|
+
not cands
|
|
418
|
+
and not route
|
|
419
|
+
and (
|
|
420
|
+
IO_RECEIVER.search(callee)
|
|
421
|
+
or HTTP_PACKAGE.search(callee)
|
|
422
|
+
or IO_NAME.search(callee)
|
|
423
|
+
or (src.split("::")[0].endswith(ORM_LANGS) and ORM_NAME.search(callee))
|
|
424
|
+
or (src.split("::")[0].endswith(".swift") and SWIFT_STORE.search(callee))
|
|
425
|
+
or (_typed_io(callee, types) and (ORM_NAME.search(callee) or IO_VERB.search(callee)))
|
|
426
|
+
or (src.split("::")[0].endswith(".rb") and AR.search(callee))
|
|
427
|
+
or (associations and src.split("::")[0].endswith(".rb") and associations.search(callee))
|
|
428
|
+
)
|
|
382
429
|
):
|
|
383
430
|
io.add(callee)
|
|
384
431
|
if in_loop:
|
|
385
|
-
g.sites.append(Site(src, "loop_io", line, detail=callee))
|
|
432
|
+
g.sites.append(Site(src, "loop_io", line, detail=callee, bounded=startup))
|
|
386
433
|
if src in by_id:
|
|
387
434
|
by_id[src].io = sorted(io)
|
|
388
435
|
framework = {f["id"] for d in parsed.values() for f in d["functions"] if f.get("framework")}
|
|
@@ -108,6 +108,24 @@ def _last_ident(node, depth: int = 0) -> str:
|
|
|
108
108
|
return ""
|
|
109
109
|
|
|
110
110
|
|
|
111
|
+
BATCHED = re.compile(r"(?i)\b(?:batch|chunk|page)\w*\b|\+=\s*(?:\w*(?:size|Size|limit|Limit|max|Max)\w*|\d{2,})")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _batched(loop) -> bool:
|
|
115
|
+
"""`for _, batch := range batches`, `for i := 0; i < n; i += 1000`: a loop over batches is the batching, one
|
|
116
|
+
call per batch is what the fix for one call per item looks like."""
|
|
117
|
+
head = loop.text.decode("utf-8", "replace").split("{", 1)[0].split("\n", 1)[0][:200]
|
|
118
|
+
return BATCHED.search(head) is not None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _route_call(node) -> bool:
|
|
122
|
+
"""`r.Get("/users", h)`, `r.Get("/api/"+p, h)`, `app.post('/x', …)`: registering a route (its first argument a
|
|
123
|
+
path), not making a request, though the method is named like one."""
|
|
124
|
+
args = node.child_by_field_name("arguments")
|
|
125
|
+
first = next(iter(args.named_children), None) if args is not None else None
|
|
126
|
+
return first is not None and re.match(r"""^[`"']/""", first.text.decode("utf-8", "replace")) is not None
|
|
127
|
+
|
|
128
|
+
|
|
111
129
|
def _callee_text(node) -> str:
|
|
112
130
|
"""`repo.find`: the callee as written. Java, Ruby and PHP keep the receiver and the method name in separate fields
|
|
113
131
|
(object/receiver + name/method); others have one function expression."""
|
|
@@ -250,14 +268,14 @@ def walk(source: bytes, parser, rel: str) -> dict:
|
|
|
250
268
|
if fn is not None and (BRANCH.search(t) or t in ("&&", "||", "and", "or", "??", "orelse", "andalso")):
|
|
251
269
|
fn["branches"] += 1
|
|
252
270
|
in_loop = loops
|
|
253
|
-
if LOOP.search(t) and not NOT_LOOP.search(t) and node.named_children:
|
|
271
|
+
if LOOP.search(t) and not NOT_LOOP.search(t) and node.named_children and not _batched(node):
|
|
254
272
|
in_loop = loops + 1
|
|
255
273
|
if CALL.match(t):
|
|
256
274
|
name = _name(node, call=True)
|
|
257
275
|
if name in REQUIRE and fn is None: # Ruby, Lua, PHP, Elixir: imports are calls
|
|
258
276
|
out["imports"] += [s for s in _import_sources(node)[:1] if s != name]
|
|
259
277
|
elif name:
|
|
260
|
-
owner["calls"].append([name, node.start_point[0] + 1, loops > 0, _callee_text(node)])
|
|
278
|
+
owner["calls"].append([name, node.start_point[0] + 1, loops > 0, _callee_text(node), _route_call(node)])
|
|
261
279
|
if name in ITER: # the closure it's given runs per item
|
|
262
280
|
for c in node.named_children:
|
|
263
281
|
if CLOSURE.search(c.type) or any(CLOSURE.search(g.type) for g in c.named_children):
|
codefactory/checks.py
CHANGED
|
@@ -10,6 +10,7 @@ from __future__ import annotations
|
|
|
10
10
|
import json
|
|
11
11
|
import os
|
|
12
12
|
import re
|
|
13
|
+
import subprocess
|
|
13
14
|
from collections import deque
|
|
14
15
|
from dataclasses import dataclass, field
|
|
15
16
|
from pathlib import Path
|
|
@@ -242,6 +243,13 @@ _NAMED_VALUE = re.compile(
|
|
|
242
243
|
_PEM_BODY = re.compile(r"(PRIVATE KEY-----(?:\\r)?(?:\\n)?)[A-Za-z0-9+/=]{8,}")
|
|
243
244
|
|
|
244
245
|
|
|
246
|
+
# raw HTML from a string literal with nothing put into it (no ${…}, no +): `el.innerHTML = '<b>Copied</b>'`,
|
|
247
|
+
# `__html: "<br>"`, also inside a page a Go or Python file holds as text
|
|
248
|
+
CONSTANT_HTML = re.compile(
|
|
249
|
+
r"""(?:\.innerHTML\s*=|__html\s*:|mark_safe\(|v-html\s*=\s*)\s*(["'`])(?:(?!\1)(?!\$\{)[^\\]|\\.)*\1\s*[;,)}]*\s*(?:/?>)?\s*$"""
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
|
|
245
253
|
def redact(text: str) -> str:
|
|
246
254
|
"""The text with secret values cut to their first 4 characters: `AKIA…`, `API_KEY = "sk_l…"`."""
|
|
247
255
|
text = _VENDOR_KEY.sub(lambda m: m.group(0)[:4] + "…", text)
|
|
@@ -359,6 +367,8 @@ def _scan(root: Path, files: list[str]) -> dict[str, Check]:
|
|
|
359
367
|
if key != "secret" and COMMENT_LINE.match(line):
|
|
360
368
|
continue # prose about a pattern ("mark_safe() it at the end") isn't the code; a key is leaked anywhere
|
|
361
369
|
if any(p.search(line) and (p not in ONLY_IN or fid.endswith(ONLY_IN[p])) for p in pats) and hit(key, i):
|
|
370
|
+
if key == "raw_html" and CONSTANT_HTML.search(line):
|
|
371
|
+
continue # a fixed string: no one's data can get into it
|
|
362
372
|
if key == "raw_html" and re.search(r"mark_safe\(.*\bsettings\.[A-Z_]+", line):
|
|
363
373
|
continue # the site's own configuration, not user data
|
|
364
374
|
if key == "plain_http" and re.match(r"\s*(?:\*|//|#|/\*)", line): # an example in a doc comment
|
|
@@ -452,15 +462,37 @@ def _scan(root: Path, files: list[str]) -> dict[str, Check]:
|
|
|
452
462
|
# ---- repository ----------------------------------------------------------------------------------------------------
|
|
453
463
|
|
|
454
464
|
CI_FILES = [
|
|
455
|
-
".github/workflows",
|
|
456
|
-
".
|
|
457
|
-
".
|
|
458
|
-
"
|
|
459
|
-
"
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
465
|
+
".github/workflows", ".gitlab-ci.yml", ".circleci", "azure-pipelines.yml", ".azure-pipelines", "Jenkinsfile",
|
|
466
|
+
".travis.yml", "bitbucket-pipelines.yml", ".buildkite", ".drone.yml", ".woodpecker.yml", ".woodpecker",
|
|
467
|
+
".cirrus.yml", ".semaphore", ".teamcity", "appveyor.yml", ".appveyor.yml", "buildspec.yml", "cloudbuild.yaml",
|
|
468
|
+
"cloudbuild.yml", "bamboo-specs", ".tekton", "rio.yml", ".rio.yml", "codefresh.yml", ".harness", "bitrise.yml",
|
|
469
|
+
"codemagic.yaml", ".gitea/workflows", ".forgejo/workflows", ".taskcluster.yml", "wercker.yml", ".concourse",
|
|
470
|
+
] # fmt: skip
|
|
471
|
+
CI_NAMES = "GitHub Actions, GitLab, CircleCI, Jenkins, Azure, Travis, Bitbucket, Buildkite, Drone, Cirrus, TeamCity, Rio, …"
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def repo_levels(root: Path) -> list[Path]:
|
|
475
|
+
"""The analyzed folder, then each folder above it up to the top of its git repository: CI, the README and the
|
|
476
|
+
license usually live at the top, so a review of a subfolder (`internal/`, one package of a monorepo) finds them."""
|
|
477
|
+
out = [root]
|
|
478
|
+
try:
|
|
479
|
+
top = subprocess.run(["git", "-C", str(root), "rev-parse", "--show-toplevel"], capture_output=True, text=True,
|
|
480
|
+
timeout=10).stdout.strip() # fmt: skip
|
|
481
|
+
except (OSError, subprocess.SubprocessError):
|
|
482
|
+
return out
|
|
483
|
+
if not top:
|
|
484
|
+
return out
|
|
485
|
+
top_p, here = Path(top).resolve(), root.resolve()
|
|
486
|
+
while here != top_p and top_p in here.parents:
|
|
487
|
+
here = here.parent
|
|
488
|
+
out.append(here)
|
|
489
|
+
return out
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _rel(root: Path, p: Path) -> str:
|
|
493
|
+
return os.path.relpath(p, root).replace("\\", "/")
|
|
494
|
+
|
|
495
|
+
|
|
464
496
|
LOCKS = [
|
|
465
497
|
"package-lock.json",
|
|
466
498
|
"yarn.lock",
|
|
@@ -525,15 +557,23 @@ def scan_repo(root: Path) -> dict:
|
|
|
525
557
|
"deps": {},
|
|
526
558
|
"deploy": [],
|
|
527
559
|
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
560
|
+
from .config import load_config
|
|
561
|
+
|
|
562
|
+
real = root.resolve() # (Windows: the same folder can be C:\\Users\\RUNNER~1\\… or C:/Users/runneradmin/…)
|
|
563
|
+
levels = repo_levels(real)
|
|
564
|
+
declared = list(load_config(root).ci) # factory.toml `ci = ["…"]`: a CI system this list doesn't know
|
|
565
|
+
for level in levels:
|
|
566
|
+
for c in [*CI_FILES, *declared]:
|
|
567
|
+
p = level / c
|
|
568
|
+
if p.is_dir():
|
|
569
|
+
info["ci"] += [_rel(real, f) for f in sorted(p.iterdir()) if f.is_file() and not f.name.startswith(".")]
|
|
570
|
+
elif p.is_file():
|
|
571
|
+
info["ci"].append(_rel(real, p))
|
|
572
|
+
if info["ci"]:
|
|
573
|
+
break # the nearest level with CI is this folder's
|
|
534
574
|
for f in info["ci"]:
|
|
535
575
|
try:
|
|
536
|
-
t = (
|
|
576
|
+
t = (real / f).read_text(encoding="utf-8", errors="replace").lower()
|
|
537
577
|
except OSError:
|
|
538
578
|
continue
|
|
539
579
|
for step, words in {
|
|
@@ -596,8 +636,10 @@ def scan_repo(root: Path) -> dict:
|
|
|
596
636
|
for f in (".nvmrc", ".node-version", ".python-version", ".tool-versions", "runtime.txt"):
|
|
597
637
|
if (root / f).exists():
|
|
598
638
|
info["runtime_pin"].append(f)
|
|
599
|
-
|
|
600
|
-
info["
|
|
639
|
+
names = ("README.md", "README.rst", "README.txt", "README", "readme.md")
|
|
640
|
+
info["readme"] = next((_rel(real, lv / f) for lv in levels for f in names if (lv / f).exists()), None)
|
|
641
|
+
licenses = ("LICENSE", "LICENSE.md", "LICENSE.txt", "COPYING")
|
|
642
|
+
info["license"] = next((_rel(real, lv / f) for lv in levels for f in licenses if (lv / f).exists()), None)
|
|
601
643
|
info["env_files"] = [
|
|
602
644
|
p.name
|
|
603
645
|
for p in root.glob(".env*")
|
|
@@ -607,7 +649,7 @@ def scan_repo(root: Path) -> dict:
|
|
|
607
649
|
and _holds_secret(p)
|
|
608
650
|
]
|
|
609
651
|
if info["readme"]:
|
|
610
|
-
t = (
|
|
652
|
+
t = (real / info["readme"]).read_text(encoding="utf-8", errors="replace").lower()
|
|
611
653
|
info["readme_run"] = bool(re.search(r"install|npm |pip |yarn |make |cargo |go run|docker", t))
|
|
612
654
|
return info
|
|
613
655
|
|
|
@@ -615,13 +657,14 @@ def scan_repo(root: Path) -> dict:
|
|
|
615
657
|
# ---- testing -------------------------------------------------------------------------------------------------------
|
|
616
658
|
|
|
617
659
|
|
|
618
|
-
def test_reach(v: View) -> set[str]:
|
|
619
|
-
"""Functions a test calls or hands on (a callback), directly or through others
|
|
660
|
+
def test_reach(v: View, also: set[str] | frozenset = frozenset()) -> set[str]:
|
|
661
|
+
"""Functions a test calls or hands on (a callback), directly or through others (`also`: ones tests reach in ways
|
|
662
|
+
the graph doesn't link, followed the same way)."""
|
|
620
663
|
out_edges: dict[str, list[str]] = {}
|
|
621
664
|
for e in v.g["edges"]:
|
|
622
665
|
if e["kind"] in ("call", "ref"):
|
|
623
666
|
out_edges.setdefault(e["src"], []).append(e["dst"])
|
|
624
|
-
start = [fid for fid, f in v.fn.items() if is_test(f["file"])]
|
|
667
|
+
start = [fid for fid, f in v.fn.items() if is_test(f["file"])] + [fid for fid in also if fid in v.fn]
|
|
625
668
|
seen, q = set(start), deque(start)
|
|
626
669
|
while q:
|
|
627
670
|
for nxt in out_edges.get(q.popleft(), []):
|
codefactory/cli.py
CHANGED
|
@@ -10,6 +10,7 @@ import json
|
|
|
10
10
|
import os
|
|
11
11
|
import sys
|
|
12
12
|
import webbrowser
|
|
13
|
+
from datetime import datetime
|
|
13
14
|
from pathlib import Path
|
|
14
15
|
|
|
15
16
|
from . import __version__
|
|
@@ -67,10 +68,23 @@ def load_graph(path: Path, languages: list[str] | None = None, cache: bool = Tru
|
|
|
67
68
|
stamp = fingerprint(root, ignore, recent) # before analysis: what's analyzed is at least this new
|
|
68
69
|
hit = load_cached(root, ignore, stamp)
|
|
69
70
|
if hit is not None:
|
|
70
|
-
return hit
|
|
71
|
+
return _scoped(hit, root)
|
|
71
72
|
graph = build(root, languages, cache).to_dict()
|
|
72
73
|
if cache and not languages:
|
|
73
74
|
save_cache(root, ignore, graph, stamp, bool(recent))
|
|
75
|
+
return _scoped(graph, root)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# --no-tests, for the command being run (load_graph has many callers; the option is the same for all of them)
|
|
79
|
+
OPTIONS = {"no_tests": False}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _scoped(graph: dict, root: Path) -> dict:
|
|
83
|
+
"""The graph as this run shows it: without test code when asked (--no-tests, or `tests = false`)."""
|
|
84
|
+
if OPTIONS["no_tests"] or not load_config(root).tests:
|
|
85
|
+
from .scope import without_tests
|
|
86
|
+
|
|
87
|
+
return without_tests(graph)
|
|
74
88
|
return graph
|
|
75
89
|
|
|
76
90
|
|
|
@@ -219,7 +233,12 @@ def cmd_view(a) -> int:
|
|
|
219
233
|
graph = load_graph(Path(a.path), a.lang, not a.no_cache)
|
|
220
234
|
graph = {**graph, "tasks": [{k: t[k] for k in ("id", "title", "prompt", "flags", "score")} for t in make_plan(graph)]}
|
|
221
235
|
out = Path(a.output or "factory.html")
|
|
222
|
-
|
|
236
|
+
audit = None
|
|
237
|
+
if Path(a.path).is_dir() and not a.no_audit: # the page's "Export audit" button: every finding, to triage
|
|
238
|
+
from .export import export
|
|
239
|
+
|
|
240
|
+
audit = export(graph, Path(a.path).resolve())
|
|
241
|
+
_write(out, render_html(graph, audit))
|
|
223
242
|
print(f"Wrote {out}: {len(graph['files'])} machines, {len(graph['flags'])} issues")
|
|
224
243
|
if not a.no_open:
|
|
225
244
|
webbrowser.open(out.resolve().as_uri())
|
|
@@ -519,16 +538,42 @@ def cmd_prompt(a) -> int:
|
|
|
519
538
|
return 0
|
|
520
539
|
|
|
521
540
|
|
|
541
|
+
def cmd_export(a) -> int:
|
|
542
|
+
from .export import export
|
|
543
|
+
|
|
544
|
+
path = Path(a.path)
|
|
545
|
+
if not path.is_dir():
|
|
546
|
+
raise SystemExit("codefactory: export needs the repository folder (it reads manifests, CI files and source text)")
|
|
547
|
+
text = export(load_graph(path, a.lang, not a.no_cache), path.resolve(), a.json, a.online)
|
|
548
|
+
out = a.output or stamped("audit", "json" if a.json else "md")
|
|
549
|
+
if out == "-":
|
|
550
|
+
print(text, end="")
|
|
551
|
+
return 0
|
|
552
|
+
_write(Path(out), text)
|
|
553
|
+
print(f"Wrote {out}: give it to Claude with \"analyze every finding in this audit and triage them into individual "
|
|
554
|
+
"fixes sorted by severity, then complexity\".") # fmt: skip
|
|
555
|
+
return 0
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def stamped(kind: str, ext: str = "md") -> str:
|
|
559
|
+
"""codefactory-review-2026-11-26-0915.md: says what it is and when, sorts by date, never overwrites the last one
|
|
560
|
+
(and has no colon, which Windows doesn't allow in a file name)."""
|
|
561
|
+
return f"codefactory-{kind}-{datetime.now():%Y-%m-%d-%H%M}.{ext}"
|
|
562
|
+
|
|
563
|
+
|
|
522
564
|
def cmd_review(a) -> int:
|
|
523
565
|
path = Path(a.path)
|
|
524
566
|
if not path.is_dir():
|
|
525
567
|
raise SystemExit("codefactory: review needs the repository folder (it reads manifests, CI files and source text)")
|
|
526
568
|
text = review_markdown(load_graph(path, a.lang, not a.no_cache), path.resolve(), a.for_ai, a.online)
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
569
|
+
# someone at a terminal gets a file (a whole report scrolling past is no use); a pipe, or a tool like Claude Code
|
|
570
|
+
# reading the output, still gets the text
|
|
571
|
+
out = a.output or (stamped("review") if sys.stdout.isatty() else "-")
|
|
572
|
+
if out == "-":
|
|
531
573
|
print(text, end="")
|
|
574
|
+
else:
|
|
575
|
+
_write(Path(out), text)
|
|
576
|
+
print(f"Wrote {out}")
|
|
532
577
|
return 0
|
|
533
578
|
|
|
534
579
|
|
|
@@ -631,6 +676,7 @@ COMMANDS = {
|
|
|
631
676
|
"path": (cmd_path, "the shortest call path between two functions: path [repo] from to"),
|
|
632
677
|
"brief": (cmd_brief, "a Markdown map of the repo for an AI agent: layers, hubs, issues by what to do"),
|
|
633
678
|
"context": (cmd_context, "before changing a file or function: callers, calls, impact, tests: context [repo] name"),
|
|
679
|
+
"export": (cmd_export, "every finding as one audit file (Markdown or --json) for an AI to triage into fixes"),
|
|
634
680
|
"review": (cmd_review, "a full technical review (summary, system map, findings by severity, gaps), no AI needed"),
|
|
635
681
|
"plan": (cmd_plan, "ranked tasks with steps, tests and a fix prompt each: the work list"),
|
|
636
682
|
"prompt": (cmd_prompt, "a ready-to-paste Claude Code prompt for one task: prompt [repo] <id or rank>"),
|
|
@@ -655,6 +701,19 @@ COMMANDS = {
|
|
|
655
701
|
}
|
|
656
702
|
|
|
657
703
|
|
|
704
|
+
START = """codefactory: map a codebase, find its problems, turn them into work. From your repository's folder:
|
|
705
|
+
|
|
706
|
+
codefactory review a technical review, saved as codefactory-review-<date>.md
|
|
707
|
+
codefactory view the interactive map, in your browser (with Export audit)
|
|
708
|
+
codefactory export every finding as one file: give it to Claude to triage into fixes
|
|
709
|
+
codefactory plan what to fix first; then `codefactory prompt 1` for a ready-to-paste brief
|
|
710
|
+
|
|
711
|
+
codefactory skill --hook teach Claude Code in this repository to use all of it
|
|
712
|
+
|
|
713
|
+
`codefactory --help` lists every command.
|
|
714
|
+
"""
|
|
715
|
+
|
|
716
|
+
|
|
658
717
|
def parser() -> argparse.ArgumentParser:
|
|
659
718
|
p = argparse.ArgumentParser(
|
|
660
719
|
prog="codefactory",
|
|
@@ -662,7 +721,8 @@ def parser() -> argparse.ArgumentParser:
|
|
|
662
721
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
663
722
|
epilog="""examples:
|
|
664
723
|
codefactory view open the factory view of this folder in your browser
|
|
665
|
-
codefactory review
|
|
724
|
+
codefactory review a technical review (codefactory-review-<date>.md)
|
|
725
|
+
codefactory export every finding as an audit to give Claude to triage
|
|
666
726
|
codefactory plan ranked tasks; then: codefactory prompt 1
|
|
667
727
|
codefactory context <name> before changing a function: callers, impact, tests
|
|
668
728
|
codefactory baseline && codefactory check fail CI only on new issues
|
|
@@ -706,12 +766,29 @@ Run `codefactory <command> --help` for a command's options.""",
|
|
|
706
766
|
help="only these analyzers (other = every language but Python and TypeScript)",
|
|
707
767
|
)
|
|
708
768
|
s.add_argument("--no-cache", action="store_true", help="analyze again even if nothing changed")
|
|
709
|
-
|
|
769
|
+
s.add_argument("--no-tests", action="store_true",
|
|
770
|
+
help="leave test code out of findings, the plan and the map (still counted for coverage)") # fmt: skip
|
|
771
|
+
if name in (
|
|
772
|
+
"flags",
|
|
773
|
+
"query",
|
|
774
|
+
"trace",
|
|
775
|
+
"path",
|
|
776
|
+
"context",
|
|
777
|
+
"plan",
|
|
778
|
+
"surface",
|
|
779
|
+
"diff",
|
|
780
|
+
"org",
|
|
781
|
+
"profile",
|
|
782
|
+
"hotspots",
|
|
783
|
+
"export",
|
|
784
|
+
):
|
|
710
785
|
s.add_argument("--json", action="store_true", help="machine-readable output")
|
|
711
786
|
if name in ("trace", "path"):
|
|
712
787
|
s.add_argument("--refs", action="store_true", help="also follow functions passed by name (callbacks)")
|
|
713
788
|
if name in ("analyze", "view", "brief", "baseline", "review", "sarif"):
|
|
714
789
|
s.add_argument("-o", "--output", help="output file")
|
|
790
|
+
if name == "export":
|
|
791
|
+
s.add_argument("-o", "--output", help="output file (default codefactory-audit-<date>.md, or .json; - prints it)")
|
|
715
792
|
if name in ("brief", "context"):
|
|
716
793
|
s.add_argument("--limit", type=int, default=12 if name == "brief" else 20, help="items per list")
|
|
717
794
|
if name == "flags":
|
|
@@ -732,6 +809,12 @@ Run `codefactory <command> --help` for a command's options.""",
|
|
|
732
809
|
s.add_argument(
|
|
733
810
|
"--fail-on", choices=list(SEVERITY_ORDER), default="warn", help="lowest new severity that fails (default warn)"
|
|
734
811
|
)
|
|
812
|
+
if name == "export":
|
|
813
|
+
s.add_argument(
|
|
814
|
+
"--online",
|
|
815
|
+
action="store_true",
|
|
816
|
+
help="also check dependencies for known vulnerabilities at OSV.dev (sends package names and versions only)",
|
|
817
|
+
)
|
|
735
818
|
if name == "review":
|
|
736
819
|
s.add_argument("--for-ai", action="store_true", help="append an evidence pack for an AI to finish the review")
|
|
737
820
|
s.add_argument(
|
|
@@ -743,6 +826,7 @@ Run `codefactory <command> --help` for a command's options.""",
|
|
|
743
826
|
s.add_argument("--top", type=int, default=10, help="how many tasks (default 10)")
|
|
744
827
|
if name == "view":
|
|
745
828
|
s.add_argument("--no-open", action="store_true", help="don't open the browser")
|
|
829
|
+
s.add_argument("--no-audit", action="store_true", help="no Export audit button (it runs the review)")
|
|
746
830
|
if name == "sql":
|
|
747
831
|
s.add_argument("-o", "--output", default="codefactory.db", help="database file (default: codefactory.db)")
|
|
748
832
|
return p
|
|
@@ -752,7 +836,11 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
752
836
|
"""Runs a command. Problems a user can fix (a bad factory.toml, a missing folder, TypeScript not installed) end
|
|
753
837
|
with a one-line message; anything unexpected says how to get the full traceback (--debug) to report it."""
|
|
754
838
|
_safe_stdout()
|
|
839
|
+
if not (sys.argv[1:] if argv is None else argv): # just `codefactory`: where to start, not a usage error
|
|
840
|
+
print(START, end="")
|
|
841
|
+
return 0
|
|
755
842
|
a = parser().parse_args(argv)
|
|
843
|
+
OPTIONS["no_tests"] = bool(getattr(a, "no_tests", False))
|
|
756
844
|
debug = a.debug or bool(os.environ.get("CODEFACTORY_DEBUG"))
|
|
757
845
|
repo = Path(getattr(a, "path", None) or ".")
|
|
758
846
|
if a.cmd not in ("skill", "update") and skill_outdated(repo if repo.is_dir() else repo.parent):
|
codefactory/config.py
CHANGED
|
@@ -39,6 +39,8 @@ class Config:
|
|
|
39
39
|
duplicate_min_lines: int = 6
|
|
40
40
|
similar_threshold: float = 0.75 # near-duplicates: share of structure in common (0-1)
|
|
41
41
|
hub_callers: int = 12
|
|
42
|
+
ci: list[str] = field(default_factory=list) # CI configuration files a system codefactory doesn't know uses
|
|
43
|
+
tests: bool = True # false: test code is left out of findings, the plan and the map (still counted for coverage)
|
|
42
44
|
queries: list[dict] = field(default_factory=list) # saved SQL checks that become flags
|
|
43
45
|
silence: list[dict] = field(default_factory=list) # [[silence]] kind / where (glob) / reason (+ by, on)
|
|
44
46
|
rules: list[dict] = field(default_factory=list) # [[rule]] custom pattern checks: id, pattern, files, severity…
|
|
@@ -93,6 +95,11 @@ def load_config(root: Path) -> Config:
|
|
|
93
95
|
cfg.layers = {name: [globs] if isinstance(globs, str) else list(globs) for name, globs in layers.items()}
|
|
94
96
|
cfg.forbid = [parse_rule(r) for r in data.get("rules", {}).get("forbid", [])]
|
|
95
97
|
cfg.ignore += list(data.get("ignore", []))
|
|
98
|
+
ci = data.get("ci", [])
|
|
99
|
+
cfg.ci = [ci] if isinstance(ci, str) else [str(x) for x in ci]
|
|
100
|
+
if not isinstance(data.get("tests", True), bool):
|
|
101
|
+
raise ValueError("factory.toml: `tests` is true (the default) or false")
|
|
102
|
+
cfg.tests = data.get("tests", True)
|
|
96
103
|
t = data.get("thresholds", {})
|
|
97
104
|
cfg.large_file = int(t.get("large_file", cfg.large_file))
|
|
98
105
|
cfg.long_function = int(t.get("long_function", cfg.long_function))
|
codefactory/deps.py
CHANGED
|
@@ -182,9 +182,9 @@ def vulnerabilities(pkgs: list[Package], timeout: int = 30, budget: float = 120)
|
|
|
182
182
|
for i in range(0, len(pkgs), BATCH):
|
|
183
183
|
chunk = pkgs[i : i + BATCH]
|
|
184
184
|
queries = [{"package": {"name": p.name, "ecosystem": p.ecosystem}, "version": p.version} for p in chunk]
|
|
185
|
-
# codefactory: ignore io_in_loop — one request per 500 packages, OSV's batch size
|
|
186
185
|
if left() <= 0:
|
|
187
186
|
raise OSError(f"OSV took longer than {budget:.0f} s")
|
|
187
|
+
# codefactory: ignore io_in_loop — one request per 500 packages, OSV's batch size
|
|
188
188
|
results = _post(f"{API}/querybatch", {"queries": queries}, left()).get("results", [])
|
|
189
189
|
if not isinstance(results, list):
|
|
190
190
|
raise ValueError("OSV's answer has no list of results")
|
codefactory/efficiency.py
CHANGED
|
@@ -201,7 +201,8 @@ def efficiency_flags(g: Graph) -> list[Flag]:
|
|
|
201
201
|
if fixed or migration: # can't grow with the data: worth knowing, not worth fixing
|
|
202
202
|
sev = "info"
|
|
203
203
|
note = (
|
|
204
|
-
" It loops over a list fixed in the code,
|
|
204
|
+
" It loops over a list fixed in the code, or runs once at startup or in a migration, so the number of "
|
|
205
|
+
"calls can't grow with the data: fine as "
|
|
205
206
|
"is unless that list gets long."
|
|
206
207
|
if fixed
|
|
207
208
|
else " It's in a migration, which runs once per upgrade."
|