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
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Efficiency checks, from what the analyzers record inside functions (Site) and the call graph.
|
|
2
|
+
|
|
3
|
+
- io_in_loop: a database, file or network call, or a call to one of the codebase's own functions that eventually
|
|
4
|
+
makes one, runs once per loop iteration (the N+1 pattern: one query per item instead of one query for all).
|
|
5
|
+
- sequential_await: awaits inside a for/while loop wait for each round in turn; independent ones can run together.
|
|
6
|
+
- quadratic_scan: searching an array (find, filter, includes, indexOf…) inside a loop over items: O(n²) as data grows.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from collections import defaultdict, deque
|
|
13
|
+
|
|
14
|
+
from .graph import Flag, Graph
|
|
15
|
+
from .paths import is_test
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def io_reach(g: Graph) -> dict[str, tuple[str, str]]:
|
|
19
|
+
"""Function id -> (next function on the way, the I/O call it reaches), for every function that does I/O itself
|
|
20
|
+
or through the functions it calls. A function doing it itself has next = itself."""
|
|
21
|
+
callers = defaultdict(list)
|
|
22
|
+
for e in g.edges:
|
|
23
|
+
if e.kind == "call":
|
|
24
|
+
callers[e.dst].append(e.src)
|
|
25
|
+
reach: dict[str, tuple[str, str]] = {}
|
|
26
|
+
q = deque()
|
|
27
|
+
for f in g.functions:
|
|
28
|
+
if f.io and f.kind != "module":
|
|
29
|
+
reach[f.id] = (f.id, f.io[0])
|
|
30
|
+
q.append(f.id)
|
|
31
|
+
while q:
|
|
32
|
+
cur = q.popleft()
|
|
33
|
+
for c in callers[cur]:
|
|
34
|
+
if c not in reach:
|
|
35
|
+
reach[c] = (cur, reach[cur][1])
|
|
36
|
+
q.append(c)
|
|
37
|
+
return reach
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _path_names(start: str, reach: dict, by_id: dict) -> list[str]:
|
|
41
|
+
"""The names of the functions from `start` to the one doing the I/O."""
|
|
42
|
+
names, cur, seen = [], start, set()
|
|
43
|
+
while cur in by_id and cur not in seen:
|
|
44
|
+
seen.add(cur)
|
|
45
|
+
names.append(by_id[cur].name)
|
|
46
|
+
nxt = reach.get(cur, (cur,))[0]
|
|
47
|
+
if nxt == cur:
|
|
48
|
+
break
|
|
49
|
+
cur = nxt
|
|
50
|
+
return names
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _name(fn) -> str:
|
|
54
|
+
return f"top-level code in {fn.file.split('/')[-1]}" if fn.kind == "module" else fn.qualname
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
NETWORK = re.compile(r"(^|\.)(fetch|urlopen)$|axios|requests\.|httpx|aiohttp|http|supabase|firestore", re.I)
|
|
58
|
+
READS = re.compile(
|
|
59
|
+
r"getAll|getFirst|getEach|fetchone|fetchall|fetchmany|(^|\.)(query|select|find\w*|get|getItem\w*|"
|
|
60
|
+
r"read\w*|scalars?|from)$|objects\.(get|filter|all)|\(.SELECT",
|
|
61
|
+
re.I,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
FILES = re.compile(
|
|
66
|
+
r"readFile|writeFile|appendFile|readdir|(^|\.)stat(Sync)?$|read_text|write_text|read_bytes|"
|
|
67
|
+
r"write_bytes|AsStringAsync|downloadAsync|downloadFileAsync|uploadAsync|^open$|iterdir|r?glob$|shutil\.|"
|
|
68
|
+
r"(^|\.)(copy2?|copyfile|copytree|move|rename|replace|unlink|remove|rmtree|mkdir|makedirs|rmdir|touch|"
|
|
69
|
+
r"copyFile|copyAsync|moveAsync|deleteAsync|makeDirectoryAsync)$",
|
|
70
|
+
re.I,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
WAIT = re.compile(r"(^|\.)(sleep|wait|setTimeout|delay)$")
|
|
75
|
+
PROCESS = re.compile(r"subprocess\.|(^|\.)(system|popen|spawn|execSync|execFile|exec_command)$|child_process", re.I)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def called(x: str) -> str:
|
|
79
|
+
return x if x.endswith(")") else f"{x}()"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def kind_of(sink: str) -> str:
|
|
83
|
+
"""wait | process | network | file | read | write: how much a call in a loop costs. Network and database reads are
|
|
84
|
+
the classic N+1; files one by one are normal in scripts; writes one at a time are slower than a batch but usually
|
|
85
|
+
fine inside one transaction; a sleep in a loop is pacing on purpose."""
|
|
86
|
+
if WAIT.search(sink):
|
|
87
|
+
return "wait"
|
|
88
|
+
if PROCESS.search(sink):
|
|
89
|
+
return "process"
|
|
90
|
+
if NETWORK.search(sink):
|
|
91
|
+
return "network"
|
|
92
|
+
if FILES.search(sink):
|
|
93
|
+
return "file"
|
|
94
|
+
return "read" if READS.search(sink) else "write"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
WRITE_SQL = re.compile(r"INSERT|UPDATE|DELETE|REPLACE|UPSERT|commit|save|put|set|write|create|add|remove|delete", re.I)
|
|
98
|
+
READ_NAME = re.compile(r"^_?(read|get|load|fetch|list|find|count|select|query|lookup|latest|recent|stored)", re.I)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def kind_through(sink: str, path: list[str]) -> str:
|
|
102
|
+
"""kind_of, using the names of the functions on the way as a hint when the call itself doesn't say: a
|
|
103
|
+
`conn.execute(sql)` reached through `read_snapshots` is a read, not a write."""
|
|
104
|
+
kind = kind_of(sink)
|
|
105
|
+
if kind == "write" and not WRITE_SQL.search(sink) and any(READ_NAME.match(n) for n in path):
|
|
106
|
+
return "read"
|
|
107
|
+
return kind
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
TX_WRAPPER = re.compile(r"transaction|atomic|withTransaction|writeTxn", re.I)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def in_transaction(g: Graph) -> set[str]:
|
|
114
|
+
"""Functions that always run inside a transaction: every call to them is made inside a transaction block, or by a
|
|
115
|
+
function that itself always runs in one (route -> service -> repository), followed to a fixed point."""
|
|
116
|
+
tx_calls: dict[tuple[str, str], int] = defaultdict(int)
|
|
117
|
+
for s in g.sites:
|
|
118
|
+
if s.kind == "tx_call" or (s.kind == "loop_call" and s.tx):
|
|
119
|
+
tx_calls[(s.fn, s.target)] += 1
|
|
120
|
+
callers: dict[str, list[tuple[str, int]]] = defaultdict(list)
|
|
121
|
+
for e in g.edges:
|
|
122
|
+
if e.kind == "call":
|
|
123
|
+
callers[e.dst].append((e.src, e.count))
|
|
124
|
+
inside: set[str] = set()
|
|
125
|
+
changed = True
|
|
126
|
+
while changed: # each round can only add, so this ends; each added function is justified by the ones before it
|
|
127
|
+
changed = False
|
|
128
|
+
for dst, srcs in callers.items():
|
|
129
|
+
if dst not in inside and all(src in inside or tx_calls.get((src, dst), 0) >= n for src, n in srcs):
|
|
130
|
+
inside.add(dst)
|
|
131
|
+
changed = True
|
|
132
|
+
return inside
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def efficiency_flags(g: Graph) -> list[Flag]:
|
|
136
|
+
"""Test files are left out: a loop of setup calls in a test isn't a problem anyone ships."""
|
|
137
|
+
by_id = {f.id: f for f in g.functions}
|
|
138
|
+
reach = io_reach(g)
|
|
139
|
+
out: list[Flag] = []
|
|
140
|
+
loop_io: dict[tuple[str, str], list[int]] = defaultdict(list) # (fn, what) -> lines
|
|
141
|
+
unbounded: set[tuple[str, str]] = set() # (fn, what) with at least one loop whose length depends on data
|
|
142
|
+
outside_tx: set[tuple[str, str]] = set() # (fn, what) with at least one call not inside a transaction
|
|
143
|
+
awaits: dict[str, list[int]] = defaultdict(list)
|
|
144
|
+
always_tx = in_transaction(g)
|
|
145
|
+
for s in g.sites:
|
|
146
|
+
if s.fn not in by_id or is_test(by_id[s.fn].file):
|
|
147
|
+
continue
|
|
148
|
+
if s.kind in ("loop_io", "loop_call"):
|
|
149
|
+
key = (s.fn, s.detail if s.kind == "loop_io" else s.target)
|
|
150
|
+
if s.kind == "loop_call" and (
|
|
151
|
+
s.target not in reach or TX_WRAPPER.search(by_id[s.target].name if s.target in by_id else "")
|
|
152
|
+
):
|
|
153
|
+
continue # nothing to reach, or the transaction helper itself (calling it per batch is the batching)
|
|
154
|
+
loop_io[key].append(s.line)
|
|
155
|
+
if not s.bounded:
|
|
156
|
+
unbounded.add(key)
|
|
157
|
+
if not (s.tx or s.fn in always_tx):
|
|
158
|
+
outside_tx.add(key)
|
|
159
|
+
elif s.kind == "loop_await" and not s.bounded: # a few fixed rounds in turn cost nothing worth reporting
|
|
160
|
+
awaits[s.fn].append(s.line)
|
|
161
|
+
elif s.kind == "loop_scan" and not s.bounded:
|
|
162
|
+
fn = by_id.get(s.fn)
|
|
163
|
+
if fn:
|
|
164
|
+
out.append(
|
|
165
|
+
Flag(
|
|
166
|
+
"quadratic_scan",
|
|
167
|
+
"info",
|
|
168
|
+
s.fn,
|
|
169
|
+
f"{_name(fn)} calls {s.detail}() on every round of a "
|
|
170
|
+
f"loop (line {s.line}): fine for short lists, slow (O(n²)) for long ones. A Map or Set "
|
|
171
|
+
"built once before the loop makes each lookup instant.",
|
|
172
|
+
line=s.line,
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
advice = {
|
|
176
|
+
"network": "one network request per item. Send one request for all items, or run them together.",
|
|
177
|
+
"read": "one query per item (the N+1 pattern). Load them all with one query (WHERE id IN (…), a JOIN).",
|
|
178
|
+
"process": "one program run per item. Fine for a handful; for many, pass them all to one run if the "
|
|
179
|
+
"program accepts several.",
|
|
180
|
+
"file": "one file operation per item. Normal when each item is its own file; if it's the same file each "
|
|
181
|
+
"time, read it once before the loop.",
|
|
182
|
+
"write": "one write per item. Fine for a few inside one transaction; for many, batch them (one multi-row "
|
|
183
|
+
"INSERT/UPDATE) and make sure they share a transaction.",
|
|
184
|
+
}
|
|
185
|
+
explained: dict[str, set[int]] = defaultdict(set) # lines an await check would only repeat
|
|
186
|
+
for (fid, what), lines in loop_io.items():
|
|
187
|
+
fn = by_id.get(fid)
|
|
188
|
+
if not fn:
|
|
189
|
+
continue
|
|
190
|
+
explained[fid].update(lines)
|
|
191
|
+
where = f"line {lines[0]}" + (f" and {len(lines) - 1} more" if len(lines) > 1 else "")
|
|
192
|
+
sink = reach[what][1] if what in by_id else what
|
|
193
|
+
kind = kind_through(sink, _path_names(what, reach, by_id))
|
|
194
|
+
if kind == "wait":
|
|
195
|
+
continue # sleeping between rounds is pacing (rate limits, polling), chosen on purpose
|
|
196
|
+
if kind == "write" and (fid, what) not in outside_tx:
|
|
197
|
+
continue # writes batched inside one transaction: the advice would be to do what it already does
|
|
198
|
+
sev = "warn" if kind in ("network", "read") else "info"
|
|
199
|
+
fixed = (fid, what) not in unbounded
|
|
200
|
+
migration = "migration" in fn.file.lower() or "migrat" in fn.name.lower()
|
|
201
|
+
if fixed or migration: # can't grow with the data: worth knowing, not worth fixing
|
|
202
|
+
sev = "info"
|
|
203
|
+
note = (
|
|
204
|
+
" It loops over a list fixed in the code, so the number of calls can't grow with the data: fine as "
|
|
205
|
+
"is unless that list gets long."
|
|
206
|
+
if fixed
|
|
207
|
+
else " It's in a migration, which runs once per upgrade."
|
|
208
|
+
if migration
|
|
209
|
+
else ""
|
|
210
|
+
)
|
|
211
|
+
if what in by_id: # one of the codebase's functions that reaches I/O
|
|
212
|
+
out.append(
|
|
213
|
+
Flag(
|
|
214
|
+
"io_in_loop",
|
|
215
|
+
sev,
|
|
216
|
+
fid,
|
|
217
|
+
f"{_name(fn)} calls {by_id[what].qualname}() inside a loop ({where}), "
|
|
218
|
+
f"and that reaches {called(sink)}: {advice[kind]}{note}",
|
|
219
|
+
[what],
|
|
220
|
+
line=lines[0],
|
|
221
|
+
detail=kind + (":fixed" if fixed or migration else ""),
|
|
222
|
+
)
|
|
223
|
+
)
|
|
224
|
+
else:
|
|
225
|
+
out.append(
|
|
226
|
+
Flag(
|
|
227
|
+
"io_in_loop",
|
|
228
|
+
sev,
|
|
229
|
+
fid,
|
|
230
|
+
f"{_name(fn)} calls {called(what)} inside a loop ({where}): {advice[kind]}{note}",
|
|
231
|
+
line=lines[0],
|
|
232
|
+
detail=kind + (":fixed" if fixed or migration else ""),
|
|
233
|
+
)
|
|
234
|
+
)
|
|
235
|
+
for fid, all_lines in awaits.items():
|
|
236
|
+
fn = by_id.get(fid)
|
|
237
|
+
lines = [ln for ln in all_lines if ln not in explained[fid]]
|
|
238
|
+
if fn and lines:
|
|
239
|
+
out.append(
|
|
240
|
+
Flag(
|
|
241
|
+
"sequential_await",
|
|
242
|
+
"info",
|
|
243
|
+
fid,
|
|
244
|
+
f"{_name(fn)} awaits inside a loop (line "
|
|
245
|
+
f"{', '.join(map(str, lines[:5]))}): each round waits for the last. If they don't "
|
|
246
|
+
"depend on each other, start them together (Promise.all / asyncio.gather).",
|
|
247
|
+
line=lines[0],
|
|
248
|
+
)
|
|
249
|
+
)
|
|
250
|
+
return out
|
codefactory/flags.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Issue detectors. They read only the Graph, so they work the same for every language."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
|
|
8
|
+
from .config import Config
|
|
9
|
+
from .efficiency import efficiency_flags
|
|
10
|
+
from .graph import Flag, Graph
|
|
11
|
+
from .paths import is_test, platform_variants
|
|
12
|
+
from .similar import near_duplicates
|
|
13
|
+
|
|
14
|
+
SEVERITY_ORDER = {"high": 0, "warn": 1, "info": 2}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# Methods a framework calls by name: React class components, web components, Angular, Django / DRF class-based views.
|
|
18
|
+
FRAMEWORK_METHODS = {
|
|
19
|
+
"render",
|
|
20
|
+
"componentDidMount",
|
|
21
|
+
"componentDidUpdate",
|
|
22
|
+
"componentWillUnmount",
|
|
23
|
+
"shouldComponentUpdate",
|
|
24
|
+
"getSnapshotBeforeUpdate",
|
|
25
|
+
"componentDidCatch",
|
|
26
|
+
"getDerivedStateFromError",
|
|
27
|
+
"getDerivedStateFromProps",
|
|
28
|
+
"UNSAFE_componentWillMount",
|
|
29
|
+
"UNSAFE_componentWillReceiveProps",
|
|
30
|
+
"UNSAFE_componentWillUpdate",
|
|
31
|
+
"constructor",
|
|
32
|
+
"connectedCallback",
|
|
33
|
+
"disconnectedCallback",
|
|
34
|
+
"attributeChangedCallback",
|
|
35
|
+
"adoptedCallback",
|
|
36
|
+
"ngOnInit",
|
|
37
|
+
"ngOnDestroy",
|
|
38
|
+
"ngOnChanges",
|
|
39
|
+
"ngAfterViewInit",
|
|
40
|
+
"ngAfterContentInit",
|
|
41
|
+
"ngDoCheck",
|
|
42
|
+
"get",
|
|
43
|
+
"post",
|
|
44
|
+
"put",
|
|
45
|
+
"patch",
|
|
46
|
+
"delete",
|
|
47
|
+
"head",
|
|
48
|
+
"options",
|
|
49
|
+
"dispatch",
|
|
50
|
+
"get_queryset",
|
|
51
|
+
"get_object",
|
|
52
|
+
"get_context_data",
|
|
53
|
+
"get_serializer_class",
|
|
54
|
+
"perform_create",
|
|
55
|
+
"perform_update",
|
|
56
|
+
"perform_destroy",
|
|
57
|
+
"form_valid",
|
|
58
|
+
"form_invalid",
|
|
59
|
+
"clean",
|
|
60
|
+
"save",
|
|
61
|
+
"run",
|
|
62
|
+
"handle",
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _is_entry(fn) -> bool:
|
|
67
|
+
n = fn.name
|
|
68
|
+
return (
|
|
69
|
+
fn.kind == "module"
|
|
70
|
+
or fn.exported
|
|
71
|
+
or fn.decorated
|
|
72
|
+
or n.startswith("__")
|
|
73
|
+
or n.startswith("test")
|
|
74
|
+
or (fn.kind == "method" and n in FRAMEWORK_METHODS)
|
|
75
|
+
or n in ("setUp", "tearDown", "setUpClass", "tearDownClass")
|
|
76
|
+
or is_test(fn.file)
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def dead_code(g: Graph) -> list[Flag]:
|
|
81
|
+
file_of = {fn.id: fn.file for fn in g.functions}
|
|
82
|
+
used = {e.dst for e in g.edges if e.kind in ("call", "ref")}
|
|
83
|
+
used_by_code = {e.dst for e in g.edges if e.kind in ("call", "ref") and not is_test(file_of.get(e.src, ""))}
|
|
84
|
+
imported = {e.dst for e in g.edges if e.kind == "import"}
|
|
85
|
+
out = []
|
|
86
|
+
for fn in g.functions:
|
|
87
|
+
# A file nothing imports is loaded by a framework, a runner or a user: its exports are entry points.
|
|
88
|
+
if _is_entry(fn) or (fn.public and fn.file not in imported):
|
|
89
|
+
continue
|
|
90
|
+
if fn.id in used:
|
|
91
|
+
if fn.id not in used_by_code and not is_test(fn.file):
|
|
92
|
+
out.append(Flag("test_only", "info", fn.id, f"{fn.qualname} is only called from tests"))
|
|
93
|
+
continue
|
|
94
|
+
if fn.dynamic: # its name is used where the analyzer can't tell which definition runs: maybe this one
|
|
95
|
+
continue
|
|
96
|
+
if fn.kind == "method": # often called through an instance or a framework: only a hint
|
|
97
|
+
out.append(
|
|
98
|
+
Flag(
|
|
99
|
+
"unused",
|
|
100
|
+
"info",
|
|
101
|
+
fn.id,
|
|
102
|
+
f"{fn.qualname} has no callers found (it may be called through an instance or a framework)",
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
else:
|
|
106
|
+
out.append(Flag("unused", "warn", fn.id, f"{fn.qualname} is never called or referenced"))
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def duplicates(g: Graph, cfg: Config) -> list[Flag]:
|
|
111
|
+
groups = defaultdict(list)
|
|
112
|
+
for fn in g.functions:
|
|
113
|
+
if fn.shape and fn.loc >= cfg.duplicate_min_lines:
|
|
114
|
+
groups[fn.shape].append(fn)
|
|
115
|
+
out = []
|
|
116
|
+
for group in groups.values():
|
|
117
|
+
# the same file for another platform (x_linux.go / x_darwin.go) copies on purpose: keep one of each set
|
|
118
|
+
fns = [
|
|
119
|
+
f
|
|
120
|
+
for i, f in enumerate(group)
|
|
121
|
+
if not any(platform_variants(f.file, o.file) or (f.file == o.file and f.name == o.name) for o in group[:i])
|
|
122
|
+
] # (and overloads: one method per type, in one file)
|
|
123
|
+
if len(fns) < 2:
|
|
124
|
+
continue
|
|
125
|
+
ids = [f.id for f in fns]
|
|
126
|
+
for f in fns:
|
|
127
|
+
others = [o for o in fns if o is not f]
|
|
128
|
+
names = ", ".join(f"{o.qualname} ({o.file})" for o in others[:3]) + (" …" if len(others) > 3 else "")
|
|
129
|
+
out.append(Flag("duplicate", "warn", f.id, f"Same code as {names}", [i for i in ids if i != f.id]))
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
NOT_PRODUCT = re.compile(r"(?:^|/)(?:database/factories|database/seeders|factories|seeds?|seeders)/")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def import_cycles(g: Graph) -> list[Flag]:
|
|
137
|
+
"""Strongly connected groups of files in the import graph (Tarjan)."""
|
|
138
|
+
adj = defaultdict(set)
|
|
139
|
+
for e in g.edges:
|
|
140
|
+
# a Rust crate compiles as one unit, so its modules may use each other; tests and factories (fixtures for
|
|
141
|
+
# tests and seeding, like Laravel's model <-> factory pairs) aren't part of the product's structure
|
|
142
|
+
if e.kind == "import" and not any(x.endswith(".rs") or is_test(x) or NOT_PRODUCT.search(x) for x in (e.src, e.dst)):
|
|
143
|
+
adj[e.src].add(e.dst)
|
|
144
|
+
index, low, stack, on, comps, counter = {}, {}, [], set(), [], [0]
|
|
145
|
+
|
|
146
|
+
def visit(v: str) -> None:
|
|
147
|
+
work = [(v, iter(sorted(adj[v])))]
|
|
148
|
+
index[v] = low[v] = counter[0]
|
|
149
|
+
counter[0] += 1
|
|
150
|
+
stack.append(v)
|
|
151
|
+
on.add(v)
|
|
152
|
+
while work:
|
|
153
|
+
node, it = work[-1]
|
|
154
|
+
nxt = next(it, None)
|
|
155
|
+
if nxt is None:
|
|
156
|
+
work.pop()
|
|
157
|
+
if work:
|
|
158
|
+
low[work[-1][0]] = min(low[work[-1][0]], low[node])
|
|
159
|
+
if low[node] == index[node]:
|
|
160
|
+
comp = []
|
|
161
|
+
while True:
|
|
162
|
+
w = stack.pop()
|
|
163
|
+
on.discard(w)
|
|
164
|
+
comp.append(w)
|
|
165
|
+
if w == node:
|
|
166
|
+
break
|
|
167
|
+
if len(comp) > 1:
|
|
168
|
+
comps.append(sorted(comp))
|
|
169
|
+
elif nxt not in index:
|
|
170
|
+
index[nxt] = low[nxt] = counter[0]
|
|
171
|
+
counter[0] += 1
|
|
172
|
+
stack.append(nxt)
|
|
173
|
+
on.add(nxt)
|
|
174
|
+
work.append((nxt, iter(sorted(adj[nxt]))))
|
|
175
|
+
elif nxt in on:
|
|
176
|
+
low[node] = min(low[node], index[nxt])
|
|
177
|
+
|
|
178
|
+
for v in sorted({f.id for f in g.files}):
|
|
179
|
+
if v not in index:
|
|
180
|
+
visit(v)
|
|
181
|
+
out = []
|
|
182
|
+
for comp in comps:
|
|
183
|
+
loop = " → ".join(c.split("/")[-1] for c in comp)
|
|
184
|
+
# Python and JavaScript run a module's code as it's imported, so a loop can break loading: high. Classes in
|
|
185
|
+
# Java, Kotlin, C#, Swift… load lazily, so a loop works at runtime and is a design smell (they can't be
|
|
186
|
+
# understood, tested or reused apart): warn.
|
|
187
|
+
lazy = all(c.endswith(LAZY_LOADING) for c in comp)
|
|
188
|
+
sev, what = ("warn", "Dependency loop") if lazy else ("high", "Import loop")
|
|
189
|
+
for f in comp:
|
|
190
|
+
out.append(Flag("cycle", sev, f, f"{what} of {len(comp)} files: {loop}", [c for c in comp if c != f]))
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
LAZY_LOADING = (".java", ".kt", ".kts", ".scala", ".sc", ".groovy", ".cs", ".swift", ".dart", ".fs", ".m", ".mm")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def size_flags(g: Graph, cfg: Config) -> list[Flag]:
|
|
198
|
+
out = []
|
|
199
|
+
for f in g.files:
|
|
200
|
+
if f.loc > cfg.large_file:
|
|
201
|
+
out.append(Flag("large_file", "info", f.id, f"{f.loc} lines (over {cfg.large_file})"))
|
|
202
|
+
for fn in g.functions:
|
|
203
|
+
if fn.kind != "module" and fn.loc > cfg.long_function:
|
|
204
|
+
out.append(Flag("long_function", "info", fn.id, f"{fn.qualname} is {fn.loc} lines (over {cfg.long_function})"))
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def hubs(g: Graph, cfg: Config) -> list[Flag]:
|
|
209
|
+
"""Functions called from many different files: a change there ripples everywhere."""
|
|
210
|
+
file_of = {fn.id: fn.file for fn in g.functions}
|
|
211
|
+
callers = defaultdict(set)
|
|
212
|
+
for e in g.edges:
|
|
213
|
+
if e.kind == "call" and file_of.get(e.src) != file_of.get(e.dst):
|
|
214
|
+
callers[e.dst].add(file_of.get(e.src))
|
|
215
|
+
by_id = {fn.id: fn for fn in g.functions}
|
|
216
|
+
return [
|
|
217
|
+
Flag("hub", "info", fid, f"{by_id[fid].qualname} is called from {len(files)} files")
|
|
218
|
+
for fid, files in callers.items()
|
|
219
|
+
if len(files) >= cfg.hub_callers and fid in by_id
|
|
220
|
+
]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def layer_violations(g: Graph, cfg: Config) -> list[Flag]:
|
|
224
|
+
if not cfg.forbid:
|
|
225
|
+
return []
|
|
226
|
+
layer_of = {f.id: f.layer for f in g.files}
|
|
227
|
+
forbidden = set(cfg.forbid)
|
|
228
|
+
out = []
|
|
229
|
+
for e in g.edges:
|
|
230
|
+
if e.kind != "import":
|
|
231
|
+
continue
|
|
232
|
+
pair = (layer_of.get(e.src), layer_of.get(e.dst))
|
|
233
|
+
if pair in forbidden:
|
|
234
|
+
out.append(
|
|
235
|
+
Flag(
|
|
236
|
+
"layer_violation",
|
|
237
|
+
"high",
|
|
238
|
+
e.src,
|
|
239
|
+
f"{e.src} ({pair[0]}) imports {e.dst} ({pair[1]}), which factory.toml forbids",
|
|
240
|
+
[e.dst],
|
|
241
|
+
)
|
|
242
|
+
)
|
|
243
|
+
return out
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def run_flags(g: Graph, cfg: Config) -> None:
|
|
247
|
+
g.flags = [
|
|
248
|
+
*import_cycles(g),
|
|
249
|
+
*layer_violations(g, cfg),
|
|
250
|
+
*duplicates(g, cfg),
|
|
251
|
+
*near_duplicates(g, cfg),
|
|
252
|
+
*efficiency_flags(g),
|
|
253
|
+
*dead_code(g),
|
|
254
|
+
*hubs(g, cfg),
|
|
255
|
+
*size_flags(g, cfg),
|
|
256
|
+
]
|
|
257
|
+
by_id = {fn.id: fn for fn in g.functions}
|
|
258
|
+
for f in g.flags: # every issue points at a line, for editors and for Claude Code
|
|
259
|
+
if not f.line and f.target in by_id:
|
|
260
|
+
f.line = by_id[f.target].line
|
|
261
|
+
g.flags.sort(key=lambda f: (SEVERITY_ORDER[f.severity], f.kind, f.target))
|
|
262
|
+
for fn in g.functions: # only needed for the checks above; keeps the saved graph and the HTML small
|
|
263
|
+
fn.tokens = ""
|
codefactory/graph.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""The language-neutral graph every analyzer produces and every other part (flags, viewer) reads."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
|
|
7
|
+
SCHEMA_VERSION = 1
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Function:
|
|
12
|
+
id: str # "<file path>::<qualname>"
|
|
13
|
+
file: str
|
|
14
|
+
name: str
|
|
15
|
+
qualname: str
|
|
16
|
+
line: int
|
|
17
|
+
end: int
|
|
18
|
+
loc: int
|
|
19
|
+
kind: str = "function" # function | method | module (top-level code)
|
|
20
|
+
decorated: bool = False
|
|
21
|
+
exported: bool = False # listed in __all__ or an entry point
|
|
22
|
+
shape: str = "" # structural hash, for duplicate detection
|
|
23
|
+
dynamic: bool = False # a method whose name is used as obj.name somewhere we couldn't resolve
|
|
24
|
+
public: bool = False # TS/JS `export`: in a file nothing imports, a framework's entry point (a route, a screen)
|
|
25
|
+
io: list[str] = field(default_factory=list) # database, file or network calls it makes itself (callee names)
|
|
26
|
+
tokens: str = "" # structure tokens for near-duplicate detection; emptied after flags run
|
|
27
|
+
doc: int = 0 # lines of its docstring (counted in loc, but not code)
|
|
28
|
+
branches: int = 0 # decision points (if, loops, case, catch, and/or): how hard it is to follow
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class File:
|
|
33
|
+
id: str # posix path relative to the analyzed root
|
|
34
|
+
module: str
|
|
35
|
+
loc: int
|
|
36
|
+
layer: str = ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Edge:
|
|
41
|
+
src: str
|
|
42
|
+
dst: str
|
|
43
|
+
kind: str # call | ref | import
|
|
44
|
+
count: int = 1
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Site:
|
|
49
|
+
"""A notable spot inside a function, for the efficiency checks."""
|
|
50
|
+
|
|
51
|
+
fn: str # function id
|
|
52
|
+
kind: str # loop_call (resolved call in a loop) | loop_io | loop_await | loop_scan | tx_call (call in a transaction)
|
|
53
|
+
line: int
|
|
54
|
+
target: str = "" # loop_call: the function called
|
|
55
|
+
detail: str = "" # loop_io / loop_scan: what's called ("db.getAllAsync", "items.find")
|
|
56
|
+
bounded: bool = False # every loop around it goes over a list fixed in the code (a literal, a constant, range(5))
|
|
57
|
+
tx: bool = False # inside a transaction (with db.session(): / transaction(db, () => …)): writes there are batched
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class Flag:
|
|
62
|
+
kind: str
|
|
63
|
+
severity: str # high | warn | info
|
|
64
|
+
target: str # a file or function id
|
|
65
|
+
message: str
|
|
66
|
+
related: list[str] = field(default_factory=list)
|
|
67
|
+
line: int = 0 # where to look (the function's line, or the exact call)
|
|
68
|
+
score: float = 0.0 # similar: the highest similarity to another member (0-1)
|
|
69
|
+
reason: str = "" # silenced: why (from the comment or factory.toml)
|
|
70
|
+
detail: str = "" # io_in_loop: network | read | file | write, with ":fixed" when the loop can't grow with the data
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Graph:
|
|
75
|
+
root: str
|
|
76
|
+
language: str
|
|
77
|
+
files: list[File] = field(default_factory=list)
|
|
78
|
+
functions: list[Function] = field(default_factory=list)
|
|
79
|
+
edges: list[Edge] = field(default_factory=list)
|
|
80
|
+
sites: list[Site] = field(default_factory=list)
|
|
81
|
+
flags: list[Flag] = field(default_factory=list)
|
|
82
|
+
silenced: list[Flag] = field(default_factory=list) # issues marked as intended; kept so they can be listed
|
|
83
|
+
layers: list[str] = field(default_factory=list) # left-to-right order for the viewer
|
|
84
|
+
rules: list[str] = field(default_factory=list) # "a -> b" pairs that are forbidden
|
|
85
|
+
|
|
86
|
+
def to_dict(self) -> dict:
|
|
87
|
+
return {"schema": SCHEMA_VERSION, **asdict(self)}
|
|
88
|
+
|
|
89
|
+
def merge(self, other: Graph) -> None:
|
|
90
|
+
self.files += other.files
|
|
91
|
+
self.functions += other.functions
|
|
92
|
+
self.edges += other.edges
|
|
93
|
+
self.sites += other.sites
|
|
94
|
+
if other.language not in self.language.split("+"):
|
|
95
|
+
self.language = f"{self.language}+{other.language}" if self.language else other.language
|