codefactory-cli 0.20.2__py3-none-any.whl → 0.21.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.
- codefactory/__init__.py +1 -1
- codefactory/analyzers/generic.py +69 -20
- codefactory/analyzers/parallel.py +23 -9
- codefactory/analyzers/treewalk.py +20 -2
- codefactory/analyzers/ts_helper.js +9 -1
- codefactory/analyzers/typescript.py +53 -22
- codefactory/audit.py +25 -7
- codefactory/baseline.py +4 -4
- codefactory/cache.py +33 -12
- codefactory/checks.py +92 -26
- codefactory/cli.py +105 -14
- codefactory/config.py +22 -3
- codefactory/deps.py +51 -21
- codefactory/diff.py +75 -29
- codefactory/efficiency.py +2 -1
- codefactory/export.py +254 -0
- codefactory/flags.py +6 -1
- codefactory/hotspots.py +10 -2
- codefactory/infra.py +4 -2
- codefactory/org.py +6 -1
- codefactory/patch.py +5 -2
- codefactory/paths.py +78 -1
- codefactory/plan.py +5 -3
- codefactory/profile.py +30 -3
- codefactory/rerank.py +29 -0
- codefactory/review.py +111 -62
- codefactory/sarif.py +16 -4
- codefactory/scope.py +42 -0
- codefactory/security.py +32 -16
- codefactory/similar.py +9 -4
- codefactory/skill.py +15 -3
- codefactory/skill_template/SKILL.md +4 -1
- codefactory/sqlgraph.py +27 -6
- codefactory/viewer/__init__.py +9 -2
- codefactory/viewer/factory.css +18 -2
- codefactory/viewer/factory.js +31 -12
- codefactory/viewer/template.html +7 -2
- {codefactory_cli-0.20.2.dist-info → codefactory_cli-0.21.0.dist-info}/METADATA +13 -9
- codefactory_cli-0.21.0.dist-info/RECORD +63 -0
- codefactory_cli-0.20.2.dist-info/RECORD +0 -61
- {codefactory_cli-0.20.2.dist-info → codefactory_cli-0.21.0.dist-info}/WHEEL +0 -0
- {codefactory_cli-0.20.2.dist-info → codefactory_cli-0.21.0.dist-info}/entry_points.txt +0 -0
- {codefactory_cli-0.20.2.dist-info → codefactory_cli-0.21.0.dist-info}/licenses/LICENSE +0 -0
- {codefactory_cli-0.20.2.dist-info → codefactory_cli-0.21.0.dist-info}/top_level.txt +0 -0
codefactory/__init__.py
CHANGED
codefactory/analyzers/generic.py
CHANGED
|
@@ -18,6 +18,7 @@ from collections import Counter, defaultdict
|
|
|
18
18
|
from pathlib import Path
|
|
19
19
|
|
|
20
20
|
from ..graph import Edge, File, Function, Graph, Site
|
|
21
|
+
from ..paths import links_outside
|
|
21
22
|
from . import parallel
|
|
22
23
|
|
|
23
24
|
# extension -> tree-sitter language. Python and TypeScript/JavaScript have their own analyzers.
|
|
@@ -81,11 +82,20 @@ JS_LANGS = {
|
|
|
81
82
|
# I/O by the receiver's or callee's name: a database, the network, files. Matched on calls nothing in the codebase
|
|
82
83
|
# defines, so the codebase's own functions are followed instead.
|
|
83
84
|
IO_RECEIVER = re.compile(
|
|
84
|
-
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|"
|
|
85
86
|
r"redis|em|entityManager|jdbc|mongo|stmt|statement|pool|tx|s3|bucket|requests|"
|
|
86
|
-
r"_db|_repo|_client|_http|\$db|\$pdo|pdo|DB|
|
|
87
|
+
r"_db|_repo|_client|_http|\$db|\$pdo|pdo|DB|HttpClient)\s*(?:\.|->|::)\s*\w+$",
|
|
87
88
|
re.I,
|
|
88
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
|
|
89
99
|
IO_NAME = re.compile(
|
|
90
100
|
r"(?:^|[.:>])(?:query|execute|executeQuery|executeUpdate|exec_query|rawQuery|QueryRow|QueryContext|ExecContext|"
|
|
91
101
|
r"Exec|urlopen|fetch|findById|findOne|findAll|find_by|"
|
|
@@ -143,8 +153,9 @@ def find_files(root: Path, ignore: list[str], include_js: bool) -> list[tuple[st
|
|
|
143
153
|
for name in sorted(filenames):
|
|
144
154
|
ext = os.path.splitext(name)[1]
|
|
145
155
|
lang = exts.get(ext) or exts.get(ext.lower())
|
|
146
|
-
|
|
147
|
-
|
|
156
|
+
rel = Path(dirpath, name).relative_to(root).as_posix()
|
|
157
|
+
if lang and not name.endswith((".d.ts", ".min.js")) and not links_outside(root, rel):
|
|
158
|
+
out.append((rel, lang))
|
|
148
159
|
return out
|
|
149
160
|
|
|
150
161
|
|
|
@@ -190,10 +201,40 @@ def _import_index(rels: list[str]) -> dict[str, list[str]]:
|
|
|
190
201
|
return idx
|
|
191
202
|
|
|
192
203
|
|
|
193
|
-
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]:
|
|
194
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),
|
|
195
|
-
else a package folder, linked through one file (its namesake if there is one). Go imports always name packages
|
|
196
|
-
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)
|
|
197
238
|
s = re.sub(r"\.(?:h|hpp|hh|rb|php|lua|dart|go|rs|java|kt|swift|cs|ex|js|ts)$", "", source.strip())
|
|
198
239
|
parts = [p for p in re.split(r"[./\\:]+", s) if p and p not in ("crate", "self", "super", "~", "@", "..")]
|
|
199
240
|
# the path as written, then without its last part: `import a.b.fn` (Kotlin, Java static) names something inside a.b
|
|
@@ -232,7 +273,7 @@ def analyze_generic(root: Path, ignore: list[str], include_js: bool = False, cac
|
|
|
232
273
|
)
|
|
233
274
|
return g
|
|
234
275
|
items = [(rel, (str(root / rel), rel, lang)) for rel, lang in found]
|
|
235
|
-
parsed = parallel.run(root, "generic", items, parse_file, tool="treewalk-
|
|
276
|
+
parsed = parallel.run(root, "generic", items, parse_file, tool="treewalk-5", cache=cache)
|
|
236
277
|
return link(g, parsed, rails_associations(root, [rel for rel, _ in found if rel.endswith(".rb")]))
|
|
237
278
|
|
|
238
279
|
|
|
@@ -278,13 +319,14 @@ def link(g: Graph, parsed: dict[str, dict], associations: re.Pattern | None = No
|
|
|
278
319
|
langs = Counter(d["lang"] for d in parsed.values())
|
|
279
320
|
g.language = "+".join(sorted(langs))
|
|
280
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 []
|
|
281
323
|
defs: dict[str, list[str]] = defaultdict(list) # name -> function ids
|
|
282
324
|
file_of: dict[str, str] = {}
|
|
283
325
|
kind_of: dict[str, str] = {}
|
|
284
326
|
imported: dict[str, set[str]] = {}
|
|
285
327
|
for rel, d in sorted(parsed.items()):
|
|
286
328
|
g.files.append(File(id=rel, module=rel.rsplit(".", 1)[0].replace("/", "."), loc=d["loc"]))
|
|
287
|
-
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}
|
|
288
330
|
g.edges += [Edge(rel, dst, "import") for dst in sorted(imported[rel])]
|
|
289
331
|
top = Function(id=f"{rel}::<module>", file=rel, name="<module>", qualname="<module>", line=1, end=1, loc=0, kind="module")
|
|
290
332
|
g.functions.append(top)
|
|
@@ -357,30 +399,37 @@ def link(g: Graph, parsed: dict[str, dict], associations: re.Pattern | None = No
|
|
|
357
399
|
target, cands = resolve(name, src)
|
|
358
400
|
for c in [target] if target else cands if len(cands) <= 3 else ():
|
|
359
401
|
refs[(src, c)] += 1
|
|
360
|
-
|
|
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])
|
|
361
405
|
target, cands = resolve(name, src, bare=not re.search(r"\.|->|::", callee), callee=callee)
|
|
362
406
|
if target:
|
|
363
407
|
calls[(src, target)] += 1
|
|
364
408
|
if in_loop:
|
|
365
|
-
g.sites.append(Site(src, "loop_call", line, target=target))
|
|
409
|
+
g.sites.append(Site(src, "loop_call", line, target=target, bounded=startup))
|
|
366
410
|
continue
|
|
367
411
|
if len(cands) <= 3:
|
|
368
412
|
for c in cands:
|
|
369
413
|
refs[(src, c)] += 1
|
|
370
414
|
else: # called by a name many things define (String, Error, Read): any of them may be what runs
|
|
371
415
|
ambiguous.add(name)
|
|
372
|
-
if
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
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
|
+
)
|
|
380
429
|
):
|
|
381
430
|
io.add(callee)
|
|
382
431
|
if in_loop:
|
|
383
|
-
g.sites.append(Site(src, "loop_io", line, detail=callee))
|
|
432
|
+
g.sites.append(Site(src, "loop_io", line, detail=callee, bounded=startup))
|
|
384
433
|
if src in by_id:
|
|
385
434
|
by_id[src].io = sorted(io)
|
|
386
435
|
framework = {f["id"] for d in parsed.values() for f in d["functions"] if f.get("framework")}
|
|
@@ -11,6 +11,7 @@ from __future__ import annotations
|
|
|
11
11
|
|
|
12
12
|
import json
|
|
13
13
|
import os
|
|
14
|
+
import time
|
|
14
15
|
from collections.abc import Callable
|
|
15
16
|
from concurrent.futures import ProcessPoolExecutor
|
|
16
17
|
from pathlib import Path
|
|
@@ -28,29 +29,41 @@ def workers() -> int:
|
|
|
28
29
|
return max(1, min(32, (os.cpu_count() or 1)))
|
|
29
30
|
|
|
30
31
|
|
|
31
|
-
def _stamp(path: Path) -> str:
|
|
32
|
+
def _stamp(path: Path, now_ns: int = 0) -> str:
|
|
33
|
+
"""The file's stamp; "" (never matches) when it changed too recently to trust (see paths.racy)."""
|
|
34
|
+
from ..paths import file_stamp, racy
|
|
35
|
+
|
|
32
36
|
st = path.stat()
|
|
33
|
-
return
|
|
37
|
+
return "" if now_ns and racy(st, now_ns) else file_stamp(st)
|
|
38
|
+
|
|
34
39
|
|
|
40
|
+
def _cache_file(root: Path, name: str) -> Path | None:
|
|
41
|
+
from ..paths import cache_dir
|
|
35
42
|
|
|
36
|
-
|
|
37
|
-
return
|
|
43
|
+
d = cache_dir(root)
|
|
44
|
+
return d / f"files-{name}.json" if d else None
|
|
38
45
|
|
|
39
46
|
|
|
40
47
|
def _load(root: Path, name: str, tool: str) -> dict:
|
|
48
|
+
path = _cache_file(root, name)
|
|
49
|
+
if path is None:
|
|
50
|
+
return {}
|
|
41
51
|
try:
|
|
42
|
-
data = json.loads(
|
|
52
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
43
53
|
except (OSError, ValueError):
|
|
44
54
|
return {}
|
|
45
55
|
return data.get("files", {}) if data.get("tool") == tool else {}
|
|
46
56
|
|
|
47
57
|
|
|
48
58
|
def _save(root: Path, name: str, tool: str, files: dict) -> None:
|
|
59
|
+
path = _cache_file(root, name)
|
|
60
|
+
if path is None:
|
|
61
|
+
return # untrusted cache folder
|
|
49
62
|
try:
|
|
50
|
-
d =
|
|
63
|
+
d = path.parent
|
|
51
64
|
d.mkdir(exist_ok=True)
|
|
52
65
|
(d / ".gitignore").write_text("# codefactory's cache: never committed\n*\n", encoding="utf-8")
|
|
53
|
-
|
|
66
|
+
path.write_text(json.dumps({"tool": tool, "files": files}), encoding="utf-8")
|
|
54
67
|
except OSError:
|
|
55
68
|
pass # a read-only checkout: analyze in full each time
|
|
56
69
|
|
|
@@ -70,13 +83,14 @@ def run(
|
|
|
70
83
|
out: dict[str, dict] = {}
|
|
71
84
|
stamps: dict[str, str] = {}
|
|
72
85
|
todo: list[tuple[str, tuple]] = []
|
|
86
|
+
now_ns = time.time_ns()
|
|
73
87
|
for rel, args in items:
|
|
74
88
|
try:
|
|
75
|
-
stamps[rel] = _stamp(root / rel)
|
|
89
|
+
stamps[rel] = _stamp(root / rel, now_ns)
|
|
76
90
|
except OSError:
|
|
77
91
|
continue
|
|
78
92
|
hit = old.get(rel)
|
|
79
|
-
if hit and hit[0] == stamps[rel]:
|
|
93
|
+
if hit and stamps[rel] and hit[0] == stamps[rel]:
|
|
80
94
|
if hit[1] is not None:
|
|
81
95
|
out[rel] = hit[1]
|
|
82
96
|
else:
|
|
@@ -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):
|
|
@@ -12,9 +12,17 @@ const ts = require(tsPath);
|
|
|
12
12
|
const ignore = new Set(JSON.parse(ignoreJson || "[]"));
|
|
13
13
|
const EXT = /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;
|
|
14
14
|
const rel = (f) => path.relative(root, f).split(path.sep).join("/");
|
|
15
|
+
const realRoot = fs.realpathSync(root);
|
|
16
|
+
// a link to somewhere outside the repository: not its code (a pull request can commit `a.ts -> ~/.npmrc`)
|
|
17
|
+
const outside = (f) => {
|
|
18
|
+
try {
|
|
19
|
+
const r = path.relative(realRoot, fs.realpathSync(f));
|
|
20
|
+
return r.startsWith("..") || path.isAbsolute(r);
|
|
21
|
+
} catch { return true; }
|
|
22
|
+
};
|
|
15
23
|
const skipped = (f) => {
|
|
16
24
|
const parts = rel(f).split("/");
|
|
17
|
-
return parts.slice(0, -1).some((p) => ignore.has(p) || (p.startsWith(".") && p !== "." && p !== "..")) || /\.d\.[mc]?ts$|\.min\.[mc]?js$/.test(f) || !EXT.test(f) || rel(f).startsWith("..");
|
|
25
|
+
return parts.slice(0, -1).some((p) => ignore.has(p) || (p.startsWith(".") && p !== "." && p !== "..")) || /\.d\.[mc]?ts$|\.min\.[mc]?js$/.test(f) || !EXT.test(f) || rel(f).startsWith("..") || outside(f);
|
|
18
26
|
};
|
|
19
27
|
|
|
20
28
|
function walkDir(dir, out) {
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"""TypeScript / JavaScript analyzer. The parsing and call resolution run in Node (ts_helper.js) with the TypeScript
|
|
2
2
|
compiler, because only the type checker can tell what `obj.method()` or a function from a React hook really is.
|
|
3
3
|
|
|
4
|
-
Needs Node on PATH and
|
|
5
|
-
|
|
4
|
+
Needs Node on PATH and a TypeScript 5.x compiler the user installed: CODEFACTORY_TYPESCRIPT pointing at one, or a
|
|
5
|
+
global install (npm install -g typescript@5). Never the one inside the analyzed repository: its node_modules is the
|
|
6
|
+
repository's code (a pull request could commit one), and codefactory never runs the code it analyzes. The compiler
|
|
7
|
+
only parses and type-checks; module resolution (tsconfig paths, aliases) comes from the project's own files either way.
|
|
6
8
|
"""
|
|
7
9
|
|
|
8
10
|
from __future__ import annotations
|
|
@@ -13,6 +15,7 @@ import os
|
|
|
13
15
|
import shutil
|
|
14
16
|
import subprocess
|
|
15
17
|
import sys
|
|
18
|
+
import time
|
|
16
19
|
from importlib.resources import files as pkg_files
|
|
17
20
|
from pathlib import Path
|
|
18
21
|
|
|
@@ -26,10 +29,15 @@ class TypeScriptUnavailable(RuntimeError):
|
|
|
26
29
|
|
|
27
30
|
|
|
28
31
|
def sources_stamp(root: Path, ignore: list[str]) -> str:
|
|
29
|
-
"""A fingerprint of every TypeScript/JavaScript file and tsconfig (empty when there are none
|
|
32
|
+
"""A fingerprint of every TypeScript/JavaScript file and tsconfig (empty when there are none; "racy" when one
|
|
33
|
+
changed too recently to trust, so the result isn't reused)."""
|
|
34
|
+
from ..paths import file_stamp
|
|
35
|
+
from ..paths import racy as too_recent
|
|
36
|
+
|
|
30
37
|
skip = set(ignore)
|
|
31
38
|
h = hashlib.sha1()
|
|
32
|
-
found = False
|
|
39
|
+
found = racy = False
|
|
40
|
+
now_ns = time.time_ns()
|
|
33
41
|
for dirpath, dirnames, filenames in os.walk(root):
|
|
34
42
|
dirnames[:] = sorted(d for d in dirnames if d not in skip)
|
|
35
43
|
for f in sorted(filenames):
|
|
@@ -39,32 +47,51 @@ def sources_stamp(root: Path, ignore: list[str]) -> str:
|
|
|
39
47
|
st = os.stat(os.path.join(dirpath, f))
|
|
40
48
|
except OSError:
|
|
41
49
|
continue
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
50
|
+
racy = racy or too_recent(st, now_ns)
|
|
51
|
+
h.update(f"{os.path.relpath(os.path.join(dirpath, f), root)}|{file_stamp(st)}\n".encode("utf-8", "surrogatepass"))
|
|
52
|
+
return ("racy" if racy else h.hexdigest()) if found else ""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def has_api(folder) -> bool:
|
|
56
|
+
"""A TypeScript package with the JavaScript compiler API (5.x and earlier). TypeScript 7, the native rewrite, ships
|
|
57
|
+
only an unstable API, so requiring it fails."""
|
|
58
|
+
return (Path(folder) / "lib" / "typescript.js").is_file()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _outside(folder: Path, root: Path) -> bool:
|
|
62
|
+
"""Not inside the analyzed repository (a global install can't be the repository's own code)."""
|
|
63
|
+
try:
|
|
64
|
+
return not folder.resolve().is_relative_to(Path(root).resolve())
|
|
65
|
+
except OSError:
|
|
66
|
+
return False
|
|
48
67
|
|
|
49
68
|
|
|
50
69
|
def find_typescript(root: Path, node: str) -> str:
|
|
51
70
|
env = os.environ.get("CODEFACTORY_TYPESCRIPT")
|
|
52
71
|
if env:
|
|
72
|
+
if not has_api(env):
|
|
73
|
+
raise TypeScriptUnavailable(f"CODEFACTORY_TYPESCRIPT ({env}) isn't a TypeScript 5.x package (no lib/typescript.js).")
|
|
53
74
|
return env
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
75
|
+
# a global install: next to node first (no subprocess); then npm, run from the home folder so the analyzed
|
|
76
|
+
# repository's .npmrc (which could set `prefix` to a folder inside it) isn't read
|
|
77
|
+
bin_dir = Path(node).resolve().parent if node else None
|
|
78
|
+
candidates = []
|
|
79
|
+
if bin_dir: # (Linux and macOS: <prefix>/lib/node_modules; Windows: next to node.exe)
|
|
80
|
+
candidates = [bin_dir.parent / "lib" / "node_modules" / "typescript", bin_dir / "node_modules" / "typescript"]
|
|
57
81
|
try:
|
|
58
|
-
npm_root = subprocess.run(
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
except (OSError, subprocess.SubprocessError):
|
|
82
|
+
npm_root = subprocess.run(["npm", "root", "-g"], capture_output=True, text=True, timeout=30, cwd=Path.home(),
|
|
83
|
+
shell=sys.platform == "win32").stdout.strip() # fmt: skip
|
|
84
|
+
if npm_root:
|
|
85
|
+
candidates.append(Path(npm_root) / "typescript")
|
|
86
|
+
except (OSError, subprocess.SubprocessError, RuntimeError): # (RuntimeError: no home folder)
|
|
64
87
|
pass
|
|
88
|
+
for c in candidates:
|
|
89
|
+
if has_api(c) and _outside(c, root):
|
|
90
|
+
return str(c)
|
|
65
91
|
raise TypeScriptUnavailable(
|
|
66
|
-
"TypeScript files found, but
|
|
67
|
-
"
|
|
92
|
+
"TypeScript files found, but no TypeScript compiler of your own is installed: `npm install -g typescript@5` (or "
|
|
93
|
+
"set CODEFACTORY_TYPESCRIPT to its folder). codefactory never runs the one in the repository's node_modules: "
|
|
94
|
+
"that's the repository's code."
|
|
68
95
|
)
|
|
69
96
|
|
|
70
97
|
|
|
@@ -76,7 +103,11 @@ def analyze_typescript(root: Path, ignore: list[str], cache: bool = True) -> Gra
|
|
|
76
103
|
from .parallel import _tool_hash
|
|
77
104
|
|
|
78
105
|
stamp = f"{stamp}|{_tool_hash()}"
|
|
79
|
-
|
|
106
|
+
from ..paths import cache_dir
|
|
107
|
+
|
|
108
|
+
folder = cache_dir(root) if cache and not stamp.startswith("racy") else None # racy: nothing to reuse or keep
|
|
109
|
+
cache = folder is not None
|
|
110
|
+
saved = folder / "typescript.json" if folder else None
|
|
80
111
|
data = None
|
|
81
112
|
if cache:
|
|
82
113
|
try:
|
codefactory/audit.py
CHANGED
|
@@ -12,8 +12,8 @@ import re
|
|
|
12
12
|
import subprocess
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
|
|
15
|
-
from .checks import ANY, PATTERNS, PLACEHOLDER, VENDOR_SECRETS, Check, Evidence
|
|
16
|
-
from .paths import drop_ignored, is_test, walk
|
|
15
|
+
from .checks import ANY, PATTERNS, PLACEHOLDER, VENDOR_SECRETS, Check, Evidence, redact
|
|
16
|
+
from .paths import drop_ignored, is_test, links_outside, walk
|
|
17
17
|
from .suppress import MARK
|
|
18
18
|
|
|
19
19
|
# GitHub Actions
|
|
@@ -59,6 +59,8 @@ def _excerpt(text: str) -> str:
|
|
|
59
59
|
def workflows(root: Path, out: dict[str, Check]) -> None:
|
|
60
60
|
for path in sorted((root / ".github" / "workflows").glob("*.y*ml")):
|
|
61
61
|
rel = path.relative_to(root).as_posix()
|
|
62
|
+
if links_outside(root, rel):
|
|
63
|
+
continue
|
|
62
64
|
try:
|
|
63
65
|
text = path.read_text(encoding="utf-8", errors="replace")
|
|
64
66
|
except OSError:
|
|
@@ -121,7 +123,7 @@ def dockerfiles(root: Path, files: list[Path], out: dict[str, Check]) -> None:
|
|
|
121
123
|
out["docker_latest"].hits.append(Evidence(rel, _line(text, m.start()), f"FROM {image}"))
|
|
122
124
|
for m in ENV_SECRET.finditer(text):
|
|
123
125
|
if not re.search(r"\$\{?\w+|changeme|example|<", m.group(0), re.I):
|
|
124
|
-
out["docker_secret"].hits.append(Evidence(rel, _line(text, m.start()), _excerpt(m.group(0))))
|
|
126
|
+
out["docker_secret"].hits.append(Evidence(rel, _line(text, m.start()), redact(_excerpt(m.group(0)))))
|
|
125
127
|
|
|
126
128
|
|
|
127
129
|
def mobile(root: Path, out: dict[str, Check]) -> None:
|
|
@@ -166,6 +168,11 @@ def history(root: Path, current: set[str], out: dict[str, Check], max_lines: int
|
|
|
166
168
|
commit, file, seen, read, note = "", "", set(), 0, ""
|
|
167
169
|
texts: dict[str, str] = {}
|
|
168
170
|
pats = PATTERNS["secret"]
|
|
171
|
+
import threading
|
|
172
|
+
|
|
173
|
+
watchdog = threading.Timer(timeout, proc.kill) # git stalled or slow: stop it, and say what was read
|
|
174
|
+
watchdog.daemon = True
|
|
175
|
+
watchdog.start()
|
|
169
176
|
try:
|
|
170
177
|
for raw in proc.stdout:
|
|
171
178
|
read += 1
|
|
@@ -190,20 +197,31 @@ def history(root: Path, current: set[str], out: dict[str, Check], max_lines: int
|
|
|
190
197
|
if value in current or (file, value) in seen or value in _now(root, file, texts):
|
|
191
198
|
continue # still in the code: the current-files check reports it (or it was marked as intended)
|
|
192
199
|
seen.add((file, value))
|
|
193
|
-
out["history_secret"].hits.append(Evidence(file, 0, f"commit {commit}: {_excerpt(line)}"))
|
|
200
|
+
out["history_secret"].hits.append(Evidence(file, 0, f"commit {commit}: {redact(_excerpt(line))}"))
|
|
194
201
|
finally:
|
|
202
|
+
timed_out = not watchdog.is_alive() and proc.poll() not in (0, None) and read <= max_lines
|
|
203
|
+
watchdog.cancel()
|
|
195
204
|
proc.kill()
|
|
196
205
|
proc.stdout.close()
|
|
197
206
|
proc.wait(timeout=timeout)
|
|
207
|
+
if timed_out and not note:
|
|
208
|
+
note = f"history read for {timeout} s, then stopped ({read:,} changed lines, the most recent commits)"
|
|
198
209
|
shallow = subprocess.run(["git", "-C", str(root), "rev-parse", "--is-shallow-repository"], capture_output=True, text=True)
|
|
199
210
|
if shallow.stdout.strip() == "true":
|
|
200
211
|
note = (note + "; " if note else "") + "shallow clone: only part of the history was available"
|
|
201
212
|
return note
|
|
202
213
|
|
|
203
214
|
|
|
204
|
-
def current_secrets(secret_check: Check) -> set[str]:
|
|
205
|
-
"""The secret values in today's files (history only reports the ones that are gone).
|
|
206
|
-
|
|
215
|
+
def current_secrets(secret_check: Check, root: Path | None = None) -> set[str]:
|
|
216
|
+
"""The secret values in today's files (history only reports the ones that are gone). Reported text is redacted,
|
|
217
|
+
so the values are read again from each reported line."""
|
|
218
|
+
lines = []
|
|
219
|
+
for e in secret_check.hits:
|
|
220
|
+
try:
|
|
221
|
+
lines.append((root / e.file).read_text(encoding="utf-8", errors="replace").splitlines()[e.line - 1])
|
|
222
|
+
except (OSError, IndexError, TypeError):
|
|
223
|
+
lines.append(e.text)
|
|
224
|
+
return {m.group(0) for line in lines for p in PATTERNS["secret"] if (m := p.search(line))}
|
|
207
225
|
|
|
208
226
|
|
|
209
227
|
def find_dockerfiles(root: Path) -> list[Path]:
|
codefactory/baseline.py
CHANGED
|
@@ -29,10 +29,10 @@ def baseline_path(repo_or_file: Path) -> Path:
|
|
|
29
29
|
def write_baseline(graph: dict, path: Path) -> int:
|
|
30
30
|
fns = {f["id"]: f for f in graph["functions"]}
|
|
31
31
|
counts = Counter(issue_key(graph, f, fns) for f in graph["flags"])
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
)
|
|
32
|
+
from .paths import write_file
|
|
33
|
+
|
|
34
|
+
doc = {"version": 1, "created": date.today().isoformat(), "issues": dict(sorted(counts.items()))}
|
|
35
|
+
write_file(path, json.dumps(doc, indent=1) + "\n")
|
|
36
36
|
return sum(counts.values())
|
|
37
37
|
|
|
38
38
|
|
codefactory/cache.py
CHANGED
|
@@ -9,6 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
import hashlib
|
|
10
10
|
import json
|
|
11
11
|
import os
|
|
12
|
+
import time
|
|
12
13
|
from pathlib import Path
|
|
13
14
|
|
|
14
15
|
from . import __version__
|
|
@@ -33,7 +34,7 @@ def _parsers() -> str:
|
|
|
33
34
|
if node:
|
|
34
35
|
bin_dir = Path(node).resolve().parent
|
|
35
36
|
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) / "
|
|
37
|
+
ts = next((c for c in candidates if c and (Path(c) / "lib" / "typescript.js").is_file()), "")
|
|
37
38
|
return f"pack={available()}|node={bool(node)}|ts={ts}"
|
|
38
39
|
|
|
39
40
|
|
|
@@ -51,12 +52,14 @@ def _tool_stamp() -> str:
|
|
|
51
52
|
return "\n".join(parts)
|
|
52
53
|
|
|
53
54
|
|
|
54
|
-
def fingerprint(root: Path, ignore: list[str]) -> str:
|
|
55
|
+
def fingerprint(root: Path, ignore: list[str], recent: list | None = None) -> str:
|
|
56
|
+
"""Every source file's stamp. `recent` (if given) gets True when a file changed too recently to trust."""
|
|
57
|
+
from .paths import file_stamp, racy
|
|
58
|
+
|
|
59
|
+
now_ns = time.time_ns()
|
|
55
60
|
skip = set(ignore)
|
|
56
61
|
h = hashlib.sha1((_tool_stamp() + "\n" + _parsers()).encode("utf-8", "surrogatepass"))
|
|
57
62
|
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
63
|
for dirpath, dirnames, filenames in os.walk(root):
|
|
61
64
|
dirnames[:] = sorted(d for d in dirnames if d not in skip and not d.endswith(".egg-info"))
|
|
62
65
|
for name in sorted(filenames):
|
|
@@ -66,28 +69,46 @@ def fingerprint(root: Path, ignore: list[str]) -> str:
|
|
|
66
69
|
st = os.stat(p)
|
|
67
70
|
except OSError:
|
|
68
71
|
continue
|
|
69
|
-
|
|
72
|
+
if recent is not None and not recent and racy(st, now_ns):
|
|
73
|
+
recent.append(True)
|
|
74
|
+
h.update(f"{os.path.relpath(p, root)}|{file_stamp(st)}\n".encode("utf-8", "surrogatepass"))
|
|
70
75
|
return h.hexdigest()
|
|
71
76
|
|
|
72
77
|
|
|
73
|
-
def _dir(root: Path) -> Path:
|
|
74
|
-
|
|
78
|
+
def _dir(root: Path) -> Path | None:
|
|
79
|
+
from .paths import cache_dir
|
|
80
|
+
|
|
81
|
+
return cache_dir(root)
|
|
75
82
|
|
|
76
83
|
|
|
77
|
-
def load_cached(root: Path, ignore: list[str]) -> dict | None:
|
|
78
|
-
|
|
84
|
+
def load_cached(root: Path, ignore: list[str], stamp: str | None = None) -> dict | None:
|
|
85
|
+
d = _dir(root)
|
|
86
|
+
if d is None:
|
|
87
|
+
return None
|
|
88
|
+
path = d / "graph.json"
|
|
79
89
|
try:
|
|
80
90
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
81
91
|
except (OSError, ValueError):
|
|
82
92
|
return None
|
|
83
|
-
return data.get("graph") if data.get("fingerprint") == fingerprint(root, ignore) else None
|
|
93
|
+
return data.get("graph") if data.get("fingerprint") == (stamp or fingerprint(root, ignore)) else None
|
|
84
94
|
|
|
85
95
|
|
|
86
|
-
def save_cache(root: Path, ignore: list[str], graph: dict) -> None:
|
|
96
|
+
def save_cache(root: Path, ignore: list[str], graph: dict, stamp: str | None = None, recent: bool = False) -> None:
|
|
97
|
+
"""Keep the graph under `stamp`: the fingerprint taken *before* analysis, so a file edited while it ran makes the
|
|
98
|
+
next run's fingerprint differ instead of being cached as analyzed. `recent`: a file changed in the moments before
|
|
99
|
+
the stamp was taken (see paths.racy): then nothing is kept."""
|
|
87
100
|
d = _dir(root)
|
|
101
|
+
if d is None:
|
|
102
|
+
return # untrusted cache folder: analyze in full each time
|
|
103
|
+
if stamp is None:
|
|
104
|
+
changed: list = []
|
|
105
|
+
stamp = fingerprint(root, ignore, changed)
|
|
106
|
+
recent = bool(changed)
|
|
107
|
+
if recent:
|
|
108
|
+
return # a same-size edit in the same clock tick would look unchanged
|
|
88
109
|
try:
|
|
89
110
|
d.mkdir(exist_ok=True)
|
|
90
111
|
(d / ".gitignore").write_text("# codefactory's cache: never committed\n*\n", encoding="utf-8")
|
|
91
|
-
(d / "graph.json").write_text(json.dumps({"fingerprint":
|
|
112
|
+
(d / "graph.json").write_text(json.dumps({"fingerprint": stamp, "graph": graph}), encoding="utf-8")
|
|
92
113
|
except OSError:
|
|
93
114
|
pass # read-only checkout: just analyze each time
|