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/__init__.py
ADDED
codefactory/__main__.py
ADDED
codefactory/accept.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""`codefactory accept`: record that a finding is intended, with the reason, in factory.toml.
|
|
2
|
+
|
|
3
|
+
A comment next to the code (`codefactory: ignore <kind> — why`) is the first choice, because the reason sits where
|
|
4
|
+
the next reader looks. `accept` is for when editing the code isn't wanted (generated code, a finding in a file you
|
|
5
|
+
don't own, a quick triage pass), and for review findings: it appends a [[silence]] rule that every command honours.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import getpass
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
from datetime import date
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from .sarif import RULES
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def known_kinds() -> set[str]:
|
|
21
|
+
return set(RULES) # every graph and review finding has a SARIF rule
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def rules_for_task(task: dict, graph: dict) -> list[tuple[str, str]]:
|
|
25
|
+
"""(kind, where) for every finding behind a plan task."""
|
|
26
|
+
fn = {f["id"]: f for f in graph["functions"]}
|
|
27
|
+
out = []
|
|
28
|
+
for i in task["flags"]:
|
|
29
|
+
flag = graph["flags"][i]
|
|
30
|
+
f = fn.get(flag["target"])
|
|
31
|
+
where = f"{f['file']}::{f['qualname']}" if f and f["kind"] != "module" else (f["file"] if f else flag["target"])
|
|
32
|
+
out.append((flag["kind"], where))
|
|
33
|
+
return sorted(set(out))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def normalize_where(where: str) -> str:
|
|
37
|
+
"""`src/a.py:42` -> `src/a.py` (a line moves; the file or function doesn't). Backslashes become slashes."""
|
|
38
|
+
where = where.replace("\\", "/")
|
|
39
|
+
return re.sub(r":\d+$", "", where)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _who(root: Path) -> str:
|
|
43
|
+
"""The person accepting: git's user.name, else the login name."""
|
|
44
|
+
try:
|
|
45
|
+
proc = subprocess.run(["git", "-C", str(root), "config", "user.name"], capture_output=True, text=True, timeout=10)
|
|
46
|
+
name = proc.stdout.strip()
|
|
47
|
+
except (OSError, subprocess.SubprocessError):
|
|
48
|
+
name = ""
|
|
49
|
+
try:
|
|
50
|
+
return name or getpass.getuser()
|
|
51
|
+
except (OSError, KeyError):
|
|
52
|
+
return "unknown"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def append_rules(root: Path, rules: list[tuple[str, str]], reason: str) -> Path:
|
|
56
|
+
path = root / "factory.toml"
|
|
57
|
+
text = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
58
|
+
blocks = []
|
|
59
|
+
by, on = _who(root), date.today().isoformat() # the audit trail: who accepted it, and when
|
|
60
|
+
for kind, where in rules:
|
|
61
|
+
# JSON strings are valid TOML basic strings (same escapes), so quoting can't break the file
|
|
62
|
+
blocks.append(
|
|
63
|
+
f"[[silence]]\nkind = {json.dumps(kind)}\nwhere = {json.dumps(where)}\nreason = {json.dumps(reason)}\n"
|
|
64
|
+
f"by = {json.dumps(by)}\non = {json.dumps(on)}\n"
|
|
65
|
+
)
|
|
66
|
+
sep = "" if not text or text.endswith("\n\n") else ("\n" if text.endswith("\n") else "\n\n")
|
|
67
|
+
path.write_text(text + sep + "\n".join(blocks), encoding="utf-8")
|
|
68
|
+
return path
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Language analyzers. Each reads a codebase and returns a Graph; add a language by adding a module here.
|
|
2
|
+
|
|
3
|
+
Python and TypeScript/JavaScript have precise analyzers (the standard library's ast; the TypeScript type checker).
|
|
4
|
+
Every other language goes through tree-sitter (generic.py), which also stands in for TypeScript/JavaScript when the
|
|
5
|
+
typescript package isn't installed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from ..graph import Graph
|
|
14
|
+
from .generic import analyze_generic
|
|
15
|
+
from .python import analyze_python
|
|
16
|
+
from .typescript import TypeScriptUnavailable, analyze_typescript
|
|
17
|
+
|
|
18
|
+
LANGUAGES = ("python", "typescript", "other")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def analyze(root: Path, ignore: list[str], languages: list[str] | None = None, cache: bool = True) -> Graph:
|
|
22
|
+
g = Graph(root=str(root), language="")
|
|
23
|
+
wanted = languages or list(LANGUAGES)
|
|
24
|
+
js_fallback = False
|
|
25
|
+
for lang in wanted:
|
|
26
|
+
if lang == "python":
|
|
27
|
+
part = analyze_python(root, ignore, cache=cache)
|
|
28
|
+
elif lang == "typescript":
|
|
29
|
+
try:
|
|
30
|
+
part = analyze_typescript(root, ignore, cache=cache)
|
|
31
|
+
except TypeScriptUnavailable as e:
|
|
32
|
+
if languages and "other" not in languages: # asked for explicitly: that's an error
|
|
33
|
+
raise SystemExit(f"codefactory: {e}") from None
|
|
34
|
+
print(f"codefactory: {e} Using the general analyzer for TypeScript/JavaScript instead.", file=sys.stderr)
|
|
35
|
+
js_fallback = True
|
|
36
|
+
continue
|
|
37
|
+
elif lang == "other":
|
|
38
|
+
part = analyze_generic(root, ignore, include_js=js_fallback, cache=cache)
|
|
39
|
+
else:
|
|
40
|
+
raise ValueError(f"unknown language {lang!r} (choose from {', '.join(LANGUAGES)})")
|
|
41
|
+
if part.files:
|
|
42
|
+
g.merge(part)
|
|
43
|
+
_unique_ids(g)
|
|
44
|
+
return g
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _unique_ids(g: Graph) -> None:
|
|
48
|
+
"""Every function id once, whatever an analyzer produced (minified or generated code can repeat a name on one
|
|
49
|
+
line): a repeat gets #2, #3… Edges keep pointing at the first."""
|
|
50
|
+
seen: dict[str, int] = {}
|
|
51
|
+
for f in g.functions:
|
|
52
|
+
n = seen.get(f.id, 0)
|
|
53
|
+
seen[f.id] = n + 1
|
|
54
|
+
if n:
|
|
55
|
+
f.id = f"{f.id}#{n + 1}"
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""Every other language, through tree-sitter (optional: `pip install "codefactory[languages]"`).
|
|
2
|
+
|
|
3
|
+
Go, Java, Kotlin, Swift, Rust, C, C++, C#, Ruby, PHP, Scala, Dart, Lua, Elixir and more get the map, copied code,
|
|
4
|
+
calls and I/O in loops, sizes and unused-code hints. Calls are matched by name, not by type: a call links to a
|
|
5
|
+
definition in the same file, then the same folder, then a file it imports, then the only definition of that name
|
|
6
|
+
anywhere. A name defined in several places that none of those settle links to each as a "ref" (so none of them
|
|
7
|
+
looks unused) but not as a call. That is less exact than the Python and TypeScript analyzers, and says so.
|
|
8
|
+
|
|
9
|
+
Grammars download on first use per language and are cached (tree-sitter-language-pack); after that it works offline.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from collections import Counter, defaultdict
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from ..graph import Edge, File, Function, Graph, Site
|
|
21
|
+
from . import parallel
|
|
22
|
+
|
|
23
|
+
# extension -> tree-sitter language. Python and TypeScript/JavaScript have their own analyzers.
|
|
24
|
+
LANGS = {
|
|
25
|
+
".go": "go",
|
|
26
|
+
".java": "java",
|
|
27
|
+
".kt": "kotlin",
|
|
28
|
+
".kts": "kotlin",
|
|
29
|
+
".swift": "swift",
|
|
30
|
+
".rs": "rust",
|
|
31
|
+
".c": "c",
|
|
32
|
+
".h": "c",
|
|
33
|
+
".cc": "cpp",
|
|
34
|
+
".cpp": "cpp",
|
|
35
|
+
".cxx": "cpp",
|
|
36
|
+
".hpp": "cpp",
|
|
37
|
+
".hh": "cpp",
|
|
38
|
+
".hxx": "cpp",
|
|
39
|
+
".cs": "csharp",
|
|
40
|
+
".rb": "ruby",
|
|
41
|
+
".php": "php",
|
|
42
|
+
".scala": "scala",
|
|
43
|
+
".sc": "scala",
|
|
44
|
+
".dart": "dart",
|
|
45
|
+
".lua": "lua",
|
|
46
|
+
".ex": "elixir",
|
|
47
|
+
".exs": "elixir",
|
|
48
|
+
".hs": "haskell",
|
|
49
|
+
".ml": "ocaml",
|
|
50
|
+
".zig": "zig",
|
|
51
|
+
".pl": "perl",
|
|
52
|
+
".pm": "perl",
|
|
53
|
+
".r": "r",
|
|
54
|
+
".R": "r",
|
|
55
|
+
".jl": "julia",
|
|
56
|
+
".m": "objc",
|
|
57
|
+
".mm": "objc",
|
|
58
|
+
".fs": "fsharp",
|
|
59
|
+
".groovy": "groovy",
|
|
60
|
+
".clj": "clojure",
|
|
61
|
+
".erl": "erlang",
|
|
62
|
+
".sol": "solidity",
|
|
63
|
+
".f90": "fortran",
|
|
64
|
+
".gleam": "gleam",
|
|
65
|
+
".nim": "nim",
|
|
66
|
+
".cr": "crystal",
|
|
67
|
+
".vb": "vb",
|
|
68
|
+
".sh": "bash",
|
|
69
|
+
".bash": "bash",
|
|
70
|
+
}
|
|
71
|
+
JS_LANGS = {
|
|
72
|
+
".js": "javascript",
|
|
73
|
+
".jsx": "javascript",
|
|
74
|
+
".mjs": "javascript",
|
|
75
|
+
".cjs": "javascript",
|
|
76
|
+
".ts": "typescript",
|
|
77
|
+
".mts": "typescript",
|
|
78
|
+
".cts": "typescript",
|
|
79
|
+
".tsx": "tsx",
|
|
80
|
+
}
|
|
81
|
+
# I/O by the receiver's or callee's name: a database, the network, files. Matched on calls nothing in the codebase
|
|
82
|
+
# defines, so the codebase's own functions are followed instead.
|
|
83
|
+
IO_RECEIVER = re.compile(
|
|
84
|
+
r"(?:^|[.:>])(?:db|database|conn|connection|cursor|session|repo|repository|dao|client|http|https|httpClient|api|"
|
|
85
|
+
r"redis|em|entityManager|jdbc|mongo|stmt|statement|pool|tx|s3|bucket|requests|"
|
|
86
|
+
r"_db|_repo|_client|_http|\$db|\$pdo|pdo|DB|Http|HttpClient)\s*(?:\.|->|::)\s*\w+$",
|
|
87
|
+
re.I,
|
|
88
|
+
)
|
|
89
|
+
IO_NAME = re.compile(
|
|
90
|
+
r"(?:^|[.:>])(?:query|execute|executeQuery|executeUpdate|exec_query|rawQuery|QueryRow|QueryContext|ExecContext|"
|
|
91
|
+
r"Exec|urlopen|fetch|findById|findOne|findAll|find_by|"
|
|
92
|
+
r"Get|Post|Do|send|request|download|upload|read_to_string|readFile|writeFile|File\.(?:read|write|open)\w*|"
|
|
93
|
+
r"fopen|fread|fwrite|curl_exec|file_get_contents|sqlite3_exec|PQexec)$"
|
|
94
|
+
)
|
|
95
|
+
# ORM verbs (Active Record, Eloquent): in Ruby and PHP `x.save` / `->update()` is a database call; in Rust, Go, Java,
|
|
96
|
+
# Kotlin or C# `map.insert(k, v)`, `set.update()` or `list.select()` is a collection
|
|
97
|
+
ORM_NAME = re.compile(r"(?:^|[.:>])(?:where|save!?|create!?|update!?|destroy|insert|select|delete!?)$")
|
|
98
|
+
ORM_LANGS = (".rb", ".php")
|
|
99
|
+
# a receiver declared as a repository, DAO, entity manager or database context: `owners.save(o)` where
|
|
100
|
+
# `OwnerRepository owners` (Spring Data), `dao.insert(x)` (Room), `context.save()` (Core Data)
|
|
101
|
+
IO_TYPE = re.compile(r"(?:Repository|Repo|Dao|DAO|Mapper|EntityManager|JdbcTemplate|DbContext|ManagedObjectContext|"
|
|
102
|
+
r"ModelContext|Realm|SQLiteDatabase|Connection|DataSource|Session|Client)$") # fmt: skip
|
|
103
|
+
IO_VERB = re.compile(r"(?:^|[.:>])(?:find\w*|get\w*|save\w*|delete\w*|remove\w*|insert\w*|update\w*|upsert\w*|"
|
|
104
|
+
r"query\w*|exists\w*|count\w*|fetch\w*|execute\w*|persist|merge|flush|commit)$") # fmt: skip
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# Core Data, SwiftData and Realm: saving or fetching through a context is disk I/O
|
|
108
|
+
SWIFT_STORE = re.compile(r"(?:^|\.)(?:context|viewContext|managedObjectContext|backgroundContext|moc|modelContext|realm)\."
|
|
109
|
+
r"(?:save|fetch\w*|delete|insert|perform\w*|count|write|objects|add)$") # fmt: skip
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _typed_io(callee: str, types: dict[str, str]) -> bool:
|
|
113
|
+
parts = [p for p in re.split(r"\.|->|::|\?\.", callee) if p]
|
|
114
|
+
if len(parts) < 2:
|
|
115
|
+
return False
|
|
116
|
+
receiver = parts[-2].lstrip("$_")
|
|
117
|
+
typ = types.get(receiver) or types.get("_" + receiver) or ""
|
|
118
|
+
return bool(IO_TYPE.search(typ))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# Ruby on Rails: ActiveRecord class methods load from the database (`Report.find(id)` in a loop is the N+1)
|
|
122
|
+
AR = re.compile(r"(?:^|[^\w.])[A-Z]\w*(?:::[A-Z]\w*)*\.(?:find|find_by\w*|where|first|last|count|pluck|exists\?)$")
|
|
123
|
+
|
|
124
|
+
ENTRY_NAMES = {"main", "Main", "init", "setup", "teardown", "initialize", "new", "default", "drop", "fmt", "deinit"}
|
|
125
|
+
GENERATED = re.compile(rb"Code generated .* DO NOT EDIT|@generated|<auto-generated|autogenerated by|DO NOT EDIT")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def available() -> bool:
|
|
129
|
+
try:
|
|
130
|
+
import tree_sitter # noqa: F401
|
|
131
|
+
import tree_sitter_language_pack # noqa: F401
|
|
132
|
+
except ImportError:
|
|
133
|
+
return False
|
|
134
|
+
return True
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def find_files(root: Path, ignore: list[str], include_js: bool) -> list[tuple[str, str]]:
|
|
138
|
+
skip = set(ignore)
|
|
139
|
+
exts = {**LANGS, **(JS_LANGS if include_js else {})}
|
|
140
|
+
out = []
|
|
141
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
142
|
+
dirnames[:] = sorted(d for d in dirnames if d not in skip and not d.startswith(".") and not d.endswith(".egg-info"))
|
|
143
|
+
for name in sorted(filenames):
|
|
144
|
+
ext = os.path.splitext(name)[1]
|
|
145
|
+
lang = exts.get(ext) or exts.get(ext.lower())
|
|
146
|
+
if lang and not name.endswith((".d.ts", ".min.js")):
|
|
147
|
+
out.append((Path(dirpath, name).relative_to(root).as_posix(), lang))
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
_PARSERS: dict = {}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def parse_file(path: str, rel: str, lang: str) -> dict | None:
|
|
155
|
+
"""The per-file step (runs in a worker)."""
|
|
156
|
+
from tree_sitter_language_pack import get_parser
|
|
157
|
+
|
|
158
|
+
from .treewalk import MAX_BYTES, walk
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
source = Path(path).read_bytes()
|
|
162
|
+
except OSError:
|
|
163
|
+
return None
|
|
164
|
+
if len(source) > MAX_BYTES or b"\0" in source[:4096]:
|
|
165
|
+
return None # data or binary
|
|
166
|
+
try:
|
|
167
|
+
parser = _PARSERS.get(lang) or _PARSERS.setdefault(lang, get_parser(lang))
|
|
168
|
+
data = walk(source, parser, rel)
|
|
169
|
+
except Exception: # an unknown grammar, a download that failed offline, a crash in one file: skip that file
|
|
170
|
+
return None
|
|
171
|
+
data["lang"] = lang
|
|
172
|
+
if GENERATED.search(source[:2000]):
|
|
173
|
+
# generated code: nobody edits it, so its copies and dead ends aren't findings, but what it calls is used
|
|
174
|
+
for f in data["functions"]:
|
|
175
|
+
data["top"]["calls"] += f["calls"]
|
|
176
|
+
data["top"]["refs"] = sorted({*data["top"]["refs"], *f["refs"]})
|
|
177
|
+
data["functions"] = []
|
|
178
|
+
return data
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _import_index(rels: list[str]) -> dict[str, list[str]]:
|
|
182
|
+
"""Path suffixes without extension (and folders) -> files, to match what an import names."""
|
|
183
|
+
idx: dict[str, list[str]] = defaultdict(list)
|
|
184
|
+
for rel in rels:
|
|
185
|
+
parts = rel.rsplit(".", 1)[0].split("/")
|
|
186
|
+
for i in range(len(parts)):
|
|
187
|
+
idx["/".join(parts[i:])].append(rel)
|
|
188
|
+
for i in range(len(parts) - 1): # the folder: Go packages, Java packages
|
|
189
|
+
idx["/".join(parts[i:-1]) + "/"].append(rel)
|
|
190
|
+
return idx
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _resolve_import(source: str, idx: dict[str, list[str]], lang: str) -> list[str]:
|
|
194
|
+
"""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 three equal files is too ambiguous to link."""
|
|
197
|
+
s = re.sub(r"\.(?:h|hpp|hh|rb|php|lua|dart|go|rs|java|kt|swift|cs|ex|js|ts)$", "", source.strip())
|
|
198
|
+
parts = [p for p in re.split(r"[./\\:]+", s) if p and p not in ("crate", "self", "super", "~", "@", "..")]
|
|
199
|
+
# the path as written, then without its last part: `import a.b.fn` (Kotlin, Java static) names something inside a.b
|
|
200
|
+
for named in (parts, parts[:-1]):
|
|
201
|
+
for i in range(len(named)):
|
|
202
|
+
key = "/".join(named[i:])
|
|
203
|
+
if lang != "go" and key in idx and len(idx[key]) <= 3:
|
|
204
|
+
return idx[key]
|
|
205
|
+
if key + "/" in idx: # a package (Go, Java): the folder stands for its files; link to one of them
|
|
206
|
+
files = [f for f in idx[key + "/"] if not _is_test(f)]
|
|
207
|
+
if not files:
|
|
208
|
+
continue
|
|
209
|
+
top = min(f.count("/") for f in files) # the shallowest folder with that name
|
|
210
|
+
files = [f for f in files if f.count("/") == top]
|
|
211
|
+
return sorted(files, key=lambda f: (Path(f).stem != named[-1], f))[:1]
|
|
212
|
+
return []
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _is_test(rel: str) -> bool:
|
|
216
|
+
from ..paths import is_test
|
|
217
|
+
|
|
218
|
+
return is_test(rel)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def analyze_generic(root: Path, ignore: list[str], include_js: bool = False, cache: bool = True) -> Graph:
|
|
222
|
+
g = Graph(root=str(root), language="")
|
|
223
|
+
found = find_files(root, ignore, include_js)
|
|
224
|
+
if not found:
|
|
225
|
+
return g
|
|
226
|
+
if not available():
|
|
227
|
+
langs = sorted({lang for _, lang in found})
|
|
228
|
+
print(
|
|
229
|
+
f"codefactory: {len(found)} files in {', '.join(langs[:6])}{' …' if len(langs) > 6 else ''} aren't analyzed. "
|
|
230
|
+
'Install the language pack to include them: pip install "codefactory[languages]"',
|
|
231
|
+
file=sys.stderr,
|
|
232
|
+
)
|
|
233
|
+
return g
|
|
234
|
+
items = [(rel, (str(root / rel), rel, lang)) for rel, lang in found]
|
|
235
|
+
parsed = parallel.run(root, "generic", items, parse_file, tool="treewalk-4", cache=cache)
|
|
236
|
+
return link(g, parsed, rails_associations(root, [rel for rel, _ in found if rel.endswith(".rb")]))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def rails_associations(root: Path, files: list[str]) -> re.Pattern | None:
|
|
240
|
+
"""`user.posts.count` loads from the database when the models say `has_many :posts`: a call through an
|
|
241
|
+
association, matched on the names the models declare (so an array attribute called `items` doesn't count)."""
|
|
242
|
+
names: set[str] = set()
|
|
243
|
+
for rel in files:
|
|
244
|
+
try:
|
|
245
|
+
text = (root / rel).read_text(encoding="utf-8", errors="replace")
|
|
246
|
+
except OSError:
|
|
247
|
+
continue
|
|
248
|
+
names |= set(re.findall(r"^\s*(?:has_many|has_and_belongs_to_many)\s+:(\w+)", text, re.M))
|
|
249
|
+
if not names:
|
|
250
|
+
return None
|
|
251
|
+
alt = "|".join(sorted(map(re.escape, names)))
|
|
252
|
+
return re.compile(rf"(?:^|[^\w.])[a-z_]\w*\.(?:{alt})\.(?:count|where|find_by\w*|find|pluck|sum|exists\?|first|last)$")
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _typed(callee: str, src: str, types: dict[str, str], cands: list[str]) -> str | None:
|
|
256
|
+
"""`repo.find` with `repo: Repo` declared → Repo.find; `self.find` / `this.find` → a method of the caller's class.
|
|
257
|
+
Only when exactly one candidate fits."""
|
|
258
|
+
parts = [p for p in re.split(r"\.|->|::|\?\.", callee) if p]
|
|
259
|
+
if len(parts) < 2:
|
|
260
|
+
return None
|
|
261
|
+
receiver = parts[-2].lstrip("$_") if parts[-2] not in ("self", "this", "$this") else None
|
|
262
|
+
if receiver is None: # a method of the caller's own class
|
|
263
|
+
cls = src.split("::", 1)[-1].rsplit(".", 1)[0] if "." in src.split("::", 1)[-1] else ""
|
|
264
|
+
want = f"{cls}.{parts[-1]}" if cls else None
|
|
265
|
+
else:
|
|
266
|
+
typ = types.get(receiver) or types.get("_" + receiver) or (receiver if receiver[:1].isupper() else None)
|
|
267
|
+
want = f"{typ}.{parts[-1]}" if typ else None
|
|
268
|
+
if not want:
|
|
269
|
+
return None
|
|
270
|
+
# (overloads carry their line in the id: `Validate.isTrue@312`; several overloads fitting is still ambiguous)
|
|
271
|
+
qual = [re.sub(r"@\d+$", "", c.split("::", 1)[-1]) for c in cands]
|
|
272
|
+
fits = [c for c, q in zip(cands, qual, strict=True) if q == want or q.endswith("." + want)]
|
|
273
|
+
return fits[0] if len(fits) == 1 else None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def link(g: Graph, parsed: dict[str, dict], associations: re.Pattern | None = None) -> Graph:
|
|
277
|
+
"""Turns per-file results into the graph: functions, import edges, name-matched calls, loop sites."""
|
|
278
|
+
langs = Counter(d["lang"] for d in parsed.values())
|
|
279
|
+
g.language = "+".join(sorted(langs))
|
|
280
|
+
idx = _import_index(list(parsed))
|
|
281
|
+
defs: dict[str, list[str]] = defaultdict(list) # name -> function ids
|
|
282
|
+
file_of: dict[str, str] = {}
|
|
283
|
+
kind_of: dict[str, str] = {}
|
|
284
|
+
imported: dict[str, set[str]] = {}
|
|
285
|
+
for rel, d in sorted(parsed.items()):
|
|
286
|
+
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}
|
|
288
|
+
g.edges += [Edge(rel, dst, "import") for dst in sorted(imported[rel])]
|
|
289
|
+
top = Function(id=f"{rel}::<module>", file=rel, name="<module>", qualname="<module>", line=1, end=1, loc=0, kind="module")
|
|
290
|
+
g.functions.append(top)
|
|
291
|
+
seen: set[str] = set()
|
|
292
|
+
for f in d["functions"]:
|
|
293
|
+
fid = f"{rel}::{f['qualname']}"
|
|
294
|
+
if fid in seen:
|
|
295
|
+
fid = f"{fid}@{f['line']}"
|
|
296
|
+
seen.add(fid)
|
|
297
|
+
f["id"] = fid
|
|
298
|
+
g.functions.append(
|
|
299
|
+
Function(
|
|
300
|
+
id=fid,
|
|
301
|
+
file=rel,
|
|
302
|
+
name=f["name"],
|
|
303
|
+
qualname=f["qualname"],
|
|
304
|
+
line=f["line"],
|
|
305
|
+
end=f["end"],
|
|
306
|
+
loc=f["end"] - f["line"] + 1,
|
|
307
|
+
kind=f["kind"],
|
|
308
|
+
public=f["public"],
|
|
309
|
+
# exported API (and what a runtime calls by name) isn't dead code: name matching can't tell
|
|
310
|
+
exported=f["public"] or f["name"] in ENTRY_NAMES,
|
|
311
|
+
shape=f["shape"],
|
|
312
|
+
tokens=f["tokens"],
|
|
313
|
+
branches=f.get("branches", 0),
|
|
314
|
+
)
|
|
315
|
+
)
|
|
316
|
+
defs[f["name"]].append(fid)
|
|
317
|
+
file_of[fid] = rel
|
|
318
|
+
kind_of[fid] = f["kind"]
|
|
319
|
+
by_id = {f.id: f for f in g.functions}
|
|
320
|
+
calls: Counter = Counter()
|
|
321
|
+
refs: Counter = Counter()
|
|
322
|
+
ambiguous: set[str] = set()
|
|
323
|
+
for rel, d in parsed.items():
|
|
324
|
+
here = rel.rsplit("/", 1)[0] if "/" in rel else ""
|
|
325
|
+
owners = [(f"{rel}::<module>", d["top"])] + [(f["id"], f) for f in d["functions"]]
|
|
326
|
+
|
|
327
|
+
types = d.get("types", {})
|
|
328
|
+
|
|
329
|
+
def resolve(
|
|
330
|
+
name: str, src: str, bare: bool = False, callee: str = "", rel: str = rel, here: str = here, types: dict = types
|
|
331
|
+
) -> tuple[str | None, list[str]]:
|
|
332
|
+
cands = [c for c in defs.get(name, ()) if c != src]
|
|
333
|
+
typed = _typed(callee, src, types, cands)
|
|
334
|
+
if typed:
|
|
335
|
+
return typed, cands
|
|
336
|
+
same = [c for c in cands if file_of[c] == rel]
|
|
337
|
+
if len(same) == 1:
|
|
338
|
+
return same[0], cands
|
|
339
|
+
if bare and not same: # f(x) with no receiver: a plain function, unless only methods have that name
|
|
340
|
+
cands = [c for c in cands if kind_of[c] != "method"] or cands
|
|
341
|
+
for pick in (
|
|
342
|
+
same,
|
|
343
|
+
[c for c in cands if file_of[c].rsplit("/", 1)[0] == here and "/" in file_of[c]] if here else [],
|
|
344
|
+
[c for c in cands if file_of[c] in imported[rel]],
|
|
345
|
+
cands if len(cands) == 1 else [],
|
|
346
|
+
):
|
|
347
|
+
if len(pick) == 1:
|
|
348
|
+
return pick[0], cands
|
|
349
|
+
if pick:
|
|
350
|
+
break # several equally likely: don't guess
|
|
351
|
+
return None, cands
|
|
352
|
+
|
|
353
|
+
for src, rec in owners:
|
|
354
|
+
io: set[str] = set()
|
|
355
|
+
for name in rec.get("refs", ()):
|
|
356
|
+
if name in defs:
|
|
357
|
+
target, cands = resolve(name, src)
|
|
358
|
+
for c in [target] if target else cands if len(cands) <= 3 else ():
|
|
359
|
+
refs[(src, c)] += 1
|
|
360
|
+
for name, line, in_loop, callee in rec["calls"]:
|
|
361
|
+
target, cands = resolve(name, src, bare=not re.search(r"\.|->|::", callee), callee=callee)
|
|
362
|
+
if target:
|
|
363
|
+
calls[(src, target)] += 1
|
|
364
|
+
if in_loop:
|
|
365
|
+
g.sites.append(Site(src, "loop_call", line, target=target))
|
|
366
|
+
continue
|
|
367
|
+
if len(cands) <= 3:
|
|
368
|
+
for c in cands:
|
|
369
|
+
refs[(src, c)] += 1
|
|
370
|
+
else: # called by a name many things define (String, Error, Read): any of them may be what runs
|
|
371
|
+
ambiguous.add(name)
|
|
372
|
+
if not cands and (
|
|
373
|
+
IO_RECEIVER.search(callee)
|
|
374
|
+
or IO_NAME.search(callee)
|
|
375
|
+
or (src.split("::")[0].endswith(ORM_LANGS) and ORM_NAME.search(callee))
|
|
376
|
+
or (src.split("::")[0].endswith(".swift") and SWIFT_STORE.search(callee))
|
|
377
|
+
or (_typed_io(callee, types) and (ORM_NAME.search(callee) or IO_VERB.search(callee)))
|
|
378
|
+
or (src.split("::")[0].endswith(".rb") and AR.search(callee))
|
|
379
|
+
or (associations and src.split("::")[0].endswith(".rb") and associations.search(callee))
|
|
380
|
+
):
|
|
381
|
+
io.add(callee)
|
|
382
|
+
if in_loop:
|
|
383
|
+
g.sites.append(Site(src, "loop_io", line, detail=callee))
|
|
384
|
+
if src in by_id:
|
|
385
|
+
by_id[src].io = sorted(io)
|
|
386
|
+
framework = {f["id"] for d in parsed.values() for f in d["functions"] if f.get("framework")}
|
|
387
|
+
for f in g.functions:
|
|
388
|
+
if f.name in ambiguous or f.id in framework:
|
|
389
|
+
f.dynamic = True
|
|
390
|
+
g.edges += [Edge(s, d, "call", c) for (s, d), c in calls.items()]
|
|
391
|
+
g.edges += [Edge(s, d, "ref", c) for (s, d), c in refs.items() if (s, d) not in calls]
|
|
392
|
+
return g
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Per-file work in parallel, with a per-file cache, so big codebases analyze on every core and re-analyze only what
|
|
2
|
+
changed.
|
|
3
|
+
|
|
4
|
+
An analyzer splits its work into a per-file step (a top-level function: path -> plain, JSON-able data) and a step
|
|
5
|
+
that links the files together. This module runs the per-file step: results for files whose size and modification
|
|
6
|
+
time haven't changed come from `.codefactory/files-<name>.json`; the rest run in a process pool (in this process when
|
|
7
|
+
there are only a few, where starting workers would cost more than it saves).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from .. import __version__
|
|
19
|
+
|
|
20
|
+
MIN_PARALLEL = 64 # files; below this, one process is faster
|
|
21
|
+
CHUNK = 16
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def workers() -> int:
|
|
25
|
+
env = os.environ.get("CODEFACTORY_JOBS")
|
|
26
|
+
if env and env.isdigit():
|
|
27
|
+
return max(1, int(env))
|
|
28
|
+
return max(1, min(32, (os.cpu_count() or 1)))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _stamp(path: Path) -> str:
|
|
32
|
+
st = path.stat()
|
|
33
|
+
return f"{st.st_size}:{st.st_mtime_ns}"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _cache_file(root: Path, name: str) -> Path:
|
|
37
|
+
return root / ".codefactory" / f"files-{name}.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _load(root: Path, name: str, tool: str) -> dict:
|
|
41
|
+
try:
|
|
42
|
+
data = json.loads(_cache_file(root, name).read_text(encoding="utf-8"))
|
|
43
|
+
except (OSError, ValueError):
|
|
44
|
+
return {}
|
|
45
|
+
return data.get("files", {}) if data.get("tool") == tool else {}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _save(root: Path, name: str, tool: str, files: dict) -> None:
|
|
49
|
+
try:
|
|
50
|
+
d = root / ".codefactory"
|
|
51
|
+
d.mkdir(exist_ok=True)
|
|
52
|
+
(d / ".gitignore").write_text("# codefactory's cache: never committed\n*\n", encoding="utf-8")
|
|
53
|
+
_cache_file(root, name).write_text(json.dumps({"tool": tool, "files": files}), encoding="utf-8")
|
|
54
|
+
except OSError:
|
|
55
|
+
pass # a read-only checkout: analyze in full each time
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def run(
|
|
59
|
+
root: Path,
|
|
60
|
+
name: str,
|
|
61
|
+
items: list[tuple[str, tuple]],
|
|
62
|
+
work: Callable[..., dict | None],
|
|
63
|
+
tool: str = "",
|
|
64
|
+
cache: bool = True,
|
|
65
|
+
) -> dict[str, dict]:
|
|
66
|
+
"""items: (relative path, arguments for work). Returns relative path -> result (None results are left out).
|
|
67
|
+
`tool` identifies the analyzer's version: a different one ignores the cache."""
|
|
68
|
+
tool = f"{__version__}|{tool}|{_tool_hash()}"
|
|
69
|
+
old = _load(root, name, tool) if cache else {}
|
|
70
|
+
out: dict[str, dict] = {}
|
|
71
|
+
stamps: dict[str, str] = {}
|
|
72
|
+
todo: list[tuple[str, tuple]] = []
|
|
73
|
+
for rel, args in items:
|
|
74
|
+
try:
|
|
75
|
+
stamps[rel] = _stamp(root / rel)
|
|
76
|
+
except OSError:
|
|
77
|
+
continue
|
|
78
|
+
hit = old.get(rel)
|
|
79
|
+
if hit and hit[0] == stamps[rel]:
|
|
80
|
+
if hit[1] is not None:
|
|
81
|
+
out[rel] = hit[1]
|
|
82
|
+
else:
|
|
83
|
+
todo.append((rel, args))
|
|
84
|
+
if len(todo) >= MIN_PARALLEL and workers() > 1:
|
|
85
|
+
try:
|
|
86
|
+
with ProcessPoolExecutor(max_workers=workers()) as pool:
|
|
87
|
+
results = list(pool.map(_call, [(work, a) for _, a in todo], chunksize=CHUNK))
|
|
88
|
+
except (OSError, RuntimeError, ImportError): # no process support here (some sandboxes): do it in-process
|
|
89
|
+
results = [work(*a) for _, a in todo]
|
|
90
|
+
else:
|
|
91
|
+
results = [work(*a) for _, a in todo]
|
|
92
|
+
new = {rel: [stamps[rel], out[rel]] for rel in out}
|
|
93
|
+
for (rel, _), res in zip(todo, results, strict=True):
|
|
94
|
+
new[rel] = [stamps[rel], res]
|
|
95
|
+
if res is not None:
|
|
96
|
+
out[rel] = res
|
|
97
|
+
if cache:
|
|
98
|
+
_save(root, name, tool, new)
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _tool_hash() -> str:
|
|
103
|
+
"""Changes whenever codefactory's own code does, so a new or edited version never reuses old results."""
|
|
104
|
+
import hashlib
|
|
105
|
+
|
|
106
|
+
from ..cache import _tool_stamp
|
|
107
|
+
|
|
108
|
+
return hashlib.sha1(_tool_stamp().encode()).hexdigest()[:12]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _call(job: tuple) -> dict | None:
|
|
112
|
+
work, args = job
|
|
113
|
+
return work(*args)
|