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.
Files changed (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/intent.py ADDED
@@ -0,0 +1,106 @@
1
+ # codefactory: ignore-file swallowed — the patterns themselves
2
+ """Recognises code that looks risky to a pattern but shows its intent, so the review doesn't report it.
3
+
4
+ Each rule here came from a false positive on a real codebase. They stay narrow: when in doubt, keep reporting.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ # ---- swallowed errors ----------------------------------------------------------------------------------------------
12
+
13
+ # Best-effort cleanup of something that may already be gone: failing to cancel, dismiss or delete it is expected.
14
+ # Deleting is only "cleanup" for leftovers (a stored item, a file, a cache), never for the user's records.
15
+ CLEANUP = re.compile(
16
+ r"\b(?:(?:dismiss|cancel|unregister|unsubscribe|abort)\w*|(?:delete|remove|unlink|clear)\w*"
17
+ r"(?:Item|File|Folder|Dir|Temp|Cache|Database|Key)\w*)\s*\([^()]*(?:\([^()]*\)[^()]*)*\)\s*\.catch\("
18
+ )
19
+ # `const x = await load().catch(() => null)`: the failure becomes a value the next lines handle. (`() => {}` is an
20
+ # empty body, not a value, so it isn't one.)
21
+ FALLBACK = re.compile(
22
+ r"(?<![=!<>])=(?![=>])\s*(?:await\s+)?[^;]*\.catch\(\s*\(\s*\)\s*=>\s*(?:null|undefined|\[\]|false|0|''|\"\")\s*\)"
23
+ )
24
+ TRAILING_COMMENT = re.compile(r"(?:\)|\}|;|\bpass)\s*(?://|#)\s*\S")
25
+
26
+
27
+ def swallow_intent(line: str, above: str) -> str | None:
28
+ """Why an empty catch on this line is deliberate, or None if it isn't shown to be."""
29
+ if TRAILING_COMMENT.search(line.split("catch", 1)[-1] if "catch" in line else line) or re.match(r"\s*(?://|#)\s*\S", above):
30
+ return "explained"
31
+ if re.search(r"catch\s*\(\s*(?:_|ignored?|expected|unused)\b", line): # Kotlin/Java/C#: named to say it's ignored
32
+ return "explained"
33
+ if CLEANUP.search(line):
34
+ return "cleanup"
35
+ if FALLBACK.search(line):
36
+ return "fallback"
37
+ return None
38
+
39
+
40
+ # ---- SQL built from strings ----------------------------------------------------------------------------------------
41
+
42
+ NUMERIC = re.compile(
43
+ r"^(?:\d+|Math\.\w+\(.*\)|Number\(.*\)|parseInt\(.*\)|parseFloat\(.*\)|int\(.*\)|float\(.*\)|len\(.*\)|"
44
+ r"[\w.]+\s*[-+*/%]\s*\d+|\d+\s*[-+*/%]\s*[\w.]+|[\w.]+\.length|[\w.]+\.size)$"
45
+ )
46
+ CONST_NAME = re.compile(r"\b[A-Z][A-Z0-9_]{2,}\b")
47
+
48
+
49
+ def _root(expr: str) -> str:
50
+ """`cols.join(", ")` -> `cols`; `[...order].reverse()` -> `order`; `row.name` -> `row`."""
51
+ m = re.match(r"\s*(?:\[\s*\.\.\.)?\s*([A-Za-z_$][\w$]*)", expr)
52
+ return m.group(1) if m else ""
53
+
54
+
55
+ def safe_names(lines: list[str], i: int, span: int = 25) -> set[str]:
56
+ """Names that, in the lines leading up to line i, only hold values from a fixed list or that were checked
57
+ against one: `for (const t of Object.keys(TABLES))`, `const cols = keys.filter((c) => allowed.has(c))`,
58
+ `if (known.has(t))`, `for t in TABLES`. Followed one step through names already known to be safe."""
59
+ safe: set[str] = set()
60
+ window = lines[max(0, i - span) : i]
61
+ for _ in range(2): # a second pass picks up names derived from names the first pass found
62
+ for ln in window:
63
+ for m in re.finditer(r"(?:\.has|\.includes|\bin)\s*\(\s*([A-Za-z_$][\w$]*)\s*\)", ln):
64
+ safe.add(m.group(1))
65
+ checked_filter = re.search(r"\(\s*\(?\s*(\w+)\s*\)?\s*=>\s*[^)]*?(?:\.has\(\s*\1\s*\)|\1\s+in\s+[A-Z])", ln)
66
+ if checked_filter and (a := re.match(r"\s*(?:const|let|var)?\s*(\w+)\s*=", ln)):
67
+ safe.add(a.group(1)) # const cols = xs.filter((c) => allowed.has(c))
68
+ for m in re.finditer(r"for\s*\(\s*(?:const|let|var)\s+(\w+)\s+of\s+(.+?)\)\s*\{?\s*$|for\s+(\w+)\s+in\s+(.+):", ln):
69
+ name, src = (m.group(1), m.group(2)) if m.group(1) else (m.group(3), m.group(4))
70
+ if CONST_NAME.search(src) or _root(src.replace("Object.keys(", "")) in safe:
71
+ safe.add(name)
72
+ # typed as a number: `int id`, `for (Integer id : ids)`, `id: Int`, Go's `id int`
73
+ for m in re.finditer(
74
+ r"\b(?:int|long|short|Integer|Long|Short|int32|int64|uint\w*)\s+(\w+)\b|(\w+)\s*:\s*(?:Int|Long|Short|int|number)\b|"
75
+ r"\b(\w+)\s+(?:int|int32|int64|uint\w*)\b",
76
+ ln,
77
+ ):
78
+ safe.add(m.group(1) or m.group(2) or m.group(3))
79
+ if (a := re.match(r"\s*(?:const|let|var)?\s*\$?(\w+)\s*=\s*(.+)", ln)) and not a.group(2).startswith("="):
80
+ rhs = a.group(2)
81
+ if (
82
+ re.match(r"(?:Object\.(?:keys|values)\(\s*)?[A-Z][A-Z0-9_]{2,}\b", rhs)
83
+ or (_root(rhs) in safe and _root(rhs) != a.group(1))
84
+ or NUMERIC.match(rhs.strip().rstrip(";")) # size = int(request.args["size"])
85
+ or re.search(r"""\.join\(\s*\(?['"]\?['"]""", rhs) # placeholders: ",".join("?" * len(ids))
86
+ ):
87
+ safe.add(a.group(1))
88
+ joined = " ".join(window) # `$scope = cond ? 'concat(?, id)' : 'cast(? as text)';` (PHP, JS) or `x = 'a' if c else 'b'`
89
+ lit = r"""(?:'[^']*'|"[^"]*")"""
90
+ for m in re.finditer(rf"\$?(\w+)\s*=\s*[^;=]*?\?\s*{lit}\s*:\s*{lit}\s*;|(\w+)\s*=\s*{lit}\s+if\s+[^\n]+?\s+else\s+{lit}",
91
+ joined): # fmt: skip
92
+ safe.add(m.group(1) or m.group(2))
93
+ return safe
94
+
95
+
96
+ def interp_safe(expr: str, safe: set[str]) -> bool:
97
+ e = expr.strip()
98
+ return bool(NUMERIC.match(e)) or _root(e) in safe
99
+
100
+
101
+ # ---- CI ------------------------------------------------------------------------------------------------------------
102
+
103
+
104
+ def push_skip_explained(workflow: str) -> bool:
105
+ """The workflow says in a comment why it doesn't run on push (a deliberate choice, e.g. to save CI minutes)."""
106
+ return any(re.match(r"\s*#.*\bpush", ln, re.I) for ln in workflow.splitlines())
codefactory/layers.py ADDED
@@ -0,0 +1,143 @@
1
+ """Which layer (factory zone) each file belongs to, and the zones' left-to-right order."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import sys
7
+ from collections import Counter
8
+ from fnmatch import fnmatch
9
+ from pathlib import PurePosixPath
10
+
11
+ from . import paths
12
+ from .config import Config
13
+ from .graph import Graph
14
+
15
+ TEST_DIRS = set(paths.TEST_DIRS)
16
+ SOURCE_DIRS = {"src", "lib", "source"}
17
+
18
+
19
+ def _inferred(paths: list[str], roots: set[str] | None = None) -> dict[str, str]:
20
+ """Layer = the first folder after the folders every file shares (src/ and one top package are skipped)."""
21
+ dirs = [PurePosixPath(p).parts[:-1] for p in paths]
22
+ nontest = [d for d in dirs if not (set(d) & TEST_DIRS)] or dirs
23
+ common: list[str] = []
24
+ if nontest:
25
+ for parts in zip(*nontest, strict=False): # up to the shortest path
26
+ if len(set(parts)) != 1:
27
+ break
28
+ common.append(parts[0])
29
+ out: dict[str, str] = {}
30
+ deeper: dict[str, tuple[str, ...]] = {} # the folders below each file's layer
31
+ for p, d in zip(paths, dirs, strict=True):
32
+ if set(d) & TEST_DIRS:
33
+ out[p] = "tests"
34
+ continue
35
+ rest = d[len(common) :] if tuple(d[: len(common)]) == tuple(common) else d
36
+ if rest and rest[0] in SOURCE_DIRS: # src/app/x.ts -> "app"; files directly in src/ -> "src"
37
+ out[p] = rest[1] if len(rest) > 1 else rest[0]
38
+ deeper[p] = rest[2:]
39
+ continue
40
+ out[p] = rest[0] if rest else (common[-1] if common else "root")
41
+ deeper[p] = rest[1:]
42
+ if not rest and common and roots is not None:
43
+ roots.add(p) # at the top of the package every file shares: placed by how it's used (_place_roots)
44
+ return _split_dominant(out, deeper, roots if roots is not None else set())
45
+
46
+
47
+ def _split_dominant(out: dict[str, str], deeper: dict[str, tuple[str, ...]], roots: set[str]) -> dict[str, str]:
48
+ """One zone holding most of the code (pip/_internal/…, app/core/…) says nothing: split it by the next folder level,
49
+ as long as that gives several real zones. Files directly in the zone's folder keep its name."""
50
+ counts = Counter(layer for layer in out.values() if layer != "tests")
51
+ total = sum(counts.values())
52
+ if not counts:
53
+ return out
54
+ top, n = counts.most_common(1)[0]
55
+ members = [p for p, layer in out.items() if layer == top]
56
+ subs = Counter(deeper[p][0] for p in members if deeper.get(p))
57
+ if total >= 12 and n >= 0.7 * total and len([c for c in subs.values() if c >= 2]) >= 3:
58
+ for p in members:
59
+ if deeper.get(p):
60
+ out[p] = deeper[p][0]
61
+ else:
62
+ roots.add(p) # directly in the split zone's folder: placed by how it's used (_place_roots)
63
+ return out
64
+
65
+
66
+ def _place_roots(g: Graph, inferred: dict[str, str], roots: set[str]) -> None:
67
+ """Files left at the top of a split package mix two roles: things the zones below use (config, logging, errors)
68
+ and things that use them (the CLI, the app). One zone for both reads as a layer that depends on everything and
69
+ is depended on by everything, so each goes by its imports: more importers inside than imports out is "shared"."""
70
+ if not roots or len({inferred[p] for p in inferred if p not in roots and inferred[p] != "tests"}) < 2:
71
+ return # no zones below them to be shared with or built on
72
+ into, out_of = Counter(), Counter()
73
+ for e in g.edges:
74
+ if e.kind == "import" and inferred.get(e.src) != "tests":
75
+ if e.dst in roots and e.src not in roots:
76
+ into[e.dst] += 1
77
+ if e.src in roots and e.dst not in roots:
78
+ out_of[e.src] += 1
79
+ for p in roots:
80
+ base = inferred[p]
81
+ inferred[p] = f"{base} shared" if into[p] > out_of[p] else f"{base} app"
82
+
83
+
84
+ def _by_depth(g: Graph, ids: set[str]) -> dict[str, str]:
85
+ """For code with no folders to go by: zones by import depth. "level 0" imports nothing else here (the
86
+ foundation); each level up builds on the ones below, like stages of a production line. Import loops share a level."""
87
+ adj = {i: set() for i in ids}
88
+ for e in g.edges:
89
+ if e.kind == "import" and e.src in ids and e.dst in ids:
90
+ adj[e.src].add(e.dst)
91
+ depth: dict[str, int] = {}
92
+
93
+ def level(v: str, trail: set[str]) -> int:
94
+ if v in depth:
95
+ return depth[v]
96
+ if v in trail: # a loop: stop here
97
+ return 0
98
+ trail.add(v)
99
+ d = max((level(w, trail) + 1 for w in adj[v]), default=0)
100
+ trail.discard(v)
101
+ depth[v] = d
102
+ return d
103
+
104
+ sys.setrecursionlimit(max(sys.getrecursionlimit(), len(ids) * 4 + 100))
105
+ out = {}
106
+ top = max((level(v, set()) for v in ids), default=0)
107
+ width = max(1, -(-(top + 1) // 6)) # at most 6 zones
108
+ for v in ids:
109
+ lo = (level(v, set()) // width) * width
110
+ hi = min(top, lo + width - 1)
111
+ out[v] = f"level {lo}" if lo == hi else f"level {lo}-{hi}"
112
+ return out
113
+
114
+
115
+ def assign_layers(g: Graph, cfg: Config) -> None:
116
+ paths = [f.id for f in g.files]
117
+ roots: set[str] = set()
118
+ inferred = _inferred(paths, roots)
119
+ _place_roots(g, inferred, roots)
120
+ main = {p for p, layer in inferred.items() if layer != "tests"}
121
+ if not cfg.layers and len({inferred[p] for p in main}) == 1 and len(main) > 6:
122
+ inferred.update(_by_depth(g, main))
123
+ for f in g.files:
124
+ f.layer = next((name for name, globs in cfg.layers.items() if any(fnmatch(f.id, gl) for gl in globs)), inferred[f.id])
125
+ g.layers = order_layers(g)
126
+ g.rules = [f"{a} -> {b}" for a, b in cfg.forbid]
127
+
128
+
129
+ def order_layers(g: Graph) -> list[str]:
130
+ """Layers that depend on others go left (entry points, UI), layers others depend on go right (data, utils)."""
131
+ layer_of = {f.id: f.layer for f in g.files}
132
+ score: Counter = Counter({f.layer: 0 for f in g.files})
133
+ for e in g.edges:
134
+ if e.kind != "import":
135
+ continue
136
+ a, b = layer_of.get(e.src), layer_of.get(e.dst)
137
+ if a and b and a != b:
138
+ score[a] += 1
139
+ score[b] -= 1
140
+ levels = {n: int(m.group(1)) for n in score if (m := re.fullmatch(r"level (\d+)(-\d+)?", n))}
141
+ if levels and len(levels) == len([n for n in score if n != "tests"]):
142
+ return sorted(score, key=lambda name: (name != "tests", -levels.get(name, 0)))
143
+ return sorted(score, key=lambda name: (name != "tests", -score[name], name))
codefactory/org.py ADDED
@@ -0,0 +1,131 @@
1
+ """Many repositories at once: a dashboard with each one's health, findings and trend, and findings per owning team.
2
+
3
+ Each run appends a snapshot to the repository's `.codefactory/history.jsonl` (one per day; a second run the same day
4
+ replaces it), so the dashboard can show whether things are getting better. The page is one self-contained HTML file.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import html
10
+ import json
11
+ from collections import Counter
12
+ from datetime import date
13
+ from pathlib import Path
14
+
15
+ SEVS = ("Critical", "High", "Medium", "Low")
16
+
17
+
18
+ def snapshot(root: Path, graph: dict) -> dict:
19
+ from .owners import load as load_owners
20
+ from .review import Review
21
+
22
+ r = Review(graph, root)
23
+ r.run()
24
+ grade, _ = r.health()
25
+ owners = load_owners(root)
26
+ per_owner: dict[str, Counter] = {}
27
+ if owners:
28
+ file_of = {fn["id"]: fn["file"] for fn in graph["functions"]}
29
+ for f in graph["flags"]:
30
+ file = file_of.get(f["target"], f["target"])
31
+ for who in owners.of(file):
32
+ per_owner.setdefault(who, Counter())[f["severity"]] += 1
33
+ code = [f for f in graph["files"]]
34
+ return {
35
+ "repo": root.name,
36
+ "profile": r.profile.summary(),
37
+ "path": str(root),
38
+ "date": date.today().isoformat(),
39
+ "grade": grade,
40
+ "findings": {s: sum(1 for f in r.findings if f.severity == s) for s in SEVS},
41
+ "flags": dict(Counter(f["severity"] for f in graph["flags"])),
42
+ "files": len(code),
43
+ "lines": sum(f["loc"] for f in code),
44
+ "languages": graph["language"],
45
+ "endpoints": len(r.surface.entries),
46
+ "open_writes": sum(1 for e, _ in r._writing_entries() if not e.auth) if r.surface.entries else 0,
47
+ "tests_reach": r.test_pct,
48
+ "top": [{"severity": f.severity, "title": f.title} for f in r.findings[:3]],
49
+ "owners": {k: dict(v) for k, v in per_owner.items()},
50
+ }
51
+
52
+
53
+ def record(root: Path, snap: dict) -> list[dict]:
54
+ """Append today's snapshot to the repository's history; return the history (oldest first)."""
55
+ path = root / ".codefactory" / "history.jsonl"
56
+ rows = []
57
+ try:
58
+ rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
59
+ except (OSError, ValueError):
60
+ rows = []
61
+ rows = [r for r in rows if r.get("date") != snap["date"]] + [{k: snap[k] for k in ("date", "grade", "findings", "flags")}]
62
+ try:
63
+ path.parent.mkdir(exist_ok=True)
64
+ path.write_text("".join(json.dumps(r) + "\n" for r in rows[-365:]), encoding="utf-8")
65
+ except OSError:
66
+ pass
67
+ return rows
68
+
69
+
70
+ def _spark(history: list[dict]) -> str:
71
+ """Critical + High + Medium findings over time, as a small inline SVG."""
72
+ values = [sum(h["findings"].get(s, 0) for s in SEVS[:3]) for h in history[-30:]]
73
+ if len(values) < 2:
74
+ return ""
75
+ hi = max(values) or 1
76
+ pts = " ".join(f"{i * 80 / (len(values) - 1):.1f},{22 - v * 20 / hi:.1f}" for i, v in enumerate(values))
77
+ return (
78
+ '<svg width="80" height="24" aria-label="trend">'
79
+ f'<polyline fill="none" stroke="currentColor" stroke-width="1.5" points="{pts}"/></svg>'
80
+ )
81
+
82
+
83
+ def _row(s: dict, history: list[dict]) -> str:
84
+ e = html.escape
85
+ f = s["findings"]
86
+ grade_class = "grade-" + s["grade"].lower().replace(" ", "-")
87
+ top = "<br>".join(
88
+ '<span class="sev-' + e(t["severity"].lower()) + '">' + e(t["severity"]) + "</span> " + e(t["title"]) for t in s["top"]
89
+ )
90
+ endpoints = str(s["endpoints"]) + (f" ({s['open_writes']} open writes)" if s["open_writes"] else "")
91
+ reach = "" if s["tests_reach"] is None else f"{s['tests_reach']}%"
92
+ cells = [
93
+ f'<td><b>{e(s["repo"])}</b><div class="muted">{e(s.get("profile", ""))}</div>'
94
+ f'<div class="muted">{e(s["languages"])} · {s["files"]:,} files · {s["lines"]:,} lines</div></td>',
95
+ f'<td class="{grade_class}">{e(s["grade"])}</td>',
96
+ *(f'<td class="num">{f[k]}</td>' for k in SEVS),
97
+ f'<td class="num">{endpoints}</td>',
98
+ f'<td class="num">{reach}</td>',
99
+ f"<td>{_spark(history)}</td>",
100
+ f'<td class="top">{top}</td>',
101
+ ]
102
+ return "<tr>" + "".join(cells) + "</tr>"
103
+
104
+
105
+ def page(snaps: list[dict], histories: dict[str, list[dict]]) -> str:
106
+ from importlib.resources import files
107
+
108
+ order = {"At risk": 0, "Fragile": 1, "Adequate": 2, "Strong": 3}
109
+ snaps = sorted(snaps, key=lambda s: (order.get(s["grade"], 9), -s["findings"]["Critical"], -s["findings"]["High"]))
110
+ owners: dict[str, Counter] = {}
111
+ for s in snaps:
112
+ for who, c in s["owners"].items():
113
+ owners.setdefault(who, Counter()).update(c)
114
+ owner_section = ""
115
+ if owners:
116
+ rows = [
117
+ f'<tr><td>{html.escape(who)}</td><td class="num">{c["high"]}</td><td class="num">{c["warn"]}</td>'
118
+ f'<td class="num">{c["info"]}</td></tr>'
119
+ for who, c in sorted(owners.items(), key=lambda kv: (-kv[1]["high"], -kv[1]["warn"]))[:40]
120
+ ]
121
+ owner_section = (
122
+ '<h2>By owner</h2><div class="wrap"><table><thead><tr><th>Owner</th><th class="num">High</th>'
123
+ '<th class="num">Warn</th><th class="num">Info</th></tr></thead><tbody>' + "".join(rows) + "</tbody></table></div>"
124
+ )
125
+ template = (files("codefactory") / "viewer" / "dashboard.html").read_text(encoding="utf-8")
126
+ summary = f"{len(snaps)} repositories · {date.today().isoformat()} · worst first"
127
+ return (
128
+ template.replace("__SUMMARY__", summary)
129
+ .replace("__ROWS__", "\n".join(_row(s, histories.get(s["path"], [])) for s in snaps))
130
+ .replace("__OWNERS__", owner_section)
131
+ )
codefactory/owners.py ADDED
@@ -0,0 +1,72 @@
1
+ """Who owns a file, from CODEOWNERS (GitHub's format; GitLab's is compatible for these rules), so every finding can be
2
+ routed to the team that has to act on it.
3
+
4
+ Rules are gitignore-style patterns followed by owners; the last matching rule wins, as on GitHub. Supported: `*`,
5
+ `**`, `?`, a leading `/` (anchored to the root), a trailing `/` (a folder and everything in it), and a pattern without
6
+ a slash matching at any depth.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from functools import lru_cache
13
+ from pathlib import Path
14
+
15
+ LOCATIONS = (".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS", ".gitlab/CODEOWNERS")
16
+
17
+
18
+ def _regex(pattern: str) -> re.Pattern:
19
+ anchored = pattern.startswith("/") or "/" in pattern.rstrip("/")
20
+ p = pattern.strip("/")
21
+ folder = pattern.endswith("/")
22
+ out = ""
23
+ i = 0
24
+ while i < len(p):
25
+ if p.startswith("**/", i):
26
+ out += "(?:.*/)?"
27
+ i += 3
28
+ elif p.startswith("**", i):
29
+ out += ".*"
30
+ i += 2
31
+ elif p[i] == "*":
32
+ out += "[^/]*"
33
+ i += 1
34
+ elif p[i] == "?":
35
+ out += "[^/]"
36
+ i += 1
37
+ else:
38
+ out += re.escape(p[i])
39
+ i += 1
40
+ prefix = "" if anchored else "(?:.*/)?"
41
+ suffix = "/.*" if folder else "(?:/.*)?"
42
+ return re.compile(f"^{prefix}{out}{suffix}$")
43
+
44
+
45
+ class Owners:
46
+ def __init__(self, rules: list[tuple[re.Pattern, list[str]]], source: str):
47
+ self.rules, self.source = rules, source
48
+
49
+ def of(self, file: str) -> list[str]:
50
+ return self._of(file.replace("\\", "/"))
51
+
52
+ @lru_cache(maxsize=65536) # noqa: B019 (one Owners per run; files repeat across findings)
53
+ def _of(self, file: str) -> list[str]:
54
+ for regex, owners in reversed(self.rules):
55
+ if regex.match(file):
56
+ return owners
57
+ return []
58
+
59
+
60
+ def load(root: Path) -> Owners | None:
61
+ for loc in LOCATIONS:
62
+ path = root / loc
63
+ if path.is_file():
64
+ rules = []
65
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
66
+ line = line.split("#", 1)[0].strip()
67
+ if not line or line.startswith("["): # comments; GitLab sections
68
+ continue
69
+ pattern, *owners = line.split()
70
+ rules.append((_regex(pattern), owners))
71
+ return Owners(rules, loc)
72
+ return None
codefactory/patch.py ADDED
@@ -0,0 +1,81 @@
1
+ """`codefactory diff --patch FILE`: check the lines a unified diff adds, without the repository.
2
+
3
+ For a patch from a pull request (`gh pr diff 42 > pr.diff`, `git diff main > change.diff`), a mailing-list patch, or
4
+ an AI agent's proposed change: every line check (credentials, SQL built from strings, shell, eval, raw HTML, weak
5
+ crypto, personal data in logs, Swift crashes, and the shell, YAML, HTML and config checks) runs on the added lines.
6
+ Graph findings (loops, copies, unused code) need the whole repository, so they're left to `codefactory diff --base`.
7
+
8
+ The added lines are written to a temporary folder at their real line numbers, so each finding points at the line in
9
+ the new file.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import tempfile
16
+ from pathlib import Path
17
+
18
+ from .diff import Item
19
+
20
+ HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")
21
+
22
+
23
+ def added_lines(text: str) -> dict[str, dict[int, str]]:
24
+ """file -> {line number in the new file: text} for every added line."""
25
+ out: dict[str, dict[int, str]] = {}
26
+ file, line = None, 0
27
+ for raw in text.splitlines():
28
+ if raw.startswith("+++ "):
29
+ name = raw[4:].strip().split("\t")[0]
30
+ file = None if name == "/dev/null" else re.sub(r"^[ab]/", "", name)
31
+ if file:
32
+ out.setdefault(file, {})
33
+ elif raw.startswith("--- ") or raw.startswith("diff ") or raw.startswith("index "):
34
+ continue
35
+ elif m := HUNK.match(raw):
36
+ line = int(m.group(1))
37
+ elif file is None:
38
+ continue
39
+ elif raw.startswith("+"):
40
+ out[file][line] = raw[1:]
41
+ line += 1
42
+ elif raw.startswith(" ") or raw == "":
43
+ line += 1
44
+ # "-" lines are gone from the new file; "\ No newline" is a marker
45
+ return {f: lines for f, lines in out.items() if lines}
46
+
47
+
48
+ def check(text: str) -> dict:
49
+ from .apple import scan as apple_scan
50
+ from .checks import _scan
51
+ from .infra import scan as infra_scan
52
+ from .privacy import scan as privacy_scan
53
+ from .sarif import RULES
54
+
55
+ added = added_lines(text)
56
+ with tempfile.TemporaryDirectory() as d:
57
+ root = Path(d)
58
+ for file, lines in added.items():
59
+ path = root / file
60
+ if not path.resolve().is_relative_to(root.resolve()):
61
+ continue # a path that climbs out of the folder
62
+ path.parent.mkdir(parents=True, exist_ok=True)
63
+ body = [lines.get(n, "") for n in range(1, max(lines) + 1)]
64
+ path.write_text("\n".join(body) + "\n", encoding="utf-8")
65
+ files = sorted(added)
66
+ checks = _scan(root, files)
67
+ checks.update(privacy_scan(root, files))
68
+ checks.update(apple_scan(root, files))
69
+ checks.update(infra_scan(root))
70
+ items = []
71
+ for kind, c in checks.items():
72
+ if kind not in RULES:
73
+ continue
74
+ for e in c.hits:
75
+ if e.line in added.get(e.file, {}):
76
+ items.append(Item(f"{kind}|{e.file}|{e.text}", kind, RULES[kind][3], e.file, e.line, "",
77
+ f"{RULES[kind][1]}: {e.text}")) # fmt: skip
78
+ rank = {"high": 0, "warn": 1, "info": 2}
79
+ items.sort(key=lambda i: (rank.get(i.severity, 3), i.file, i.line))
80
+ return {"base": "the patch", "changed": files, "new": items, "fixed": [], "patch": True,
81
+ "added": sum(len(v) for v in added.values())} # fmt: skip
codefactory/paths.py ADDED
@@ -0,0 +1,93 @@
1
+ """What kind of file a path is. One definition, used by every check, so they all agree on what's a test."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import re
7
+
8
+ TEST_DIRS = ("tests", "test", "testing", "__tests__", "__mocks__", "spec")
9
+ SCRIPT_DIRS = ("scripts", "script", "tools", "bin")
10
+
11
+
12
+ def ignored(path: str, ignore: list[str]) -> bool:
13
+ """In a folder factory.toml's `ignore` names (fixtures, vendor…): left out of every check, like the analyzers do."""
14
+ return bool(set(path.replace("\\", "/").split("/")[:-1]) & set(ignore))
15
+
16
+
17
+ def drop_ignored(checks: dict, root) -> dict:
18
+ """Remove evidence in ignored folders from a {key: Check} result."""
19
+ from .config import load_config
20
+
21
+ ignore = load_config(root).ignore
22
+ if ignore:
23
+ for c in checks.values():
24
+ c.hits = [e for e in c.hits if not ignored(e.file, ignore)]
25
+ return checks
26
+
27
+
28
+ # folders no check needs to look inside: dependencies, environments, build output, caches
29
+ NOT_SOURCE = frozenset({".git", ".hg", ".svn", "node_modules", ".venv", "venv", "env", "__pycache__", ".codefactory",
30
+ "site-packages", "dist", "build", "Pods", ".expo", ".next", ".nuxt", ".gradle", "DerivedData",
31
+ "coverage", ".tox", ".mypy_cache", ".pytest_cache", ".ruff_cache", "bower_components"}) # fmt: skip
32
+
33
+
34
+ def walk(root, names: tuple[str, ...] = (), suffixes: tuple[str, ...] = (), skip=NOT_SOURCE, hidden: bool = True):
35
+ """Relative paths (posix) of the files under `root` with one of these names or suffixes (all files if neither),
36
+ pruning `skip` folders (and hidden ones unless `hidden`) before descending: `Path.rglob` walks all of
37
+ node_modules first and filters after, which on a JavaScript project is most of the time spent."""
38
+ import os
39
+
40
+ root = str(root)
41
+ for dirpath, dirnames, filenames in os.walk(root):
42
+ dirnames[:] = [d for d in dirnames if d not in skip and (hidden or not d.startswith("."))]
43
+ rel_dir = os.path.relpath(dirpath, root).replace("\\", "/")
44
+ for name in filenames:
45
+ if (names or suffixes) and name not in names and not name.endswith(suffixes):
46
+ continue
47
+ yield name if rel_dir == "." else f"{rel_dir}/{name}"
48
+
49
+
50
+ @functools.lru_cache(maxsize=65536)
51
+ def is_test(path: str) -> bool:
52
+ """tests/…, __tests__/…, test_*.py, *_test.py, *.test.ts, *.spec.js…"""
53
+ parts = path.replace("\\", "/").split("/")
54
+ name = parts[-1]
55
+ return (
56
+ any(p in TEST_DIRS for p in parts[:-1])
57
+ or name.startswith("test_")
58
+ or name.endswith("_test.py")
59
+ or ".test." in name
60
+ or ".spec." in name
61
+ or TEST_NAME.search(name) is not None
62
+ )
63
+
64
+
65
+ # Other languages' conventions: Go's x_test.go, Ruby's x_spec.rb, Java/Kotlin/C#/Swift/Scala's FooTest(s).java
66
+ TEST_NAME = re.compile(r"_(?:test|spec|tests)\.\w+$|[a-z0-9]Tests?\.(?:java|kt|cs|swift|scala|groovy|php|m)$")
67
+
68
+
69
+ def is_script(path: str) -> bool:
70
+ """One-off tooling (scripts/, tools/, bin/ at the top): matters less than the product's code."""
71
+ return path.replace("\\", "/").split("/")[0] in SCRIPT_DIRS
72
+
73
+
74
+ # Platform and architecture tags in file names (Go's file_linux_amd64.go, C's io_win32.c, Python's _posix.py).
75
+ PLATFORM = re.compile(
76
+ r"[._-](?:linux|darwin|windows|win32|win64|nt|posix|unix|bsd|freebsd|netbsd|openbsd|dragonfly|solaris|illumos|aix|"
77
+ r"plan9|android|ios|macos|osx|wasm|wasip1|js|zos|hurd|amd64|x86_64|x64|386|x86|i386|arm|arm64|aarch64|armv7|"
78
+ r"mips|mipsle|mips64|mips64le|ppc|ppc64|ppc64le|riscv|riscv64|s390x|loong64|sparc64|generic|noasm|purego|asm|"
79
+ r"cgo|nocgo|other|fallback|stub|stubs|default)(?=[._-]|$)",
80
+ re.I,
81
+ )
82
+
83
+
84
+ def platform_variants(a: str, b: str) -> bool:
85
+ """Two files that are the same file for different platforms (their copies are on purpose)."""
86
+ if a == b:
87
+ return False
88
+ da, _, na = a.rpartition("/")
89
+ db, _, nb = b.rpartition("/")
90
+ if da != db:
91
+ return False
92
+ sa, sb = PLATFORM.sub("", na.rsplit(".", 1)[0]), PLATFORM.sub("", nb.rsplit(".", 1)[0])
93
+ return sa == sb and (sa != na.rsplit(".", 1)[0] or sb != nb.rsplit(".", 1)[0])