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,299 @@
|
|
|
1
|
+
"""One file through tree-sitter: its functions, calls, imports and loops, as plain data.
|
|
2
|
+
|
|
3
|
+
Runs in worker processes, so everything it returns is picklable (and JSON-able, for the per-file cache). It knows no
|
|
4
|
+
language in particular: tree-sitter grammars name their nodes consistently (`function_declaration`,
|
|
5
|
+
`method_definition`, `call_expression`, `for_statement`…), and these patterns match those names. What a grammar
|
|
6
|
+
names differently is missed, not misread.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
# Node kinds, by naming convention across grammars.
|
|
15
|
+
FUNC = re.compile(
|
|
16
|
+
r"^(?:function|method|constructor|destructor|operator|init|deinit|subscript|getter|setter|accessor|local_function|"
|
|
17
|
+
r"fun|func|def|singleton_method|protocol_function)_?(?:definition|declaration|item|statement|spec|signature)?$|"
|
|
18
|
+
r"^(?:function_definition|method|function|subroutine_definition|function_subroutine)$"
|
|
19
|
+
)
|
|
20
|
+
NOT_FUNC = re.compile(r"signature|_type$|^function$") # declarations without bodies; `function` keyword tokens
|
|
21
|
+
CLASS = re.compile(
|
|
22
|
+
r"^(?:class|struct|interface|trait|impl|enum|object|module|namespace|protocol|extension|record|union|"
|
|
23
|
+
r"type_spec|contract|mixin)_?(?:definition|declaration|item|specifier|body)?$|^(?:class|module)$"
|
|
24
|
+
)
|
|
25
|
+
CALL = re.compile(
|
|
26
|
+
r"^(?:call|call_expression|method_invocation|function_call|invocation_expression|method_call_expression|"
|
|
27
|
+
r"call_expr|function_call_expression|member_call_expression|scoped_call_expression|nullsafe_member_call_expression|"
|
|
28
|
+
r"object_creation_expression|new_expression|constructor_invocation|navigation_expression_call|macro_invocation|"
|
|
29
|
+
r"command|function_call_statement)$"
|
|
30
|
+
)
|
|
31
|
+
LOOP = re.compile(r"(?:^|_)(?:for|foreach|while|loop|repeat|until|do_while)(?:_|$)")
|
|
32
|
+
NOT_LOOP = re.compile(r"do_block|for_clause|range_clause|_in$|loop_label|while_condition|for_initializer")
|
|
33
|
+
IMPORT = re.compile(
|
|
34
|
+
r"^(?:import|import_declaration|import_statement|import_from_statement|import_header|use_declaration|"
|
|
35
|
+
r"preproc_include|using_directive|namespace_use_declaration|import_spec|require_call|include_expression|"
|
|
36
|
+
r"require_expression|extern_crate_declaration)$"
|
|
37
|
+
)
|
|
38
|
+
# Iteration helpers whose block or closure argument runs once per item.
|
|
39
|
+
ITER = {
|
|
40
|
+
"each",
|
|
41
|
+
"map",
|
|
42
|
+
"forEach",
|
|
43
|
+
"for_each",
|
|
44
|
+
"each_with_index",
|
|
45
|
+
"flatMap",
|
|
46
|
+
"flat_map",
|
|
47
|
+
"collect",
|
|
48
|
+
"select",
|
|
49
|
+
"filter",
|
|
50
|
+
"reject",
|
|
51
|
+
"times",
|
|
52
|
+
"each_value",
|
|
53
|
+
"each_key",
|
|
54
|
+
"forEachIndexed",
|
|
55
|
+
"mapNotNull",
|
|
56
|
+
"iter",
|
|
57
|
+
"into_iter",
|
|
58
|
+
"for_each_entry",
|
|
59
|
+
}
|
|
60
|
+
REQUIRE = {"require", "require_relative", "require_once", "include_once", "load", "dofile", "import", "source"}
|
|
61
|
+
CLOSURE = re.compile(r"block|lambda|closure|anonymous_function|function_literal|func_literal|arrow_function|do_block")
|
|
62
|
+
IDENT = re.compile(r"identifier|^name$|^constant$|word|property_identifier|field_identifier|simple_identifier")
|
|
63
|
+
STRINGY = re.compile(r"string|char_literal|heredoc")
|
|
64
|
+
NUMBER = re.compile(r"number|integer|float|decimal|^int_literal|real_literal")
|
|
65
|
+
COMMENT = re.compile(r"comment")
|
|
66
|
+
PUBLIC = re.compile(r"^\s*(?:@\w+\s+)*(?:export|public|pub\b|open\b|def\b|module_function)")
|
|
67
|
+
BRANCH = re.compile(
|
|
68
|
+
r"^(?:if|elif|else_if|elsif|unless|for|foreach|while|until|do|loop|case|when|catch|rescue|except|guard|match_arm|"
|
|
69
|
+
r"switch_case|switch_section|conditional|ternary)(?:_\w+)?$"
|
|
70
|
+
)
|
|
71
|
+
MAX_BYTES = 1_000_000 # bigger files are generated or data
|
|
72
|
+
MAX_DEPTH = 400 # pathological nesting (generated code) is cut, not followed
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _name(node, call: bool = False) -> str:
|
|
76
|
+
"""A definition's or call's name: its `name` field, else the last identifier of its callee or declarator."""
|
|
77
|
+
for field in ("name", "declarator", "function", "method", "constructor", "type", "macro"):
|
|
78
|
+
child = node.child_by_field_name(field)
|
|
79
|
+
if child is not None:
|
|
80
|
+
if IDENT.search(child.type) or child.type in ("operator_name", "destructor_name"):
|
|
81
|
+
return child.text.decode("utf-8", "replace")
|
|
82
|
+
found = _last_ident(child)
|
|
83
|
+
if found:
|
|
84
|
+
return found
|
|
85
|
+
for c in node.named_children: # Ruby `def name`, Elixir and friends: the first identifier
|
|
86
|
+
if IDENT.search(c.type):
|
|
87
|
+
return c.text.decode("utf-8", "replace")
|
|
88
|
+
if call and node.named_children: # Swift, Kotlin: the callee is the first child (a.b.query -> query)
|
|
89
|
+
return _last_ident(node.named_children[0])
|
|
90
|
+
return ""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _last_ident(node, depth: int = 0) -> str:
|
|
94
|
+
if IDENT.search(node.type) and not node.named_children:
|
|
95
|
+
return node.text.decode("utf-8", "replace")
|
|
96
|
+
if depth > 6:
|
|
97
|
+
return ""
|
|
98
|
+
for field in ("name", "field", "property", "declarator", "function", "attribute", "method"):
|
|
99
|
+
child = node.child_by_field_name(field)
|
|
100
|
+
if child is not None:
|
|
101
|
+
return _last_ident(child, depth + 1)
|
|
102
|
+
for c in reversed(node.named_children):
|
|
103
|
+
if c.type in ("argument_list", "arguments", "parameter_list", "parameters", "type_arguments"):
|
|
104
|
+
continue
|
|
105
|
+
got = _last_ident(c, depth + 1)
|
|
106
|
+
if got:
|
|
107
|
+
return got
|
|
108
|
+
return ""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _callee_text(node) -> str:
|
|
112
|
+
"""`repo.find`: the callee as written. Java, Ruby and PHP keep the receiver and the method name in separate fields
|
|
113
|
+
(object/receiver + name/method); others have one function expression."""
|
|
114
|
+
receiver = node.child_by_field_name("object") or node.child_by_field_name("receiver")
|
|
115
|
+
method = node.child_by_field_name("name") or node.child_by_field_name("method")
|
|
116
|
+
if receiver is not None and method is not None:
|
|
117
|
+
text = receiver.text.decode("utf-8", "replace") + "." + method.text.decode("utf-8", "replace")
|
|
118
|
+
else:
|
|
119
|
+
fn = node.child_by_field_name("function") or node.child_by_field_name("method")
|
|
120
|
+
fn = fn or (node.named_children[0] if node.named_children else None)
|
|
121
|
+
text = (fn or node).text.decode("utf-8", "replace")
|
|
122
|
+
return re.sub(r"\s+", "", text.split("(")[0])[:80]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
BODY = {"block", "body", "compound_statement", "body_statement", "function_body", "statement_block", "do_block"}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _has_body(node) -> bool:
|
|
129
|
+
return node.child_by_field_name("body") is not None or any(c.type in BODY for c in node.named_children)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _import_sources(node) -> list[str]:
|
|
133
|
+
"""What an import names: every quoted path (Go's grouped imports, C includes), else the dotted path."""
|
|
134
|
+
text = node.text.decode("utf-8", "replace")
|
|
135
|
+
quoted = re.findall(r"""["'<]([^"'<>\n]+)["'>]""", text)
|
|
136
|
+
if quoted:
|
|
137
|
+
return quoted
|
|
138
|
+
text = re.sub(r"^\s*(?:import|from|use|using|require|include|extern\s+crate|static)\b", "", text)
|
|
139
|
+
text = re.split(r"\s+(?:import|as)\s+|[;{(]", text)[0].strip().strip("*").strip(".:")
|
|
140
|
+
return [text] if text else []
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
HERITAGE = re.compile(
|
|
144
|
+
r"inheritance|superclass|super_interfaces|base_list|extends|implements|delegation_specifier|heritage|base_class"
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _inherits(node, source: bytes) -> bool:
|
|
149
|
+
"""`class A: Base`, `extends`, `implements`, Ruby's `class A < B`: by a child node, else by the header's text."""
|
|
150
|
+
if any(HERITAGE.search(c.type) for c in node.children):
|
|
151
|
+
return True
|
|
152
|
+
body = node.child_by_field_name("body")
|
|
153
|
+
head = source[node.start_byte : body.start_byte if body is not None else min(node.end_byte, node.start_byte + 300)]
|
|
154
|
+
head = head.split(b"{")[0].split(b"\n")[0]
|
|
155
|
+
return bool(re.search(rb"\b(?:extends|implements)\b|^\s*(?:\w+\s+)*(?:class|struct|object|enum)\s+\w+[^:<(]*[:<]", head))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
OVERRIDE = re.compile(r"\boverride\b|@Override\b")
|
|
159
|
+
PRIVATE = re.compile(r"^\s*(?:@\w+(?:\([^)]*\))?\s+)*(?:\w+\s+)*?(?:private|internal|protected|fileprivate)\b")
|
|
160
|
+
PUBLIC_BY_DEFAULT = (".kt", ".kts", ".scala", ".sc", ".groovy", ".rb", ".php") # no modifier = public
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _public(head: str, name: str, rel: str) -> bool:
|
|
164
|
+
"""Part of the file's public surface: an explicit `public`/`export`/`pub`, a capitalised Go name, a Dart name
|
|
165
|
+
without `_`, or no restricting modifier in a language where members are public by default (Kotlin, Scala, Ruby,
|
|
166
|
+
PHP)."""
|
|
167
|
+
if PUBLIC.match(head) or name == "main":
|
|
168
|
+
return True
|
|
169
|
+
if rel.endswith(".go"):
|
|
170
|
+
return name[:1].isupper()
|
|
171
|
+
if rel.endswith(".dart"):
|
|
172
|
+
return not name.startswith("_")
|
|
173
|
+
return rel.endswith(PUBLIC_BY_DEFAULT) and not PRIVATE.match(head)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# Declared types, by name, from the text: `repo: Repo` (Swift, Kotlin, TypeScript, Rust, Python annotations),
|
|
177
|
+
# `Repo repo` (Java, C#, C++), `val repo = Repo(…)` / `let repo = new Repo(…)`, Go's `repo *Repo` and `repo := &Repo{`.
|
|
178
|
+
# File-wide, so two variables of one name with different types in one file stay ambiguous (both are dropped).
|
|
179
|
+
TYPE_PATTERNS = (
|
|
180
|
+
re.compile(r"\b(\w+)\s*:\s*(?:&\s*)?(?:mut\s+)?(?:inout\s+)?([A-Z]\w*)\b"),
|
|
181
|
+
re.compile(r"\b([A-Z]\w*)(?:<[^<>]*>)?\s+(\w+)\s*[;=,)]"),
|
|
182
|
+
re.compile(r"\b(?:let|var|val|const|auto)\s+(\w+)\s*=\s*(?:new\s+)?([A-Z]\w*)\s*[({<]"),
|
|
183
|
+
re.compile(r"\b(\w+)\s+\*?([A-Z]\w*)\s*[,)]"),
|
|
184
|
+
re.compile(r"\b(\w+)\s*:=\s*&?([A-Z]\w*)\s*\{"),
|
|
185
|
+
)
|
|
186
|
+
NOT_TYPES = {"String", "Int", "Bool", "Double", "Float", "Long", "Integer", "Boolean", "Object", "Any", "Void", "None",
|
|
187
|
+
"Optional", "List", "Map", "Set", "Array", "Dictionary", "Self", "This", "True", "False", "Null",
|
|
188
|
+
"Error"} # fmt: skip
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def declared_types(text: str) -> dict[str, str]:
|
|
192
|
+
seen: dict[str, set[str]] = {}
|
|
193
|
+
for i, pat in enumerate(TYPE_PATTERNS):
|
|
194
|
+
for m in pat.finditer(text):
|
|
195
|
+
name, typ = (m.group(2), m.group(1)) if i == 1 else (m.group(1), m.group(2))
|
|
196
|
+
if typ not in NOT_TYPES and name[:1].islower():
|
|
197
|
+
seen.setdefault(name, set()).add(typ)
|
|
198
|
+
return {name: next(iter(types)) for name, types in seen.items() if len(types) == 1}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def walk(source: bytes, parser, rel: str) -> dict:
|
|
202
|
+
"""Functions (with calls, loops and structure tokens), imports and the file's top-level calls."""
|
|
203
|
+
tree = parser.parse(source)
|
|
204
|
+
lines = source.count(b"\n") + 1
|
|
205
|
+
out = {"loc": lines, "functions": [], "imports": [], "top": {"calls": [], "refs": set()}}
|
|
206
|
+
inheriting: set[str] = set() # classes that extend or implement something: a framework may call their methods
|
|
207
|
+
stack = [(tree.root_node, None, (), 0, 0)] # node, enclosing function record, class path, loop depth, depth
|
|
208
|
+
while stack:
|
|
209
|
+
node, fn, classes, loops, depth = stack.pop()
|
|
210
|
+
t = node.type
|
|
211
|
+
if depth > MAX_DEPTH:
|
|
212
|
+
continue
|
|
213
|
+
if COMMENT.search(t):
|
|
214
|
+
continue
|
|
215
|
+
owner = fn if fn is not None else out["top"]
|
|
216
|
+
if IMPORT.match(t) and fn is None:
|
|
217
|
+
out["imports"] += _import_sources(node)
|
|
218
|
+
continue
|
|
219
|
+
if FUNC.match(t) and not NOT_FUNC.search(t) and _has_body(node) and _name(node):
|
|
220
|
+
# (a definition without a name, such as a property getter `get() = …`, is part of what holds it)
|
|
221
|
+
name = _name(node)
|
|
222
|
+
head = source[node.start_byte : min(node.end_byte, node.start_byte + 200)].decode("utf-8", "replace")
|
|
223
|
+
receiver = re.match(r"\s*func\s*\(\s*\w*\s*\*?\s*(\w+)", head) # Go methods live outside their type
|
|
224
|
+
qual = ".".join([*classes, *([receiver.group(1)] if receiver else []), name])
|
|
225
|
+
rec = {
|
|
226
|
+
"name": name,
|
|
227
|
+
"qualname": qual,
|
|
228
|
+
"line": node.start_point[0] + 1,
|
|
229
|
+
"end": node.end_point[0] + 1,
|
|
230
|
+
"kind": "method" if classes or receiver else "function",
|
|
231
|
+
# an override is called through the type it overrides (a framework, an interface): never "unused"
|
|
232
|
+
"framework": (bool(classes) and classes[-1] in inheriting) or bool(OVERRIDE.search(head)),
|
|
233
|
+
"public": _public(head, name, rel),
|
|
234
|
+
"calls": [],
|
|
235
|
+
"refs": set(),
|
|
236
|
+
"branches": 0,
|
|
237
|
+
"tokens": [],
|
|
238
|
+
}
|
|
239
|
+
out["functions"].append(rec)
|
|
240
|
+
for c in reversed(node.children):
|
|
241
|
+
stack.append((c, rec, classes, 0, depth + 1)) # loops outside a function don't run its body
|
|
242
|
+
continue
|
|
243
|
+
if CLASS.match(t) and node.named_children:
|
|
244
|
+
name = _name(node)
|
|
245
|
+
if _inherits(node, source):
|
|
246
|
+
inheriting.add(name)
|
|
247
|
+
for c in reversed(node.children):
|
|
248
|
+
stack.append((c, fn, (*classes, name) if name else classes, loops, depth + 1))
|
|
249
|
+
continue
|
|
250
|
+
if fn is not None and (BRANCH.search(t) or t in ("&&", "||", "and", "or", "??", "orelse", "andalso")):
|
|
251
|
+
fn["branches"] += 1
|
|
252
|
+
in_loop = loops
|
|
253
|
+
if LOOP.search(t) and not NOT_LOOP.search(t) and node.named_children:
|
|
254
|
+
in_loop = loops + 1
|
|
255
|
+
if CALL.match(t):
|
|
256
|
+
name = _name(node, call=True)
|
|
257
|
+
if name in REQUIRE and fn is None: # Ruby, Lua, PHP, Elixir: imports are calls
|
|
258
|
+
out["imports"] += [s for s in _import_sources(node)[:1] if s != name]
|
|
259
|
+
elif name:
|
|
260
|
+
owner["calls"].append([name, node.start_point[0] + 1, loops > 0, _callee_text(node)])
|
|
261
|
+
if name in ITER: # the closure it's given runs per item
|
|
262
|
+
for c in node.named_children:
|
|
263
|
+
if CLOSURE.search(c.type) or any(CLOSURE.search(g.type) for g in c.named_children):
|
|
264
|
+
in_loop = loops + 1
|
|
265
|
+
if IDENT.search(t) and not node.named_children:
|
|
266
|
+
parent = node.parent
|
|
267
|
+
if (
|
|
268
|
+
parent is not None
|
|
269
|
+
and not FUNC.match(parent.type)
|
|
270
|
+
and not CALL.match(parent.type)
|
|
271
|
+
and (parent.child_by_field_name("function") != node)
|
|
272
|
+
): # a name used as a value (a callback, a table entry): keeps that function from looking unused
|
|
273
|
+
owner["refs"].add(node.text.decode("utf-8", "replace"))
|
|
274
|
+
if fn is not None and not node.named_children: # leaves: the function's structure, for duplicate detection
|
|
275
|
+
text = node.text.decode("utf-8", "replace")
|
|
276
|
+
if IDENT.search(t):
|
|
277
|
+
# local-looking names are blanked (a renamed copy still matches); fields, types and called names are
|
|
278
|
+
# kept, so small functions that merely share a shape don't look like copies
|
|
279
|
+
parent = node.parent
|
|
280
|
+
keep = t != "identifier" or (
|
|
281
|
+
parent is not None and (CALL.match(parent.type) or parent.child_by_field_name("function") == node)
|
|
282
|
+
)
|
|
283
|
+
fn["tokens"].append(text if keep else "ID")
|
|
284
|
+
elif NUMBER.search(t):
|
|
285
|
+
fn["tokens"].append(f"N:{text[:12]}")
|
|
286
|
+
elif STRINGY.search(t) or STRINGY.search(node.parent.type if node.parent else ""):
|
|
287
|
+
fn["tokens"] += [f"S:{w}" for w in text.strip("'\"`").split()[:24]]
|
|
288
|
+
else:
|
|
289
|
+
fn["tokens"].append(t)
|
|
290
|
+
for c in reversed(node.children):
|
|
291
|
+
stack.append((c, fn, classes, in_loop, depth + 1))
|
|
292
|
+
out["top"]["refs"] = sorted(out["top"]["refs"])
|
|
293
|
+
out["types"] = declared_types(source.decode("utf-8", "replace"))
|
|
294
|
+
for rec in out["functions"]:
|
|
295
|
+
rec["refs"] = sorted(rec["refs"])
|
|
296
|
+
toks = rec.pop("tokens")
|
|
297
|
+
rec["tokens"] = " ".join(toks) if len(toks) >= 25 else ""
|
|
298
|
+
rec["shape"] = hashlib.sha1(rec["tokens"].encode("utf-8", "surrogatepass")).hexdigest()[:16] if rec["tokens"] else ""
|
|
299
|
+
return out
|