adre-cli 0.1.0__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.
- adre/__init__.py +5 -0
- adre/analyzers/__init__.py +1 -0
- adre/analyzers/architecture.py +253 -0
- adre/analyzers/findings.py +457 -0
- adre/analyzers/inference.py +163 -0
- adre/cli.py +923 -0
- adre/core/__init__.py +1 -0
- adre/core/accepted.py +225 -0
- adre/core/adaptive.py +221 -0
- adre/core/baseline.py +1165 -0
- adre/core/config.py +60 -0
- adre/core/decision_engine.py +361 -0
- adre/core/declared.py +313 -0
- adre/core/evolution_intelligence.py +390 -0
- adre/core/explainer.py +413 -0
- adre/core/git_intelligence.py +392 -0
- adre/core/github_check.py +212 -0
- adre/core/incremental.py +288 -0
- adre/core/layers.py +306 -0
- adre/core/pr_intelligence.py +261 -0
- adre/core/pr_review.py +454 -0
- adre/core/prioritization.py +196 -0
- adre/core/project.py +41 -0
- adre/core/refactor_intelligence.py +201 -0
- adre/core/repositories.py +312 -0
- adre/core/review.py +96 -0
- adre/core/rules_shared.py +75 -0
- adre/core/sarif.py +141 -0
- adre/core/scope.py +141 -0
- adre/core/snapshots.py +242 -0
- adre/core/stability_intelligence.py +361 -0
- adre/graph/__init__.py +0 -0
- adre/graph/dependencies.py +379 -0
- adre/parsers/__init__.py +87 -0
- adre/parsers/go.py +140 -0
- adre/parsers/javascript.py +364 -0
- adre/parsers/jvm.py +127 -0
- adre/parsers/python.py +153 -0
- adre/reports/__init__.py +1 -0
- adre/reports/architecture.py +349 -0
- adre/rules.py +12 -0
- adre/web.py +3731 -0
- adre_cli-0.1.0.dist-info/METADATA +343 -0
- adre_cli-0.1.0.dist-info/RECORD +48 -0
- adre_cli-0.1.0.dist-info/WHEEL +5 -0
- adre_cli-0.1.0.dist-info/entry_points.txt +2 -0
- adre_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
- adre_cli-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from collections import defaultdict, deque
|
|
3
|
+
|
|
4
|
+
from adre.core.config import MAX_INDIRECT_CHAINS, MAX_INDIRECT_GRAPH_SIZE
|
|
5
|
+
from adre.core.incremental import build_incremental_index
|
|
6
|
+
from adre.core.layers import get_layer
|
|
7
|
+
from adre.parsers import collect_source_files, parse_source_file
|
|
8
|
+
from adre.parsers.go import build_go_index, is_go_file, resolve_go_import
|
|
9
|
+
from adre.parsers.jvm import build_jvm_index, is_jvm_file, resolve_jvm_import
|
|
10
|
+
from adre.parsers.javascript import JS_EXTENSIONS, resolve_javascript_specifier
|
|
11
|
+
from adre.parsers.python import absolute_python_module, python_module_from_path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_imports(file_path):
|
|
15
|
+
record = parse_source_file(file_path, os.path.basename(file_path))
|
|
16
|
+
if not record:
|
|
17
|
+
return []
|
|
18
|
+
return list(record.get("imports") or [])
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def collect_python_files(project_root):
|
|
22
|
+
files, _, _ = collect_source_files(project_root)
|
|
23
|
+
return [(path, rel) for path, rel in files if rel.endswith(".py")]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_project_index(project_root, rules=None, persist_cache=True, reuse_cache=True):
|
|
27
|
+
return build_incremental_index(
|
|
28
|
+
project_root,
|
|
29
|
+
rules=rules,
|
|
30
|
+
persist_cache=persist_cache,
|
|
31
|
+
reuse_cache=reuse_cache,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def build_dependency_graph(project_root, rules=None):
|
|
36
|
+
dependency_graph, _meta = build_project_index(project_root, rules=rules)
|
|
37
|
+
return dependency_graph
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def graph_records(dependency_graph):
|
|
41
|
+
return {
|
|
42
|
+
path: data
|
|
43
|
+
for path, data in dependency_graph.items()
|
|
44
|
+
if isinstance(data, dict) and "imports" in data
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def build_module_index(dependency_graph):
|
|
49
|
+
module_index = {}
|
|
50
|
+
records = graph_records(dependency_graph)
|
|
51
|
+
for file_path in records:
|
|
52
|
+
if not file_path.endswith(".py"):
|
|
53
|
+
continue
|
|
54
|
+
module_name = python_module_from_path(file_path)
|
|
55
|
+
module_index[module_name] = file_path
|
|
56
|
+
if module_name.endswith(".__init__"):
|
|
57
|
+
module_index[module_name.replace(".__init__", "")] = file_path
|
|
58
|
+
return module_index
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def unique_module_suffix_match(resolved_name, module_index):
|
|
62
|
+
"""Match `app.foo` to `backend.app.foo` or `src.app.foo` when unique.
|
|
63
|
+
|
|
64
|
+
src-layout and backend-layout packages are imported without the extra
|
|
65
|
+
directory prefix. Refuse to guess when more than one file matches.
|
|
66
|
+
"""
|
|
67
|
+
if not resolved_name or "." not in resolved_name:
|
|
68
|
+
return None
|
|
69
|
+
suffix = "." + resolved_name
|
|
70
|
+
hits = []
|
|
71
|
+
seen = set()
|
|
72
|
+
for name, path in module_index.items():
|
|
73
|
+
if name == resolved_name or name.endswith(suffix):
|
|
74
|
+
if path not in seen:
|
|
75
|
+
seen.add(path)
|
|
76
|
+
hits.append(path)
|
|
77
|
+
if len(hits) == 1:
|
|
78
|
+
return hits[0]
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _exact_or_suffix(name, module_index):
|
|
83
|
+
if not name:
|
|
84
|
+
return None
|
|
85
|
+
if name in module_index:
|
|
86
|
+
return module_index[name]
|
|
87
|
+
return unique_module_suffix_match(name, module_index)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _resolve_python_module(resolved_name, module_index):
|
|
91
|
+
"""Resolve a dotted module name, falling back to the deepest known package."""
|
|
92
|
+
if not resolved_name or resolved_name == ".":
|
|
93
|
+
return None
|
|
94
|
+
hit = _exact_or_suffix(resolved_name, module_index)
|
|
95
|
+
if hit:
|
|
96
|
+
return hit
|
|
97
|
+
parts = resolved_name.split(".")
|
|
98
|
+
for index in range(len(parts) - 1, 0, -1):
|
|
99
|
+
candidate = ".".join(parts[:index])
|
|
100
|
+
if candidate in module_index:
|
|
101
|
+
return module_index[candidate]
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _is_from_import(detail):
|
|
106
|
+
kind = detail.get("kind")
|
|
107
|
+
if kind:
|
|
108
|
+
return kind == "from"
|
|
109
|
+
return (detail.get("raw") or "").startswith("from ")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def resolve_python_import(detail, from_file, module_index):
|
|
113
|
+
"""Return the project files a Python import statement depends on.
|
|
114
|
+
|
|
115
|
+
`from pkg import name` depends on `pkg/name.py` when `name` is a submodule
|
|
116
|
+
(this also works for namespace packages without `__init__.py`), and on
|
|
117
|
+
`pkg` itself for names that are plain attributes of the package.
|
|
118
|
+
"""
|
|
119
|
+
module = detail.get("module") or ""
|
|
120
|
+
level = detail.get("level") or 0
|
|
121
|
+
base = absolute_python_module(from_file, module, level) if (level and from_file) else module
|
|
122
|
+
|
|
123
|
+
targets = []
|
|
124
|
+
attribute_names = []
|
|
125
|
+
if _is_from_import(detail):
|
|
126
|
+
for name in detail.get("names") or []:
|
|
127
|
+
if not name or name == "*":
|
|
128
|
+
attribute_names.append(name)
|
|
129
|
+
continue
|
|
130
|
+
submodule = "{0}.{1}".format(base, name) if base else name
|
|
131
|
+
hit = _exact_or_suffix(submodule, module_index)
|
|
132
|
+
if hit:
|
|
133
|
+
targets.append(hit)
|
|
134
|
+
else:
|
|
135
|
+
attribute_names.append(name)
|
|
136
|
+
if attribute_names or not targets:
|
|
137
|
+
hit = _resolve_python_module(base, module_index)
|
|
138
|
+
if hit:
|
|
139
|
+
targets.append(hit)
|
|
140
|
+
return targets
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def resolve_import_to_file(import_name, module_index, from_file=None, level=0, dependency_graph=None, module_resolution=None):
|
|
144
|
+
if from_file and _is_javascript_file(from_file):
|
|
145
|
+
file_index = set(graph_records(dependency_graph or {}).keys()) if dependency_graph is not None else set(module_index.values())
|
|
146
|
+
return resolve_javascript_specifier(from_file, import_name, file_index, module_resolution)
|
|
147
|
+
|
|
148
|
+
resolved_name = import_name
|
|
149
|
+
if from_file and from_file.endswith(".py") and level:
|
|
150
|
+
resolved_name = absolute_python_module(from_file, import_name, level)
|
|
151
|
+
return _resolve_python_module(resolved_name, module_index)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _is_javascript_file(path):
|
|
155
|
+
return os.path.splitext(path)[1].lower() in JS_EXTENSIONS
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def is_runtime_import(detail):
|
|
159
|
+
"""False for imports that never execute at module load time.
|
|
160
|
+
|
|
161
|
+
Type-only imports (`if TYPE_CHECKING:`, TypeScript `import type`) are
|
|
162
|
+
erased, and function-local or dynamic imports run later, so neither can
|
|
163
|
+
form an import-time cycle.
|
|
164
|
+
"""
|
|
165
|
+
if not isinstance(detail, dict):
|
|
166
|
+
return True
|
|
167
|
+
return not (detail.get("type_only") or detail.get("deferred"))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def build_graph(dependency_graph, runtime_only=False):
|
|
171
|
+
"""Resolve imports to project files.
|
|
172
|
+
|
|
173
|
+
With runtime_only=True, imports that do not run at module load time are
|
|
174
|
+
left out; that graph is the one used for cycle detection.
|
|
175
|
+
"""
|
|
176
|
+
graph = {}
|
|
177
|
+
records = graph_records(dependency_graph)
|
|
178
|
+
module_index = build_module_index(dependency_graph)
|
|
179
|
+
file_index = set(records.keys())
|
|
180
|
+
jvm_by_name, jvm_by_package = build_jvm_index(records)
|
|
181
|
+
go_by_dir = build_go_index(records)
|
|
182
|
+
|
|
183
|
+
for file_path, data in records.items():
|
|
184
|
+
graph[file_path] = set()
|
|
185
|
+
details = data.get("import_details") or [
|
|
186
|
+
{"module": imported, "level": 0} for imported in data.get("imports", [])
|
|
187
|
+
]
|
|
188
|
+
javascript = _is_javascript_file(file_path)
|
|
189
|
+
for detail in details:
|
|
190
|
+
if runtime_only and not is_runtime_import(detail):
|
|
191
|
+
continue
|
|
192
|
+
if javascript:
|
|
193
|
+
hit = resolve_javascript_specifier(
|
|
194
|
+
file_path,
|
|
195
|
+
detail.get("module") or "",
|
|
196
|
+
file_index,
|
|
197
|
+
data.get("module_resolution"),
|
|
198
|
+
)
|
|
199
|
+
resolved_files = [hit] if hit else []
|
|
200
|
+
elif file_path.endswith(".py"):
|
|
201
|
+
resolved_files = resolve_python_import(detail, file_path, module_index)
|
|
202
|
+
elif is_jvm_file(file_path):
|
|
203
|
+
resolved_files = resolve_jvm_import(detail, jvm_by_name, jvm_by_package)
|
|
204
|
+
elif is_go_file(file_path):
|
|
205
|
+
resolved_files = resolve_go_import(detail, file_path, data, go_by_dir)
|
|
206
|
+
else:
|
|
207
|
+
resolved_files = []
|
|
208
|
+
if not runtime_only and isinstance(detail, dict) and data.get("import_details"):
|
|
209
|
+
detail["resolved"] = list(resolved_files)
|
|
210
|
+
for resolved_file in resolved_files:
|
|
211
|
+
if resolved_file != file_path and resolved_file in records:
|
|
212
|
+
graph[file_path].add(resolved_file)
|
|
213
|
+
return graph
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def strongly_connected_components(graph):
|
|
217
|
+
"""Tarjan's algorithm, iterative so deep import chains cannot overflow the stack."""
|
|
218
|
+
index_of = {}
|
|
219
|
+
lowlink = {}
|
|
220
|
+
on_stack = set()
|
|
221
|
+
stack = []
|
|
222
|
+
components = []
|
|
223
|
+
counter = 0
|
|
224
|
+
|
|
225
|
+
for root in sorted(graph):
|
|
226
|
+
if root in index_of:
|
|
227
|
+
continue
|
|
228
|
+
work = [(root, iter(sorted(n for n in graph.get(root, ()) if n in graph)))]
|
|
229
|
+
index_of[root] = lowlink[root] = counter
|
|
230
|
+
counter += 1
|
|
231
|
+
stack.append(root)
|
|
232
|
+
on_stack.add(root)
|
|
233
|
+
while work:
|
|
234
|
+
node, neighbors = work[-1]
|
|
235
|
+
advanced = False
|
|
236
|
+
for neighbor in neighbors:
|
|
237
|
+
if neighbor not in index_of:
|
|
238
|
+
index_of[neighbor] = lowlink[neighbor] = counter
|
|
239
|
+
counter += 1
|
|
240
|
+
stack.append(neighbor)
|
|
241
|
+
on_stack.add(neighbor)
|
|
242
|
+
work.append((neighbor, iter(sorted(n for n in graph.get(neighbor, ()) if n in graph))))
|
|
243
|
+
advanced = True
|
|
244
|
+
break
|
|
245
|
+
if neighbor in on_stack:
|
|
246
|
+
lowlink[node] = min(lowlink[node], index_of[neighbor])
|
|
247
|
+
if advanced:
|
|
248
|
+
continue
|
|
249
|
+
work.pop()
|
|
250
|
+
if work:
|
|
251
|
+
parent = work[-1][0]
|
|
252
|
+
lowlink[parent] = min(lowlink[parent], lowlink[node])
|
|
253
|
+
if lowlink[node] == index_of[node]:
|
|
254
|
+
component = []
|
|
255
|
+
while True:
|
|
256
|
+
member = stack.pop()
|
|
257
|
+
on_stack.discard(member)
|
|
258
|
+
component.append(member)
|
|
259
|
+
if member == node:
|
|
260
|
+
break
|
|
261
|
+
components.append(sorted(component))
|
|
262
|
+
return components
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def detect_cycle_groups(graph):
|
|
266
|
+
"""Groups of files that import each other, directly or indirectly.
|
|
267
|
+
|
|
268
|
+
Each group is a strongly connected component with more than one file.
|
|
269
|
+
Groups are stable: adding or removing an edge inside a group does not
|
|
270
|
+
change it, unlike an enumeration of individual cycles.
|
|
271
|
+
"""
|
|
272
|
+
groups = [component for component in strongly_connected_components(graph) if len(component) > 1]
|
|
273
|
+
return sorted(groups, key=lambda group: (-len(group), group))
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def shortest_cycle_through(graph, node, members=None):
|
|
277
|
+
"""Shortest closed path node -> ... -> node, staying inside `members`."""
|
|
278
|
+
allowed = set(members) if members is not None else None
|
|
279
|
+
previous = {}
|
|
280
|
+
queue = deque()
|
|
281
|
+
for neighbor in sorted(graph.get(node, ())):
|
|
282
|
+
if allowed is not None and neighbor not in allowed:
|
|
283
|
+
continue
|
|
284
|
+
if neighbor == node:
|
|
285
|
+
return [node, node]
|
|
286
|
+
if neighbor not in previous:
|
|
287
|
+
previous[neighbor] = node
|
|
288
|
+
queue.append(neighbor)
|
|
289
|
+
while queue:
|
|
290
|
+
current = queue.popleft()
|
|
291
|
+
for neighbor in sorted(graph.get(current, ())):
|
|
292
|
+
if allowed is not None and neighbor not in allowed:
|
|
293
|
+
continue
|
|
294
|
+
if neighbor == node:
|
|
295
|
+
path = [current]
|
|
296
|
+
while path[-1] != node:
|
|
297
|
+
path.append(previous[path[-1]])
|
|
298
|
+
path.reverse()
|
|
299
|
+
return path + [node]
|
|
300
|
+
if neighbor not in previous:
|
|
301
|
+
previous[neighbor] = current
|
|
302
|
+
queue.append(neighbor)
|
|
303
|
+
return None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def detect_cycles(graph):
|
|
307
|
+
"""One representative cycle per cycle group, through the group's first file."""
|
|
308
|
+
cycles = []
|
|
309
|
+
for group in detect_cycle_groups(graph):
|
|
310
|
+
cycle = shortest_cycle_through(graph, group[0], group)
|
|
311
|
+
if cycle:
|
|
312
|
+
cycles.append(cycle)
|
|
313
|
+
return cycles
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def detect_indirect_dependencies(graph, max_depth=4):
|
|
317
|
+
if len(graph) > MAX_INDIRECT_GRAPH_SIZE:
|
|
318
|
+
return []
|
|
319
|
+
|
|
320
|
+
chains = []
|
|
321
|
+
seen = set()
|
|
322
|
+
|
|
323
|
+
def dfs(node, path):
|
|
324
|
+
if len(chains) >= MAX_INDIRECT_CHAINS:
|
|
325
|
+
return
|
|
326
|
+
if len(path) > max_depth:
|
|
327
|
+
return
|
|
328
|
+
for neighbor in sorted(graph.get(node, [])):
|
|
329
|
+
if neighbor in path:
|
|
330
|
+
continue
|
|
331
|
+
next_path = path + [neighbor]
|
|
332
|
+
if len(next_path) >= 3:
|
|
333
|
+
chain_key = tuple(next_path)
|
|
334
|
+
if chain_key not in seen:
|
|
335
|
+
seen.add(chain_key)
|
|
336
|
+
chains.append(next_path)
|
|
337
|
+
if len(chains) >= MAX_INDIRECT_CHAINS:
|
|
338
|
+
return
|
|
339
|
+
dfs(neighbor, next_path)
|
|
340
|
+
|
|
341
|
+
for node in sorted(graph):
|
|
342
|
+
dfs(node, [node])
|
|
343
|
+
if len(chains) >= MAX_INDIRECT_CHAINS:
|
|
344
|
+
break
|
|
345
|
+
return sorted(chains, key=lambda chain: (-len(chain), chain))
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def find_hotspot_files(graph, limit=10):
|
|
349
|
+
inbound_counts = defaultdict(int)
|
|
350
|
+
dependents = defaultdict(list)
|
|
351
|
+
|
|
352
|
+
for source, targets in graph.items():
|
|
353
|
+
for target in targets:
|
|
354
|
+
inbound_counts[target] += 1
|
|
355
|
+
dependents[target].append(source)
|
|
356
|
+
|
|
357
|
+
hotspots = []
|
|
358
|
+
for file_path, count in inbound_counts.items():
|
|
359
|
+
if count < 2:
|
|
360
|
+
continue
|
|
361
|
+
hotspots.append({
|
|
362
|
+
"file": file_path,
|
|
363
|
+
"dependency_count": count,
|
|
364
|
+
"dependents": sorted(dependents[file_path]),
|
|
365
|
+
})
|
|
366
|
+
|
|
367
|
+
return sorted(
|
|
368
|
+
hotspots,
|
|
369
|
+
key=lambda item: (-item["dependency_count"], item["file"]),
|
|
370
|
+
)[:limit]
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def dependency_graph_edges(dependency_graph):
|
|
374
|
+
edges = set()
|
|
375
|
+
resolved = build_graph(dependency_graph)
|
|
376
|
+
for source, targets in resolved.items():
|
|
377
|
+
for target in sorted(targets):
|
|
378
|
+
edges.add((source, target))
|
|
379
|
+
return edges
|
adre/parsers/__init__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from adre.core.config import MAX_ANALYZED_FILES, MAX_FILE_BYTES, SKIP_DIRS
|
|
4
|
+
from adre.parsers.go import GO_EXTENSIONS, parse_go_file
|
|
5
|
+
from adre.parsers.javascript import JS_EXTENSIONS, parse_javascript_file
|
|
6
|
+
from adre.parsers.jvm import JVM_EXTENSIONS, language_for_jvm, parse_jvm_file
|
|
7
|
+
from adre.parsers.python import parse_python_file
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
PYTHON_EXTENSIONS = {".py"}
|
|
11
|
+
SUPPORTED_EXTENSIONS = PYTHON_EXTENSIONS | JS_EXTENSIONS | JVM_EXTENSIONS | GO_EXTENSIONS
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def language_for_path(rel_path):
|
|
15
|
+
ext = os.path.splitext(rel_path)[1].lower()
|
|
16
|
+
if ext in PYTHON_EXTENSIONS:
|
|
17
|
+
return "python"
|
|
18
|
+
if ext in {".ts", ".tsx", ".mts", ".cts"}:
|
|
19
|
+
return "typescript"
|
|
20
|
+
if ext in JS_EXTENSIONS:
|
|
21
|
+
return "javascript"
|
|
22
|
+
if ext in JVM_EXTENSIONS:
|
|
23
|
+
return language_for_jvm(rel_path)
|
|
24
|
+
if ext in GO_EXTENSIONS:
|
|
25
|
+
return "go"
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def parse_source_file(file_path, rel_path, max_bytes=MAX_FILE_BYTES):
|
|
30
|
+
language = language_for_path(rel_path)
|
|
31
|
+
if language == "python":
|
|
32
|
+
return parse_python_file(file_path, rel_path, max_bytes=max_bytes)
|
|
33
|
+
if language in {"javascript", "typescript"}:
|
|
34
|
+
return parse_javascript_file(file_path, rel_path, max_bytes=max_bytes)
|
|
35
|
+
if language in {"java", "kotlin"}:
|
|
36
|
+
return parse_jvm_file(file_path, rel_path, max_bytes=max_bytes)
|
|
37
|
+
if language == "go":
|
|
38
|
+
return parse_go_file(file_path, rel_path, max_bytes=max_bytes)
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_test_filename(filename):
|
|
43
|
+
name = (filename or "").lower()
|
|
44
|
+
stem, ext = os.path.splitext(name)
|
|
45
|
+
if stem.startswith("test_") or stem.endswith("_test"):
|
|
46
|
+
return True
|
|
47
|
+
if ".test." in name or name.endswith(".test" + ext):
|
|
48
|
+
return True
|
|
49
|
+
if ".spec." in name or name.endswith(".spec" + ext):
|
|
50
|
+
return True
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def collect_source_files(project_root, max_files=MAX_ANALYZED_FILES):
|
|
55
|
+
files = []
|
|
56
|
+
truncated = False
|
|
57
|
+
unsupported = 0
|
|
58
|
+
|
|
59
|
+
for root, dirs, filenames in os.walk(project_root):
|
|
60
|
+
dirs[:] = [
|
|
61
|
+
directory for directory in dirs
|
|
62
|
+
if directory not in SKIP_DIRS
|
|
63
|
+
and not directory.startswith(".")
|
|
64
|
+
and not os.path.islink(os.path.join(root, directory))
|
|
65
|
+
]
|
|
66
|
+
dirs.sort()
|
|
67
|
+
for filename in sorted(filenames):
|
|
68
|
+
if filename.startswith(".") or is_test_filename(filename):
|
|
69
|
+
continue
|
|
70
|
+
ext = os.path.splitext(filename)[1].lower()
|
|
71
|
+
if ext not in SUPPORTED_EXTENSIONS:
|
|
72
|
+
if ext in {
|
|
73
|
+
".rs", ".rb", ".php", ".cs", ".swift", ".scala",
|
|
74
|
+
".c", ".h", ".cpp", ".hpp",
|
|
75
|
+
}:
|
|
76
|
+
unsupported += 1
|
|
77
|
+
continue
|
|
78
|
+
file_path = os.path.join(root, filename)
|
|
79
|
+
if os.path.islink(file_path):
|
|
80
|
+
continue
|
|
81
|
+
rel_path = os.path.relpath(file_path, project_root)
|
|
82
|
+
if len(files) >= max_files:
|
|
83
|
+
truncated = True
|
|
84
|
+
return files, truncated, unsupported
|
|
85
|
+
files.append((file_path, rel_path))
|
|
86
|
+
|
|
87
|
+
return files, truncated, unsupported
|
adre/parsers/go.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Go import parsing and resolution.
|
|
2
|
+
|
|
3
|
+
Go imports name packages by import path. A path inside the project's module
|
|
4
|
+
(from the nearest go.mod) maps to a directory; the importing file depends on
|
|
5
|
+
every non-test .go file in that directory.
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
from adre.parsers.javascript import strip_comments
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
GO_EXTENSIONS = {".go"}
|
|
14
|
+
MODULE_PATTERN = re.compile(r"^\s*module\s+(\S+)", re.M)
|
|
15
|
+
IMPORT_BLOCK_PATTERN = re.compile(r"\bimport\s*\((.*?)\)", re.S)
|
|
16
|
+
IMPORT_SPEC_PATTERN = re.compile(r"""(?:^|\n)\s*(?:[\w.]+\s+)?"([^"]+)\"""")
|
|
17
|
+
SINGLE_IMPORT_PATTERN = re.compile(r"""\bimport\s+(?:[\w.]+\s+)?"([^"]+)\"""")
|
|
18
|
+
PACKAGE_PATTERN = re.compile(r"^\s*package\s+(\w+)", re.M)
|
|
19
|
+
FUNC_PATTERN = re.compile(r"^func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)", re.M)
|
|
20
|
+
TYPE_PATTERN = re.compile(r"^type\s+([A-Za-z_]\w*)\s+(struct|interface)", re.M)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_go_file(file_path, rel_path, max_bytes=512000):
|
|
24
|
+
record = {
|
|
25
|
+
"path": rel_path,
|
|
26
|
+
"language": "go",
|
|
27
|
+
"imports": [],
|
|
28
|
+
"import_details": [],
|
|
29
|
+
"symbols": [],
|
|
30
|
+
"parse_error": None,
|
|
31
|
+
"package": "",
|
|
32
|
+
}
|
|
33
|
+
try:
|
|
34
|
+
with open(file_path, "r", encoding="utf-8") as handle:
|
|
35
|
+
source = handle.read(max_bytes + 1)
|
|
36
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
37
|
+
record["parse_error"] = str(exc)
|
|
38
|
+
return record
|
|
39
|
+
if len(source.encode("utf-8", errors="ignore")) > max_bytes:
|
|
40
|
+
record["parse_error"] = "file exceeds analysis size limit"
|
|
41
|
+
return record
|
|
42
|
+
|
|
43
|
+
code = strip_comments(source)
|
|
44
|
+
package = PACKAGE_PATTERN.search(code)
|
|
45
|
+
if package:
|
|
46
|
+
record["package"] = package.group(1)
|
|
47
|
+
|
|
48
|
+
found = {}
|
|
49
|
+
for block in IMPORT_BLOCK_PATTERN.finditer(code):
|
|
50
|
+
for spec in IMPORT_SPEC_PATTERN.finditer(block.group(1)):
|
|
51
|
+
found[block.start(1) + spec.start(1)] = spec.group(1)
|
|
52
|
+
for match in SINGLE_IMPORT_PATTERN.finditer(code):
|
|
53
|
+
found.setdefault(match.start(1), match.group(1))
|
|
54
|
+
for position in sorted(found):
|
|
55
|
+
path = found[position]
|
|
56
|
+
line = code.count("\n", 0, position) + 1
|
|
57
|
+
record["imports"].append(path)
|
|
58
|
+
record["import_details"].append({
|
|
59
|
+
"module": path,
|
|
60
|
+
"names": [],
|
|
61
|
+
"line": line,
|
|
62
|
+
"level": 0,
|
|
63
|
+
"kind": "import",
|
|
64
|
+
"raw": 'import "{0}"'.format(path),
|
|
65
|
+
"type_only": False,
|
|
66
|
+
"deferred": False,
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
for pattern, kind in ((TYPE_PATTERN, "class"), (FUNC_PATTERN, "function")):
|
|
70
|
+
for match in pattern.finditer(code):
|
|
71
|
+
record["symbols"].append({
|
|
72
|
+
"name": match.group(1),
|
|
73
|
+
"kind": kind,
|
|
74
|
+
"line": code.count("\n", 0, match.start(1)) + 1,
|
|
75
|
+
"loc": 1,
|
|
76
|
+
"complexity": 0,
|
|
77
|
+
})
|
|
78
|
+
return record
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def is_go_file(path):
|
|
82
|
+
return os.path.splitext(path)[1].lower() in GO_EXTENSIONS
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def nearest_go_module(rel_path, project_root, cache):
|
|
86
|
+
"""{"module": import path, "root": project-relative dir} from the closest go.mod."""
|
|
87
|
+
root = os.path.realpath(project_root)
|
|
88
|
+
directory = os.path.dirname(rel_path)
|
|
89
|
+
visited = []
|
|
90
|
+
result = None
|
|
91
|
+
while True:
|
|
92
|
+
if directory in cache:
|
|
93
|
+
result = cache[directory]
|
|
94
|
+
break
|
|
95
|
+
visited.append(directory)
|
|
96
|
+
candidate = os.path.join(root, directory, "go.mod")
|
|
97
|
+
if os.path.isfile(candidate) and not os.path.islink(candidate):
|
|
98
|
+
try:
|
|
99
|
+
with open(candidate, "r", encoding="utf-8") as handle:
|
|
100
|
+
match = MODULE_PATTERN.search(strip_comments(handle.read(65536)))
|
|
101
|
+
except (OSError, UnicodeDecodeError):
|
|
102
|
+
match = None
|
|
103
|
+
if match:
|
|
104
|
+
result = {"module": match.group(1).strip('"'), "root": directory}
|
|
105
|
+
break
|
|
106
|
+
if not directory:
|
|
107
|
+
break
|
|
108
|
+
directory = os.path.dirname(directory)
|
|
109
|
+
for item in visited:
|
|
110
|
+
cache[item] = result
|
|
111
|
+
return result
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def build_go_index(records):
|
|
115
|
+
"""Return directory -> [go files] for Go source records."""
|
|
116
|
+
by_dir = {}
|
|
117
|
+
for path in records:
|
|
118
|
+
if is_go_file(path):
|
|
119
|
+
by_dir.setdefault(os.path.dirname(path), []).append(path)
|
|
120
|
+
for files in by_dir.values():
|
|
121
|
+
files.sort()
|
|
122
|
+
return by_dir
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def resolve_go_import(detail, from_file, record, by_dir):
|
|
126
|
+
module_info = (record or {}).get("go_module")
|
|
127
|
+
import_path = (detail.get("module") or "").strip()
|
|
128
|
+
if not module_info or not import_path:
|
|
129
|
+
return []
|
|
130
|
+
module = module_info["module"]
|
|
131
|
+
if import_path == module:
|
|
132
|
+
relative = ""
|
|
133
|
+
elif import_path.startswith(module + "/"):
|
|
134
|
+
relative = import_path[len(module) + 1:]
|
|
135
|
+
else:
|
|
136
|
+
return [] # standard library or third-party module
|
|
137
|
+
directory = os.path.normpath(os.path.join(module_info["root"], relative)) if (module_info["root"] or relative) else ""
|
|
138
|
+
if directory == ".":
|
|
139
|
+
directory = ""
|
|
140
|
+
return [path for path in by_dir.get(directory, []) if path != from_file]
|