codefactory-cli 0.20.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codefactory/__init__.py +3 -0
- codefactory/__main__.py +5 -0
- codefactory/accept.py +68 -0
- codefactory/analyzers/__init__.py +55 -0
- codefactory/analyzers/generic.py +392 -0
- codefactory/analyzers/parallel.py +113 -0
- codefactory/analyzers/python.py +279 -0
- codefactory/analyzers/python_parse.py +402 -0
- codefactory/analyzers/treewalk.py +299 -0
- codefactory/analyzers/ts_helper.js +483 -0
- codefactory/analyzers/typescript.py +118 -0
- codefactory/apple.py +80 -0
- codefactory/audit.py +227 -0
- codefactory/baseline.py +58 -0
- codefactory/brief.py +330 -0
- codefactory/cache.py +93 -0
- codefactory/checks.py +608 -0
- codefactory/cli.py +782 -0
- codefactory/config.py +157 -0
- codefactory/coverage.py +104 -0
- codefactory/deps.py +182 -0
- codefactory/diff.py +197 -0
- codefactory/efficiency.py +250 -0
- codefactory/flags.py +263 -0
- codefactory/graph.py +95 -0
- codefactory/hotspots.py +344 -0
- codefactory/infra.py +242 -0
- codefactory/intent.py +106 -0
- codefactory/layers.py +143 -0
- codefactory/org.py +131 -0
- codefactory/owners.py +72 -0
- codefactory/patch.py +81 -0
- codefactory/paths.py +93 -0
- codefactory/plan.py +476 -0
- codefactory/privacy.py +221 -0
- codefactory/profile.py +667 -0
- codefactory/rerank.py +161 -0
- codefactory/review.py +1504 -0
- codefactory/rules.py +50 -0
- codefactory/sarif.py +661 -0
- codefactory/sbom.py +78 -0
- codefactory/security.py +537 -0
- codefactory/similar.py +199 -0
- codefactory/skill.py +144 -0
- codefactory/skill_template/SKILL.md +68 -0
- codefactory/skill_template/__init__.py +0 -0
- codefactory/sqlgraph.py +109 -0
- codefactory/suppress.py +92 -0
- codefactory/taint.py +439 -0
- codefactory/trace.py +72 -0
- codefactory/viewer/__init__.py +19 -0
- codefactory/viewer/dashboard.html +43 -0
- codefactory/viewer/factory.css +61 -0
- codefactory/viewer/factory.js +665 -0
- codefactory/viewer/template.html +47 -0
- codefactory_cli-0.20.1.dist-info/METADATA +250 -0
- codefactory_cli-0.20.1.dist-info/RECORD +61 -0
- codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
- codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
- codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
- codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/apple.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Swift checks that matter on Apple platforms: crashes waiting to happen, retain cycles, work on the main thread,
|
|
2
|
+
and weakened code-signing entitlements.
|
|
3
|
+
|
|
4
|
+
All are line patterns with a little structure (a brace-matched block for "inside viewDidLoad" or "inside a closure"),
|
|
5
|
+
so they're leads with the exact line, ranked Low to Medium.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .checks import Check, Evidence
|
|
14
|
+
from .paths import drop_ignored, is_test, walk
|
|
15
|
+
|
|
16
|
+
FORCE = re.compile(r"\btry!|\bas!\s")
|
|
17
|
+
STORED_CLOSURE = re.compile(
|
|
18
|
+
r"\.sink\s*\{|\.sink\s*\(|\.subscribe\s*\{|addObserver\(forName:[^)]*\)\s*\{|scheduledTimer\([^)]*repeats:\s*true[^)]*\)\s*\{|"
|
|
19
|
+
r"\bself\.\w+\s*=\s*\{|\.observe\([^)]*\)\s*\{"
|
|
20
|
+
)
|
|
21
|
+
WEAK = re.compile(r"\[\s*(?:weak|unowned)\s+self\s*\]")
|
|
22
|
+
MAIN_SCOPE = re.compile(
|
|
23
|
+
r"func\s+(?:viewDidLoad|viewWillAppear|viewDidAppear|viewWillLayoutSubviews|layoutSubviews|draw)\s*\(|"
|
|
24
|
+
r"var\s+body\s*:\s*some\s+View"
|
|
25
|
+
)
|
|
26
|
+
SYNC_IO = re.compile(
|
|
27
|
+
r"Data\(contentsOf:|String\(contentsOf:|NSData\(contentsOf|FileManager\.default\.(?:contents|contentsOfDirectory|copyItem|"
|
|
28
|
+
r"moveItem|removeItem)|\.write\(to:|sqlite3_(?:exec|step|prepare)|try\s+\w+\.write\(|NSString\(contentsOf"
|
|
29
|
+
)
|
|
30
|
+
WEAK_ENTITLEMENTS = re.compile(
|
|
31
|
+
r"<key>(com\.apple\.security\.cs\.(?:disable-library-validation|allow-unsigned-executable-memory|allow-dyld-environment-variables|"
|
|
32
|
+
r"disable-executable-page-protection)|com\.apple\.security\.get-task-allow)</key>\s*<true\s*/>"
|
|
33
|
+
)
|
|
34
|
+
KEYS = ("swift_force", "swift_retain_cycle", "main_thread_io", "entitlement_weakened")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _block(lines: list[str], start: int) -> tuple[int, int]:
|
|
38
|
+
"""(first, last) line index of the brace block opening on line `start`."""
|
|
39
|
+
depth, opened = 0, False
|
|
40
|
+
for i in range(start, min(len(lines), start + 400)):
|
|
41
|
+
for ch in lines[i]:
|
|
42
|
+
if ch == "{":
|
|
43
|
+
depth += 1
|
|
44
|
+
opened = True
|
|
45
|
+
elif ch == "}":
|
|
46
|
+
depth -= 1
|
|
47
|
+
if opened and depth <= 0:
|
|
48
|
+
return start, i
|
|
49
|
+
return start, min(len(lines) - 1, start + 400)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def scan(root: Path, files: list[str]) -> dict[str, Check]:
|
|
53
|
+
out = {k: Check(k) for k in KEYS}
|
|
54
|
+
for fid in files:
|
|
55
|
+
if not fid.endswith(".swift") or is_test(fid):
|
|
56
|
+
continue
|
|
57
|
+
try:
|
|
58
|
+
lines = (root / fid).read_text(encoding="utf-8", errors="replace").splitlines()
|
|
59
|
+
except OSError:
|
|
60
|
+
continue
|
|
61
|
+
code = [re.sub(r"//.*$", "", ln) for ln in lines]
|
|
62
|
+
for i, ln in enumerate(code):
|
|
63
|
+
if FORCE.search(ln):
|
|
64
|
+
out["swift_force"].hits.append(Evidence(fid, i + 1, lines[i].strip()[:140]))
|
|
65
|
+
if STORED_CLOSURE.search(ln) and not WEAK.search(ln):
|
|
66
|
+
first, last = _block(code, i)
|
|
67
|
+
body = "\n".join(code[first : last + 1])
|
|
68
|
+
if re.search(r"\bself\.", body) and not WEAK.search(body):
|
|
69
|
+
out["swift_retain_cycle"].hits.append(Evidence(fid, i + 1, lines[i].strip()[:140]))
|
|
70
|
+
if MAIN_SCOPE.search(ln):
|
|
71
|
+
first, last = _block(code, i)
|
|
72
|
+
for j in range(first, last + 1):
|
|
73
|
+
if SYNC_IO.search(code[j]) and "Task {" not in code[j] and "async" not in code[j]:
|
|
74
|
+
out["main_thread_io"].hits.append(Evidence(fid, j + 1, lines[j].strip()[:140]))
|
|
75
|
+
for path in sorted(root / rel for rel in walk(root, suffixes=(".entitlements",))):
|
|
76
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
77
|
+
for m in WEAK_ENTITLEMENTS.finditer(text):
|
|
78
|
+
rel = path.relative_to(root).as_posix()
|
|
79
|
+
out["entitlement_weakened"].hits.append(Evidence(rel, text.count("\n", 0, m.start()) + 1, m.group(1)))
|
|
80
|
+
return drop_ignored(out, root)
|
codefactory/audit.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
# codefactory: ignore-file secret, eval, shell — the patterns themselves
|
|
2
|
+
"""Security checks on what surrounds the code: CI workflows, Dockerfiles, mobile app configuration, and secrets that
|
|
3
|
+
were committed once and deleted later (still in git history, so still leaked).
|
|
4
|
+
|
|
5
|
+
Each returns Evidence (file, line, text) under a check key, like checks.scan_sources, so the review, SARIF and
|
|
6
|
+
`codefactory accept` treat them the same way.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
import subprocess
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from .checks import ANY, PATTERNS, PLACEHOLDER, VENDOR_SECRETS, Check, Evidence
|
|
16
|
+
from .paths import drop_ignored, is_test, walk
|
|
17
|
+
from .suppress import MARK
|
|
18
|
+
|
|
19
|
+
# GitHub Actions
|
|
20
|
+
PR_TARGET = re.compile(r"^(?!\s*#).*\bpull_request_target\b", re.M) # also `on: pull_request_target`, `on: [push, …]`
|
|
21
|
+
# checking out the PR's code: a checkout's `ref:` set to the head, or a command that fetches it. The head sha used
|
|
22
|
+
# elsewhere (an env var for looking up artifacts) is just a string.
|
|
23
|
+
HEAD_CHECKOUT = re.compile(
|
|
24
|
+
r"^\s*ref:\s*\$\{\{\s*(?:github\.event\.pull_request\.head\.(?:sha|ref)|github\.head_ref)|gh pr checkout|"
|
|
25
|
+
r"git (?:fetch|checkout)[^\n]*(?:refs/pull/|pull_request\.head|head_ref)",
|
|
26
|
+
re.M,
|
|
27
|
+
)
|
|
28
|
+
SCRIPT_KEY = re.compile(r"^(\s*)(?:-\s+)?(run|script):\s*(.*)$")
|
|
29
|
+
UNTRUSTED = re.compile(
|
|
30
|
+
r"\$\{\{\s*github\.(?:event\.(?:issue|pull_request|comment|review|review_comment|discussion|head_commit|commits|pages)"
|
|
31
|
+
r"[\w.\[\]*]*\.(?:title|body|head_ref|label|message|name|email|ref)|head_ref)\s*\}\}"
|
|
32
|
+
)
|
|
33
|
+
USES = re.compile(r"^\s*-?\s*uses:\s*([\w.-]+/[\w./-]+)@([\w.-]+)", re.M)
|
|
34
|
+
FIRST_PARTY = ("actions/", "github/")
|
|
35
|
+
VENDORED = re.compile(r"(?:^|/)(?:\.yarn|vendor|node_modules|dist|build|third_party|bower_components)/|\.min\.(?:js|css)$")
|
|
36
|
+
# Dockerfiles
|
|
37
|
+
FROM = re.compile(r"^[ \t]*FROM\s+(\S+)", re.I | re.M) # [ \t], not \s: \s would start on a blank line above
|
|
38
|
+
USER = re.compile(r"^[ \t]*USER\s+(\S+)", re.I | re.M)
|
|
39
|
+
ENV_SECRET = re.compile(
|
|
40
|
+
r"^[ \t]*(?:ENV|ARG)\s+\w*(?:SECRET|PASSWORD|PASSWD|TOKEN|API_?KEY|PRIVATE_KEY)\w*[= ]\s*\S+", re.I | re.M
|
|
41
|
+
)
|
|
42
|
+
# Mobile
|
|
43
|
+
ATS = re.compile(r"NSAllowsArbitraryLoads[\"']?\s*(?::\s*true|</key>\s*<true\s*/>)", re.I)
|
|
44
|
+
CLEARTEXT = re.compile(r"usesCleartextTraffic\s*[=:]\s*[\"']?true", re.I)
|
|
45
|
+
|
|
46
|
+
KEYS = ("gha_pr_target", "gha_injection", "gha_unpinned", "docker_root", "docker_secret", "docker_latest",
|
|
47
|
+
"mobile_cleartext", "history_secret") # fmt: skip
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _line(text: str, pos: int) -> int:
|
|
51
|
+
return text.count("\n", 0, pos) + 1
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _excerpt(text: str) -> str:
|
|
55
|
+
t = text.strip()
|
|
56
|
+
return t if len(t) <= 140 else t[:137] + "…"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def workflows(root: Path, out: dict[str, Check]) -> None:
|
|
60
|
+
for path in sorted((root / ".github" / "workflows").glob("*.y*ml")):
|
|
61
|
+
rel = path.relative_to(root).as_posix()
|
|
62
|
+
try:
|
|
63
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
64
|
+
except OSError:
|
|
65
|
+
continue
|
|
66
|
+
lines = text.splitlines()
|
|
67
|
+
if m := PR_TARGET.search(text):
|
|
68
|
+
# runs with the repository's secrets and write access, on code from a fork: dangerous only if it checks
|
|
69
|
+
# that code out (or builds it); otherwise it's the safe way to label or comment on a PR
|
|
70
|
+
danger = HEAD_CHECKOUT.search(text)
|
|
71
|
+
out["gha_pr_target"].hits.append(
|
|
72
|
+
Evidence(rel, _line(text, m.start()), "pull_request_target" + (" + checks out the PR's code" if danger else ""))
|
|
73
|
+
)
|
|
74
|
+
out["gha_pr_target"].data[rel] = "checkout" if danger else "trigger"
|
|
75
|
+
for i in _script_lines(lines): # only text a shell (run:) or github-script (script:) executes
|
|
76
|
+
if UNTRUSTED.search(lines[i - 1]) and not lines[i - 1].strip().startswith("#"):
|
|
77
|
+
out["gha_injection"].hits.append(Evidence(rel, i, _excerpt(lines[i - 1])))
|
|
78
|
+
for m in USES.finditer(text):
|
|
79
|
+
action, ref = m.group(1), m.group(2)
|
|
80
|
+
if not action.startswith(FIRST_PARTY) and not re.fullmatch(r"[0-9a-f]{40}", ref):
|
|
81
|
+
out["gha_unpinned"].hits.append(Evidence(rel, _line(text, m.start()), f"{action}@{ref}"))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _script_lines(lines: list[str]) -> list[int]:
|
|
85
|
+
"""1-based numbers of the lines inside `run:` and `script:` values (inline or block)."""
|
|
86
|
+
out, block_indent = [], None
|
|
87
|
+
for i, ln in enumerate(lines, 1):
|
|
88
|
+
if block_indent is not None:
|
|
89
|
+
if not ln.strip() or len(ln) - len(ln.lstrip()) > block_indent:
|
|
90
|
+
out.append(i)
|
|
91
|
+
continue
|
|
92
|
+
block_indent = None
|
|
93
|
+
m = SCRIPT_KEY.match(ln)
|
|
94
|
+
if m:
|
|
95
|
+
if m.group(3).strip() in ("|", ">", "|-", ">-", "|+", ">+", ""):
|
|
96
|
+
block_indent = ln.find(m.group(2)) # the block is everything indented past the key itself
|
|
97
|
+
else:
|
|
98
|
+
out.append(i)
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def dockerfiles(root: Path, files: list[Path], out: dict[str, Check]) -> None:
|
|
103
|
+
for path in files:
|
|
104
|
+
rel = path.relative_to(root).as_posix()
|
|
105
|
+
try:
|
|
106
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
107
|
+
except OSError:
|
|
108
|
+
continue
|
|
109
|
+
froms = list(FROM.finditer(text))
|
|
110
|
+
if not froms:
|
|
111
|
+
continue
|
|
112
|
+
users = [u.group(1) for u in USER.finditer(text)]
|
|
113
|
+
if not users or users[-1] in ("root", "0", "0:0"):
|
|
114
|
+
out["docker_root"].hits.append(Evidence(rel, _line(text, froms[-1].start()), f"no USER after {froms[-1].group(1)}"))
|
|
115
|
+
for m in froms:
|
|
116
|
+
image = m.group(1)
|
|
117
|
+
if image.lower() == "scratch" or image.startswith("$") or "@sha256:" in image:
|
|
118
|
+
continue
|
|
119
|
+
tag = image.split("/")[-1].partition(":")[2]
|
|
120
|
+
if not tag or tag == "latest":
|
|
121
|
+
out["docker_latest"].hits.append(Evidence(rel, _line(text, m.start()), f"FROM {image}"))
|
|
122
|
+
for m in ENV_SECRET.finditer(text):
|
|
123
|
+
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))))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def mobile(root: Path, out: dict[str, Check]) -> None:
|
|
128
|
+
names = ("app.json", "app.config.json", "Info.plist", "AndroidManifest.xml")
|
|
129
|
+
found = (root / rel for rel in walk(root, names=names))
|
|
130
|
+
for path in sorted(found):
|
|
131
|
+
rel = path.relative_to(root).as_posix()
|
|
132
|
+
try:
|
|
133
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
134
|
+
except OSError:
|
|
135
|
+
continue
|
|
136
|
+
for pat in (ATS, CLEARTEXT):
|
|
137
|
+
if m := pat.search(text):
|
|
138
|
+
out["mobile_cleartext"].hits.append(Evidence(rel, _line(text, m.start()), _excerpt(m.group(0))))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _now(root: Path, file: str, texts: dict[str, str]) -> str:
|
|
142
|
+
"""The file's current text ("" if it's gone): a key still there isn't a deleted one, even when a
|
|
143
|
+
`codefactory: ignore` comment keeps the current-files check quiet about it."""
|
|
144
|
+
if file not in texts:
|
|
145
|
+
try:
|
|
146
|
+
texts[file] = (root / file).read_text(encoding="utf-8", errors="replace")
|
|
147
|
+
except OSError:
|
|
148
|
+
texts[file] = ""
|
|
149
|
+
return texts[file]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def history(root: Path, current: set[str], out: dict[str, Check], max_lines: int = 400_000, timeout: int = 60) -> str:
|
|
153
|
+
"""Secrets added in any commit (and branch) that aren't in the current files: deleted, but still leaked. Returns a
|
|
154
|
+
note on how much history was read ("" when everything was)."""
|
|
155
|
+
inside = subprocess.run(["git", "-C", str(root), "rev-parse", "--is-inside-work-tree"], capture_output=True, text=True)
|
|
156
|
+
if inside.stdout.strip() != "true": # (a monorepo's subfolder has no .git of its own, but is in a repository)
|
|
157
|
+
return "not a git repository: history not checked"
|
|
158
|
+
try:
|
|
159
|
+
proc = subprocess.Popen(
|
|
160
|
+
["git", "-C", str(root), "log", "--all", "-p", "--no-color", "--no-ext-diff", "-U0", "--format=@@commit %h %as",
|
|
161
|
+
"--relative", "--", "."], # this folder only, paths relative to it (a monorepo package)
|
|
162
|
+
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace",
|
|
163
|
+
) # fmt: skip
|
|
164
|
+
except OSError:
|
|
165
|
+
return "git isn't available: history not checked"
|
|
166
|
+
commit, file, seen, read, note = "", "", set(), 0, ""
|
|
167
|
+
texts: dict[str, str] = {}
|
|
168
|
+
pats = PATTERNS["secret"]
|
|
169
|
+
try:
|
|
170
|
+
for raw in proc.stdout:
|
|
171
|
+
read += 1
|
|
172
|
+
if read > max_lines:
|
|
173
|
+
note = f"history read up to {max_lines:,} changed lines (the most recent commits)"
|
|
174
|
+
break
|
|
175
|
+
if raw.startswith("@@commit "):
|
|
176
|
+
commit = raw[9:].strip()
|
|
177
|
+
elif raw.startswith("+++ "):
|
|
178
|
+
file = raw[6:].strip() if raw.startswith("+++ b/") else ""
|
|
179
|
+
elif raw.startswith("+") and not raw.startswith("+++") and file:
|
|
180
|
+
line = raw[1:]
|
|
181
|
+
if len(line) > 500 or VENDORED.search(file):
|
|
182
|
+
continue # minified or vendored code (a bundled yarn release, dist/, vendor/): not anyone's key
|
|
183
|
+
if not ANY["secret"].search(line):
|
|
184
|
+
continue # one search rules out almost every line
|
|
185
|
+
use = VENDOR_SECRETS if is_test(file) else pats # test fixtures: only real credential formats
|
|
186
|
+
if any(p.search(line) for p in use):
|
|
187
|
+
value = next(m.group(0) for p in use if (m := p.search(line)))
|
|
188
|
+
if re.search(PLACEHOLDER, line) or MARK.search(line):
|
|
189
|
+
continue # (a `codefactory: ignore` comment on it said it isn't real)
|
|
190
|
+
if value in current or (file, value) in seen or value in _now(root, file, texts):
|
|
191
|
+
continue # still in the code: the current-files check reports it (or it was marked as intended)
|
|
192
|
+
seen.add((file, value))
|
|
193
|
+
out["history_secret"].hits.append(Evidence(file, 0, f"commit {commit}: {_excerpt(line)}"))
|
|
194
|
+
finally:
|
|
195
|
+
proc.kill()
|
|
196
|
+
proc.stdout.close()
|
|
197
|
+
proc.wait(timeout=timeout)
|
|
198
|
+
shallow = subprocess.run(["git", "-C", str(root), "rev-parse", "--is-shallow-repository"], capture_output=True, text=True)
|
|
199
|
+
if shallow.stdout.strip() == "true":
|
|
200
|
+
note = (note + "; " if note else "") + "shallow clone: only part of the history was available"
|
|
201
|
+
return note
|
|
202
|
+
|
|
203
|
+
|
|
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
|
+
return {m.group(0) for e in secret_check.hits for p in PATTERNS["secret"] if (m := p.search(e.text))}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def find_dockerfiles(root: Path) -> list[Path]:
|
|
210
|
+
return sorted(
|
|
211
|
+
root / rel for rel in walk(root) if re.fullmatch(r"(?i)dockerfile(\..+)?|.+\.dockerfile", rel.rsplit("/", 1)[-1])
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def scan_config(root: Path) -> dict[str, Check]:
|
|
216
|
+
"""Everything here but git history (which is the same on both sides of a diff)."""
|
|
217
|
+
out = {k: Check(k) for k in KEYS}
|
|
218
|
+
workflows(root, out)
|
|
219
|
+
dockerfiles(root, find_dockerfiles(root), out)
|
|
220
|
+
mobile(root, out)
|
|
221
|
+
return drop_ignored(out, root)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def scan(root: Path, current_secrets: set[str]) -> tuple[dict[str, Check], str]:
|
|
225
|
+
out = scan_config(root)
|
|
226
|
+
note = history(root, current_secrets, out)
|
|
227
|
+
return drop_ignored(out, root), note
|
codefactory/baseline.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""The ratchet: save today's issues as a baseline (commit it), then fail only on issues that weren't there. The backlog
|
|
2
|
+
can be worked down at any pace; nothing new slips in.
|
|
3
|
+
|
|
4
|
+
An issue's identity is its kind, file and function (not its line, which moves as code above it changes), counted:
|
|
5
|
+
two io_in_loop issues in one function stay two.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from datetime import date
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
NAME = "codefactory-baseline.json"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def issue_key(graph: dict, flag: dict, fns: dict | None = None) -> str:
|
|
19
|
+
fns = fns if fns is not None else {f["id"]: f for f in graph["functions"]}
|
|
20
|
+
fn = fns.get(flag["target"])
|
|
21
|
+
where = f"{fn['file']}::{fn['qualname']}" if fn else flag["target"]
|
|
22
|
+
return f"{flag['kind']}|{where}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def baseline_path(repo_or_file: Path) -> Path:
|
|
26
|
+
return repo_or_file / NAME if repo_or_file.is_dir() else repo_or_file
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def write_baseline(graph: dict, path: Path) -> int:
|
|
30
|
+
fns = {f["id"]: f for f in graph["functions"]}
|
|
31
|
+
counts = Counter(issue_key(graph, f, fns) for f in graph["flags"])
|
|
32
|
+
path.write_text(
|
|
33
|
+
json.dumps({"version": 1, "created": date.today().isoformat(), "issues": dict(sorted(counts.items()))}, indent=1) + "\n",
|
|
34
|
+
encoding="utf-8",
|
|
35
|
+
)
|
|
36
|
+
return sum(counts.values())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def read_baseline(path: Path) -> Counter | None:
|
|
40
|
+
try:
|
|
41
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
42
|
+
except (OSError, ValueError):
|
|
43
|
+
return None
|
|
44
|
+
return Counter(data.get("issues", {}))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def compare(graph: dict, base: Counter) -> tuple[list[dict], Counter]:
|
|
48
|
+
"""(issues not in the baseline, baseline issues no longer found)."""
|
|
49
|
+
fns = {f["id"]: f for f in graph["functions"]}
|
|
50
|
+
left = Counter(base)
|
|
51
|
+
new = []
|
|
52
|
+
for f in graph["flags"]:
|
|
53
|
+
k = issue_key(graph, f, fns)
|
|
54
|
+
if left[k] > 0:
|
|
55
|
+
left[k] -= 1
|
|
56
|
+
else:
|
|
57
|
+
new.append(f)
|
|
58
|
+
return new, +left
|