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,364 @@
|
|
|
1
|
+
import bisect
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
JS_EXTENSIONS = {".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts"}
|
|
8
|
+
RESOLVE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]
|
|
9
|
+
INDEX_FILES = ["index" + extension for extension in RESOLVE_EXTENSIONS]
|
|
10
|
+
# TypeScript ESM code imports "./x.js" while the source file is x.ts.
|
|
11
|
+
JS_TO_TS_EXTENSIONS = {
|
|
12
|
+
".js": [".ts", ".tsx"],
|
|
13
|
+
".jsx": [".tsx"],
|
|
14
|
+
".mjs": [".mts"],
|
|
15
|
+
".cjs": [".cts"],
|
|
16
|
+
}
|
|
17
|
+
CONFIG_FILENAMES = ("tsconfig.json", "jsconfig.json")
|
|
18
|
+
MAX_EXTENDS_DEPTH = 5
|
|
19
|
+
|
|
20
|
+
# Patterns run over the whole comment-stripped source, so statements may span
|
|
21
|
+
# lines (Prettier breaks long import lists across lines).
|
|
22
|
+
# Patterns run over the whole comment-stripped source, so statements may span
|
|
23
|
+
# lines (Prettier breaks long import lists across lines). Each pattern names
|
|
24
|
+
# the specifier group "spec".
|
|
25
|
+
STATIC_IMPORT = re.compile(
|
|
26
|
+
# import x from 'm' / import { a,\n b } from 'm' / export * from 'm' / import type T from 'm'
|
|
27
|
+
r"""\b(?:import|export)\s+(?P<type>type\s+)?(?P<clause>[\w\s{},*$]*?)\bfrom\s*(?P<q>['"])(?P<spec>[^'"\n]+)(?P=q)"""
|
|
28
|
+
)
|
|
29
|
+
SIDE_EFFECT_IMPORT = re.compile(r"""\bimport\s*(?P<q>['"])(?P<spec>[^'"\n]+)(?P=q)""")
|
|
30
|
+
REQUIRE_CALL = re.compile(r"""\brequire\s*\(\s*(?P<q>['"])(?P<spec>[^'"\n]+)(?P=q)\s*\)""")
|
|
31
|
+
DYNAMIC_IMPORT = re.compile(r"""\bimport\s*\(\s*(?P<q>['"])(?P<spec>[^'"\n]+)(?P=q)\s*\)""")
|
|
32
|
+
IMPORT_PATTERNS = [STATIC_IMPORT, SIDE_EFFECT_IMPORT, REQUIRE_CALL, DYNAMIC_IMPORT]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _type_only_clause(match):
|
|
36
|
+
"""True for `import type …` and `import { type A, type B } from …`.
|
|
37
|
+
|
|
38
|
+
TypeScript erases these, so they never load the module at runtime.
|
|
39
|
+
"""
|
|
40
|
+
clause = (match.group("clause") or "").strip()
|
|
41
|
+
if match.group("type"):
|
|
42
|
+
# `import type from './x'` is a default import named "type".
|
|
43
|
+
return bool(clause)
|
|
44
|
+
if not clause.startswith("{") or not clause.endswith("}"):
|
|
45
|
+
return False
|
|
46
|
+
specifiers = [item.strip() for item in clause[1:-1].split(",") if item.strip()]
|
|
47
|
+
return bool(specifiers) and all(item.startswith("type ") for item in specifiers)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
STATEMENT_KEYWORD = re.compile(r"\b(?:import|export|require)\b")
|
|
51
|
+
|
|
52
|
+
SYMBOL_PATTERNS = [
|
|
53
|
+
(re.compile(r"^\s*(?:export\s+)?(?:default\s+)?class\s+([A-Za-z_][\w]*)"), "class"),
|
|
54
|
+
(re.compile(r"^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Za-z_][\w]*)"), "function"),
|
|
55
|
+
(re.compile(r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_][\w]*)\s*="), "function"),
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def strip_comments(source):
|
|
60
|
+
"""Blank out // and /* */ comments, keeping strings and line numbers intact."""
|
|
61
|
+
out = []
|
|
62
|
+
index = 0
|
|
63
|
+
length = len(source)
|
|
64
|
+
while index < length:
|
|
65
|
+
char = source[index]
|
|
66
|
+
nxt = source[index + 1] if index + 1 < length else ""
|
|
67
|
+
if char == "/" and nxt == "/":
|
|
68
|
+
end = source.find("\n", index)
|
|
69
|
+
end = length if end == -1 else end
|
|
70
|
+
out.append(" " * (end - index))
|
|
71
|
+
index = end
|
|
72
|
+
elif char == "/" and nxt == "*":
|
|
73
|
+
end = source.find("*/", index + 2)
|
|
74
|
+
end = length if end == -1 else end + 2
|
|
75
|
+
out.append("".join("\n" if c == "\n" else " " for c in source[index:end]))
|
|
76
|
+
index = end
|
|
77
|
+
elif char in {"'", '"', "`"}:
|
|
78
|
+
end = index + 1
|
|
79
|
+
while end < length:
|
|
80
|
+
current = source[end]
|
|
81
|
+
if current == "\\":
|
|
82
|
+
end += 2
|
|
83
|
+
continue
|
|
84
|
+
if current == char:
|
|
85
|
+
end += 1
|
|
86
|
+
break
|
|
87
|
+
if current == "\n" and char != "`":
|
|
88
|
+
break
|
|
89
|
+
end += 1
|
|
90
|
+
out.append(source[index:end])
|
|
91
|
+
index = end
|
|
92
|
+
else:
|
|
93
|
+
out.append(char)
|
|
94
|
+
index += 1
|
|
95
|
+
return "".join(out)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def parse_javascript_file(file_path, rel_path, max_bytes=512000):
|
|
99
|
+
language = "typescript" if os.path.splitext(rel_path)[1].lower() in {".ts", ".tsx", ".mts", ".cts"} else "javascript"
|
|
100
|
+
record = {
|
|
101
|
+
"path": rel_path,
|
|
102
|
+
"language": language,
|
|
103
|
+
"imports": [],
|
|
104
|
+
"import_details": [],
|
|
105
|
+
"symbols": [],
|
|
106
|
+
"parse_error": None,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
with open(file_path, "r", encoding="utf-8") as handle:
|
|
111
|
+
source = handle.read(max_bytes + 1)
|
|
112
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
113
|
+
record["parse_error"] = str(exc)
|
|
114
|
+
return record
|
|
115
|
+
|
|
116
|
+
if len(source.encode("utf-8", errors="ignore")) > max_bytes:
|
|
117
|
+
record["parse_error"] = "file exceeds analysis size limit"
|
|
118
|
+
return record
|
|
119
|
+
|
|
120
|
+
code = strip_comments(source)
|
|
121
|
+
lines = source.splitlines()
|
|
122
|
+
line_starts = [0]
|
|
123
|
+
for position, char in enumerate(code):
|
|
124
|
+
if char == "\n":
|
|
125
|
+
line_starts.append(position + 1)
|
|
126
|
+
|
|
127
|
+
found = {}
|
|
128
|
+
for pattern in IMPORT_PATTERNS:
|
|
129
|
+
for match in pattern.finditer(code):
|
|
130
|
+
position = match.start("spec")
|
|
131
|
+
if position in found:
|
|
132
|
+
continue
|
|
133
|
+
statement_start = match.start()
|
|
134
|
+
keywords = list(STATEMENT_KEYWORD.finditer(code, match.start(), position))
|
|
135
|
+
if keywords:
|
|
136
|
+
statement_start = keywords[-1].start()
|
|
137
|
+
type_only = pattern is STATIC_IMPORT and _type_only_clause(match)
|
|
138
|
+
deferred = pattern is DYNAMIC_IMPORT
|
|
139
|
+
found[position] = (match.group("spec"), statement_start, type_only, deferred)
|
|
140
|
+
|
|
141
|
+
for position in sorted(found):
|
|
142
|
+
specifier, statement_start, type_only, deferred = found[position]
|
|
143
|
+
line_number = bisect.bisect_right(line_starts, position)
|
|
144
|
+
statement_line = bisect.bisect_right(line_starts, statement_start)
|
|
145
|
+
raw = " ".join(
|
|
146
|
+
part.strip() for part in lines[statement_line - 1:line_number] if part.strip()
|
|
147
|
+
)
|
|
148
|
+
record["imports"].append(specifier)
|
|
149
|
+
record["import_details"].append({
|
|
150
|
+
"module": specifier,
|
|
151
|
+
"names": [],
|
|
152
|
+
"line": statement_line,
|
|
153
|
+
"level": 1 if specifier.startswith(".") else 0,
|
|
154
|
+
"raw": raw[:200],
|
|
155
|
+
"type_only": type_only,
|
|
156
|
+
"deferred": deferred,
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
for line_number, line in enumerate(lines, start=1):
|
|
160
|
+
for pattern, kind in SYMBOL_PATTERNS:
|
|
161
|
+
match = pattern.match(line)
|
|
162
|
+
if match:
|
|
163
|
+
record["symbols"].append({
|
|
164
|
+
"name": match.group(1),
|
|
165
|
+
"kind": kind,
|
|
166
|
+
"line": line_number,
|
|
167
|
+
"loc": 1,
|
|
168
|
+
"complexity": 0,
|
|
169
|
+
})
|
|
170
|
+
break
|
|
171
|
+
|
|
172
|
+
return record
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _candidate_files(joined):
|
|
176
|
+
candidates = []
|
|
177
|
+
base, ext = os.path.splitext(joined)
|
|
178
|
+
ext = ext.lower()
|
|
179
|
+
if ext in JS_EXTENSIONS:
|
|
180
|
+
candidates.append(joined)
|
|
181
|
+
for ts_ext in JS_TO_TS_EXTENSIONS.get(ext, []):
|
|
182
|
+
candidates.append(base + ts_ext)
|
|
183
|
+
for extension in RESOLVE_EXTENSIONS:
|
|
184
|
+
candidates.append(joined + extension)
|
|
185
|
+
for index_name in INDEX_FILES:
|
|
186
|
+
candidates.append(os.path.join(joined, index_name))
|
|
187
|
+
return candidates
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _first_existing(joined, file_index):
|
|
191
|
+
joined = os.path.normpath(joined)
|
|
192
|
+
if joined.startswith(".." + os.sep) or joined == "..":
|
|
193
|
+
return None
|
|
194
|
+
for candidate in _candidate_files(joined):
|
|
195
|
+
if candidate in file_index:
|
|
196
|
+
return candidate
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _match_path_pattern(pattern, specifier):
|
|
201
|
+
if "*" not in pattern:
|
|
202
|
+
return "" if pattern == specifier else None
|
|
203
|
+
prefix, _, suffix = pattern.partition("*")
|
|
204
|
+
if (
|
|
205
|
+
specifier.startswith(prefix)
|
|
206
|
+
and specifier.endswith(suffix)
|
|
207
|
+
and len(specifier) >= len(prefix) + len(suffix)
|
|
208
|
+
):
|
|
209
|
+
return specifier[len(prefix):len(specifier) - len(suffix)]
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def resolve_javascript_specifier(from_rel_path, specifier, file_index, module_resolution=None):
|
|
214
|
+
if not specifier:
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
if specifier.startswith("."):
|
|
218
|
+
from_dir = os.path.dirname(from_rel_path)
|
|
219
|
+
return _first_existing(os.path.join(from_dir, specifier.replace("/", os.sep)), file_index)
|
|
220
|
+
|
|
221
|
+
if not module_resolution:
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
# tsconfig/jsconfig "paths": the longest matching prefix wins, as in tsc.
|
|
225
|
+
matches = []
|
|
226
|
+
for pattern, targets in module_resolution.get("paths") or []:
|
|
227
|
+
captured = _match_path_pattern(pattern, specifier)
|
|
228
|
+
if captured is None:
|
|
229
|
+
continue
|
|
230
|
+
prefix_length = len(pattern.partition("*")[0])
|
|
231
|
+
matches.append((-prefix_length, pattern, captured, targets))
|
|
232
|
+
for _, _pattern, captured, targets in sorted(matches, key=lambda item: item[0]):
|
|
233
|
+
for target in targets:
|
|
234
|
+
substituted = target.replace("*", captured, 1)
|
|
235
|
+
hit = _first_existing(substituted.replace("/", os.sep), file_index)
|
|
236
|
+
if hit:
|
|
237
|
+
return hit
|
|
238
|
+
|
|
239
|
+
base_url = module_resolution.get("base_url")
|
|
240
|
+
if base_url is not None:
|
|
241
|
+
return _first_existing(os.path.join(base_url, specifier.replace("/", os.sep)), file_index)
|
|
242
|
+
return None
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# --- tsconfig / jsconfig loading -------------------------------------------
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _load_jsonc(path):
|
|
249
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
250
|
+
text = handle.read(512000)
|
|
251
|
+
text = strip_comments(text)
|
|
252
|
+
text = re.sub(r",(\s*[}\]])", r"\1", text)
|
|
253
|
+
data = json.loads(text)
|
|
254
|
+
return data if isinstance(data, dict) else {}
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _read_compiler_options(config_path, project_root, depth=0):
|
|
258
|
+
"""Return (base_url, paths, paths_dir) merged across relative `extends`.
|
|
259
|
+
|
|
260
|
+
As in tsc, `paths` targets resolve against `baseUrl` when one is set
|
|
261
|
+
anywhere in the chain, otherwise against the directory of the config
|
|
262
|
+
that declared `paths`.
|
|
263
|
+
"""
|
|
264
|
+
try:
|
|
265
|
+
data = _load_jsonc(config_path)
|
|
266
|
+
except (OSError, UnicodeDecodeError, ValueError):
|
|
267
|
+
return None, None, None
|
|
268
|
+
|
|
269
|
+
config_dir = os.path.dirname(config_path)
|
|
270
|
+
base_url = None
|
|
271
|
+
paths = None
|
|
272
|
+
paths_dir = None
|
|
273
|
+
|
|
274
|
+
extends = data.get("extends")
|
|
275
|
+
parents = extends if isinstance(extends, list) else [extends] if extends else []
|
|
276
|
+
for parent in parents:
|
|
277
|
+
if depth >= MAX_EXTENDS_DEPTH or not isinstance(parent, str) or not parent.startswith("."):
|
|
278
|
+
continue
|
|
279
|
+
parent_path = os.path.realpath(os.path.join(config_dir, parent))
|
|
280
|
+
if not parent_path.endswith(".json"):
|
|
281
|
+
parent_path += ".json"
|
|
282
|
+
if not _inside(parent_path, project_root) or not os.path.isfile(parent_path):
|
|
283
|
+
continue
|
|
284
|
+
parent_base, parent_paths, parent_paths_dir = _read_compiler_options(parent_path, project_root, depth + 1)
|
|
285
|
+
if parent_base is not None:
|
|
286
|
+
base_url = parent_base
|
|
287
|
+
if parent_paths is not None:
|
|
288
|
+
paths, paths_dir = parent_paths, parent_paths_dir
|
|
289
|
+
|
|
290
|
+
options = data.get("compilerOptions") or {}
|
|
291
|
+
if isinstance(options, dict):
|
|
292
|
+
if isinstance(options.get("baseUrl"), str):
|
|
293
|
+
base_url = os.path.normpath(os.path.join(config_dir, options["baseUrl"]))
|
|
294
|
+
if isinstance(options.get("paths"), dict):
|
|
295
|
+
paths, paths_dir = options["paths"], config_dir
|
|
296
|
+
return base_url, paths, paths_dir
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _inside(path, root):
|
|
300
|
+
path = os.path.realpath(path)
|
|
301
|
+
root = os.path.realpath(root)
|
|
302
|
+
return path == root or path.startswith(root + os.sep)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _to_project_rel(absolute, project_root):
|
|
306
|
+
rel = os.path.relpath(absolute, project_root)
|
|
307
|
+
return "" if rel == "." else rel
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def load_module_resolution(config_path, project_root):
|
|
311
|
+
"""Normalize a tsconfig/jsconfig into project-relative resolution rules."""
|
|
312
|
+
root = os.path.realpath(project_root)
|
|
313
|
+
base_url, paths, paths_dir = _read_compiler_options(os.path.realpath(config_path), root)
|
|
314
|
+
if base_url is None and not paths:
|
|
315
|
+
return None
|
|
316
|
+
paths_base = base_url if base_url is not None else paths_dir
|
|
317
|
+
resolution = {"config": _to_project_rel(os.path.realpath(config_path), root)}
|
|
318
|
+
if base_url is not None:
|
|
319
|
+
resolution["base_url"] = _to_project_rel(base_url, root)
|
|
320
|
+
rules = []
|
|
321
|
+
for pattern, targets in (paths or {}).items():
|
|
322
|
+
if not isinstance(pattern, str) or not isinstance(targets, list):
|
|
323
|
+
continue
|
|
324
|
+
normalized = [
|
|
325
|
+
_to_project_rel(os.path.normpath(os.path.join(paths_base, target)), root)
|
|
326
|
+
for target in targets
|
|
327
|
+
if isinstance(target, str)
|
|
328
|
+
]
|
|
329
|
+
if normalized:
|
|
330
|
+
rules.append([pattern, normalized])
|
|
331
|
+
resolution["paths"] = rules
|
|
332
|
+
return resolution
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def nearest_config(rel_path, project_root, cache):
|
|
336
|
+
"""Resolution rules from the closest tsconfig.json/jsconfig.json above the file.
|
|
337
|
+
|
|
338
|
+
Like tsc, the nearest config wins even when it declares no aliases; it
|
|
339
|
+
reaches a parent config only through `extends`. Returns None when no
|
|
340
|
+
config applies or it declares neither `baseUrl` nor `paths`.
|
|
341
|
+
"""
|
|
342
|
+
root = os.path.realpath(project_root)
|
|
343
|
+
directory = os.path.dirname(rel_path)
|
|
344
|
+
visited = []
|
|
345
|
+
result = None
|
|
346
|
+
while True:
|
|
347
|
+
if directory in cache:
|
|
348
|
+
result = cache[directory]
|
|
349
|
+
break
|
|
350
|
+
visited.append(directory)
|
|
351
|
+
absolute_dir = os.path.join(root, directory)
|
|
352
|
+
found = False
|
|
353
|
+
for name in CONFIG_FILENAMES:
|
|
354
|
+
candidate = os.path.join(absolute_dir, name)
|
|
355
|
+
if os.path.isfile(candidate) and not os.path.islink(candidate):
|
|
356
|
+
result = load_module_resolution(candidate, root)
|
|
357
|
+
found = True
|
|
358
|
+
break
|
|
359
|
+
if found or not directory:
|
|
360
|
+
break
|
|
361
|
+
directory = os.path.dirname(directory)
|
|
362
|
+
for item in visited:
|
|
363
|
+
cache[item] = result
|
|
364
|
+
return result
|
adre/parsers/jvm.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Java and Kotlin import parsing and resolution.
|
|
2
|
+
|
|
3
|
+
Imports name classes by fully qualified name (`com.acme.service.UserService`),
|
|
4
|
+
so resolution maps package + declared type/function names to files.
|
|
5
|
+
"""
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from adre.parsers.javascript import strip_comments
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
JVM_EXTENSIONS = {".java", ".kt", ".kts"}
|
|
13
|
+
|
|
14
|
+
PACKAGE_PATTERN = re.compile(r"^\s*package\s+([\w.`]+)\s*;?", re.M)
|
|
15
|
+
IMPORT_PATTERN = re.compile(r"^\s*import\s+(static\s+)?((?:[\w`]+\.)*[\w`]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*;?", re.M)
|
|
16
|
+
TYPE_PATTERN = re.compile(
|
|
17
|
+
r"^\s*(?:(?:public|private|protected|internal|abstract|final|sealed|open|data|enum|"
|
|
18
|
+
r"annotation|inner|static|value|strictfp|non-sealed)\s+)*"
|
|
19
|
+
r"(class|interface|enum|record|object|@interface)\s+([A-Za-z_]\w*)",
|
|
20
|
+
re.M,
|
|
21
|
+
)
|
|
22
|
+
TOP_LEVEL_FUNCTION_PATTERN = re.compile(r"^(?:(?:public|private|internal|inline|suspend)\s+)*fun\s+(?:<[^>]*>\s*)?([A-Za-z_]\w*)\s*\(", re.M)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def language_for_jvm(rel_path):
|
|
26
|
+
return "java" if rel_path.lower().endswith(".java") else "kotlin"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def parse_jvm_file(file_path, rel_path, max_bytes=512000):
|
|
30
|
+
record = {
|
|
31
|
+
"path": rel_path,
|
|
32
|
+
"language": language_for_jvm(rel_path),
|
|
33
|
+
"imports": [],
|
|
34
|
+
"import_details": [],
|
|
35
|
+
"symbols": [],
|
|
36
|
+
"parse_error": None,
|
|
37
|
+
"package": "",
|
|
38
|
+
}
|
|
39
|
+
try:
|
|
40
|
+
with open(file_path, "r", encoding="utf-8") as handle:
|
|
41
|
+
source = handle.read(max_bytes + 1)
|
|
42
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
43
|
+
record["parse_error"] = str(exc)
|
|
44
|
+
return record
|
|
45
|
+
if len(source.encode("utf-8", errors="ignore")) > max_bytes:
|
|
46
|
+
record["parse_error"] = "file exceeds analysis size limit"
|
|
47
|
+
return record
|
|
48
|
+
|
|
49
|
+
code = strip_comments(source)
|
|
50
|
+
package = PACKAGE_PATTERN.search(code)
|
|
51
|
+
if package:
|
|
52
|
+
record["package"] = package.group(1).replace("`", "")
|
|
53
|
+
|
|
54
|
+
for match in IMPORT_PATTERN.finditer(code):
|
|
55
|
+
name = match.group(2).replace("`", "")
|
|
56
|
+
line = code.count("\n", 0, match.start(2)) + 1
|
|
57
|
+
record["imports"].append(name)
|
|
58
|
+
record["import_details"].append({
|
|
59
|
+
"module": name,
|
|
60
|
+
"names": [],
|
|
61
|
+
"line": line,
|
|
62
|
+
"level": 0,
|
|
63
|
+
"kind": "static" if match.group(1) else "import",
|
|
64
|
+
"raw": match.group(0).strip()[:200],
|
|
65
|
+
"type_only": False,
|
|
66
|
+
"deferred": False,
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
for match in TYPE_PATTERN.finditer(code):
|
|
70
|
+
record["symbols"].append({
|
|
71
|
+
"name": match.group(2),
|
|
72
|
+
"kind": "class",
|
|
73
|
+
"line": code.count("\n", 0, match.start(2)) + 1,
|
|
74
|
+
"loc": 1,
|
|
75
|
+
"complexity": 0,
|
|
76
|
+
})
|
|
77
|
+
if record["language"] == "kotlin":
|
|
78
|
+
for match in TOP_LEVEL_FUNCTION_PATTERN.finditer(code):
|
|
79
|
+
record["symbols"].append({
|
|
80
|
+
"name": match.group(1),
|
|
81
|
+
"kind": "function",
|
|
82
|
+
"line": code.count("\n", 0, match.start(1)) + 1,
|
|
83
|
+
"loc": 1,
|
|
84
|
+
"complexity": 0,
|
|
85
|
+
})
|
|
86
|
+
return record
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def is_jvm_file(path):
|
|
90
|
+
return os.path.splitext(path)[1].lower() in JVM_EXTENSIONS
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def build_jvm_index(records):
|
|
94
|
+
"""Return (fqn -> file, package -> [files]) for JVM source records."""
|
|
95
|
+
by_name = {}
|
|
96
|
+
by_package = {}
|
|
97
|
+
for path, record in records.items():
|
|
98
|
+
if not is_jvm_file(path):
|
|
99
|
+
continue
|
|
100
|
+
package = record.get("package") or ""
|
|
101
|
+
by_package.setdefault(package, []).append(path)
|
|
102
|
+
stem = os.path.splitext(os.path.basename(path))[0]
|
|
103
|
+
names = [stem] + [symbol.get("name") for symbol in record.get("symbols") or [] if symbol.get("name")]
|
|
104
|
+
for name in names:
|
|
105
|
+
fqn = "{0}.{1}".format(package, name) if package else name
|
|
106
|
+
by_name.setdefault(fqn, path)
|
|
107
|
+
for files in by_package.values():
|
|
108
|
+
files.sort()
|
|
109
|
+
return by_name, by_package
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def resolve_jvm_import(detail, by_name, by_package):
|
|
113
|
+
name = (detail.get("module") or "").strip()
|
|
114
|
+
if not name:
|
|
115
|
+
return []
|
|
116
|
+
if name.endswith(".*"):
|
|
117
|
+
owner = name[:-2]
|
|
118
|
+
if owner in by_name: # import static a.b.Type.*
|
|
119
|
+
return [by_name[owner]]
|
|
120
|
+
return list(by_package.get(owner) or [])
|
|
121
|
+
parts = name.split(".")
|
|
122
|
+
# Exact class, then the enclosing type for static members or nested classes.
|
|
123
|
+
for end in range(len(parts), 1, -1):
|
|
124
|
+
candidate = ".".join(parts[:end])
|
|
125
|
+
if candidate in by_name:
|
|
126
|
+
return [by_name[candidate]]
|
|
127
|
+
return []
|
adre/parsers/python.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _read_source(file_path, max_bytes):
|
|
6
|
+
with open(file_path, "r", encoding="utf-8") as handle:
|
|
7
|
+
return handle.read(max_bytes + 1)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def parse_python_file(file_path, rel_path, max_bytes=512000):
|
|
11
|
+
record = {
|
|
12
|
+
"path": rel_path,
|
|
13
|
+
"language": "python",
|
|
14
|
+
"imports": [],
|
|
15
|
+
"import_details": [],
|
|
16
|
+
"symbols": [],
|
|
17
|
+
"parse_error": None,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
source = _read_source(file_path, max_bytes)
|
|
22
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
23
|
+
record["parse_error"] = str(exc)
|
|
24
|
+
return record
|
|
25
|
+
|
|
26
|
+
if len(source.encode("utf-8", errors="ignore")) > max_bytes:
|
|
27
|
+
record["parse_error"] = "file exceeds analysis size limit"
|
|
28
|
+
return record
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
tree = ast.parse(source, filename=file_path)
|
|
32
|
+
except SyntaxError as exc:
|
|
33
|
+
record["parse_error"] = "syntax error: {0}".format(exc.msg or "invalid Python")
|
|
34
|
+
return record
|
|
35
|
+
except (ValueError, RecursionError, MemoryError) as exc:
|
|
36
|
+
record["parse_error"] = "could not parse: {0}".format(exc.__class__.__name__)
|
|
37
|
+
return record
|
|
38
|
+
|
|
39
|
+
for node, type_only, deferred in _iter_imports(tree):
|
|
40
|
+
flags = {"type_only": type_only, "deferred": deferred}
|
|
41
|
+
if isinstance(node, ast.Import):
|
|
42
|
+
for alias in node.names:
|
|
43
|
+
record["import_details"].append(dict({
|
|
44
|
+
"module": alias.name,
|
|
45
|
+
"names": [alias.asname or alias.name],
|
|
46
|
+
"line": getattr(node, "lineno", 1),
|
|
47
|
+
"level": 0,
|
|
48
|
+
"kind": "import",
|
|
49
|
+
"raw": "import {0}".format(alias.name),
|
|
50
|
+
}, **flags))
|
|
51
|
+
record["imports"].append(alias.name)
|
|
52
|
+
else:
|
|
53
|
+
module = node.module or ""
|
|
54
|
+
names = [alias.name for alias in node.names]
|
|
55
|
+
record["import_details"].append(dict({
|
|
56
|
+
"module": module,
|
|
57
|
+
"names": names,
|
|
58
|
+
"line": getattr(node, "lineno", 1),
|
|
59
|
+
"level": node.level or 0,
|
|
60
|
+
"kind": "from",
|
|
61
|
+
"raw": "from {0}{1} import {2}".format(
|
|
62
|
+
"." * (node.level or 0),
|
|
63
|
+
module,
|
|
64
|
+
", ".join(names),
|
|
65
|
+
),
|
|
66
|
+
}, **flags))
|
|
67
|
+
if module or node.level:
|
|
68
|
+
record["imports"].append(module or ".")
|
|
69
|
+
|
|
70
|
+
for node in getattr(tree, "body", []):
|
|
71
|
+
if isinstance(node, ast.ClassDef):
|
|
72
|
+
record["symbols"].append({
|
|
73
|
+
"name": node.name,
|
|
74
|
+
"kind": "class",
|
|
75
|
+
"line": getattr(node, "lineno", 1),
|
|
76
|
+
"loc": _node_loc(node),
|
|
77
|
+
"complexity": _complexity(node),
|
|
78
|
+
})
|
|
79
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
80
|
+
record["symbols"].append({
|
|
81
|
+
"name": node.name,
|
|
82
|
+
"kind": "function",
|
|
83
|
+
"line": getattr(node, "lineno", 1),
|
|
84
|
+
"loc": _node_loc(node),
|
|
85
|
+
"complexity": _complexity(node),
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
return record
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _is_type_checking_test(test):
|
|
92
|
+
if isinstance(test, ast.Name):
|
|
93
|
+
return test.id == "TYPE_CHECKING"
|
|
94
|
+
if isinstance(test, ast.Attribute):
|
|
95
|
+
return test.attr == "TYPE_CHECKING"
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _iter_imports(tree):
|
|
100
|
+
"""Yield (import_node, type_only, deferred) without recursion.
|
|
101
|
+
|
|
102
|
+
type_only: inside an `if TYPE_CHECKING:` block, never executed at runtime.
|
|
103
|
+
deferred: inside a function body, executed only when the function runs,
|
|
104
|
+
so it cannot take part in an import-time cycle.
|
|
105
|
+
"""
|
|
106
|
+
stack = [(tree, False, False)]
|
|
107
|
+
while stack:
|
|
108
|
+
node, type_only, deferred = stack.pop()
|
|
109
|
+
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
110
|
+
yield node, type_only, deferred
|
|
111
|
+
continue
|
|
112
|
+
if isinstance(node, ast.If) and _is_type_checking_test(node.test):
|
|
113
|
+
children = [(child, True, deferred) for child in node.body]
|
|
114
|
+
children += [(child, type_only, deferred) for child in node.orelse]
|
|
115
|
+
else:
|
|
116
|
+
in_function = deferred or isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda))
|
|
117
|
+
children = [(child, type_only, in_function) for child in ast.iter_child_nodes(node)]
|
|
118
|
+
stack.extend(reversed(children))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _node_loc(node):
|
|
122
|
+
start = getattr(node, "lineno", 1)
|
|
123
|
+
end = getattr(node, "end_lineno", start)
|
|
124
|
+
return max(1, end - start + 1)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _complexity(node):
|
|
128
|
+
count = 0
|
|
129
|
+
for child in ast.walk(node):
|
|
130
|
+
if isinstance(child, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ast.With, ast.BoolOp)):
|
|
131
|
+
count += 1
|
|
132
|
+
return count
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def python_module_from_path(rel_path):
|
|
136
|
+
if rel_path.endswith("__init__.py"):
|
|
137
|
+
module_path = os.path.dirname(rel_path)
|
|
138
|
+
else:
|
|
139
|
+
module_path = rel_path[:-3] if rel_path.endswith(".py") else rel_path
|
|
140
|
+
return module_path.replace(os.sep, ".").replace("/", ".")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def absolute_python_module(from_rel_path, module, level):
|
|
144
|
+
if not level:
|
|
145
|
+
return module
|
|
146
|
+
package_parts = [part for part in os.path.dirname(from_rel_path).replace("\\", "/").split("/") if part]
|
|
147
|
+
drop = level - 1
|
|
148
|
+
if drop > len(package_parts):
|
|
149
|
+
return module
|
|
150
|
+
base = package_parts[:len(package_parts) - drop]
|
|
151
|
+
if module:
|
|
152
|
+
return ".".join(base + module.split("."))
|
|
153
|
+
return ".".join(base)
|
adre/reports/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|