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
adre/core/declared.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Declared (intended) architecture: `.adre/architecture.json`.
|
|
2
|
+
|
|
3
|
+
Inference covers repositories that already show a clear structure. Teams that
|
|
4
|
+
know the architecture they want can state it, and declared rules are checked
|
|
5
|
+
whether or not inference found enough structure:
|
|
6
|
+
|
|
7
|
+
{
|
|
8
|
+
"layers": [
|
|
9
|
+
{"name": "presentation", "paths": ["controllers/*", "routes/*"]},
|
|
10
|
+
{"name": "application", "paths": ["services/*"]},
|
|
11
|
+
{"name": "data", "paths": ["repositories/*"]}
|
|
12
|
+
],
|
|
13
|
+
"strict": false,
|
|
14
|
+
"forbidden": [
|
|
15
|
+
{"from": "controllers/*", "to": "repositories/*", "reason": "Go through a service."}
|
|
16
|
+
]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
Layers are listed top to bottom. A layer may import any layer below it, never
|
|
20
|
+
one above it, directly or through a chain of other modules. With
|
|
21
|
+
`"strict": true` a layer may only import the layer directly below it.
|
|
22
|
+
`forbidden` lists extra dependencies that are never allowed. Paths are glob
|
|
23
|
+
patterns over project-relative paths (`*` also matches `/`); a file belongs to
|
|
24
|
+
the first layer whose pattern matches it.
|
|
25
|
+
|
|
26
|
+
Only dependencies that are new relative to the reference (the PR base tree, or
|
|
27
|
+
the saved baseline) are reported, like every other ADRE finding.
|
|
28
|
+
"""
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
from collections import deque
|
|
32
|
+
from fnmatch import fnmatchcase
|
|
33
|
+
|
|
34
|
+
from adre.core.config import BASELINE_DIRNAME
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
DECLARED_FILENAME = "architecture.json"
|
|
38
|
+
MAX_INDIRECT_EDGES = 500
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def declared_rel_path():
|
|
42
|
+
return "{0}/{1}".format(BASELINE_DIRNAME, DECLARED_FILENAME)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def declared_path(project_root):
|
|
46
|
+
return os.path.join(os.path.realpath(project_root), BASELINE_DIRNAME, DECLARED_FILENAME)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _patterns(value, where):
|
|
50
|
+
if isinstance(value, str):
|
|
51
|
+
value = [value]
|
|
52
|
+
if not isinstance(value, list) or not value or not all(isinstance(item, str) and item.strip() for item in value):
|
|
53
|
+
raise ValueError("{0} needs one or more path patterns.".format(where))
|
|
54
|
+
return [item.strip().replace("\\", "/") for item in value]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_declared(data, source=DECLARED_FILENAME):
|
|
58
|
+
if not isinstance(data, dict):
|
|
59
|
+
raise ValueError("{0} must be a JSON object.".format(source))
|
|
60
|
+
layers = []
|
|
61
|
+
names = set()
|
|
62
|
+
for index, layer in enumerate(data.get("layers") or [], start=1):
|
|
63
|
+
where = "{0} layer {1}".format(source, index)
|
|
64
|
+
if not isinstance(layer, dict) or not isinstance(layer.get("name"), str) or not layer["name"].strip():
|
|
65
|
+
raise ValueError('{0} needs a "name".'.format(where))
|
|
66
|
+
name = layer["name"].strip()
|
|
67
|
+
if name in names:
|
|
68
|
+
raise ValueError("{0}: layer name {1!r} is used twice.".format(where, name))
|
|
69
|
+
names.add(name)
|
|
70
|
+
layers.append({"name": name, "paths": _patterns(layer.get("paths"), where), "rank": index - 1})
|
|
71
|
+
forbidden = []
|
|
72
|
+
for index, rule in enumerate(data.get("forbidden") or [], start=1):
|
|
73
|
+
where = "{0} forbidden rule {1}".format(source, index)
|
|
74
|
+
if not isinstance(rule, dict):
|
|
75
|
+
raise ValueError("{0} must be an object.".format(where))
|
|
76
|
+
forbidden.append({
|
|
77
|
+
"from": _patterns(rule.get("from"), where + ' "from"'),
|
|
78
|
+
"to": _patterns(rule.get("to"), where + ' "to"'),
|
|
79
|
+
"reason": str(rule.get("reason") or "").strip(),
|
|
80
|
+
"index": index,
|
|
81
|
+
})
|
|
82
|
+
if not layers and not forbidden:
|
|
83
|
+
raise ValueError('{0} declares no "layers" and no "forbidden" rules.'.format(source))
|
|
84
|
+
strict = data.get("strict", False)
|
|
85
|
+
if not isinstance(strict, bool):
|
|
86
|
+
raise ValueError('{0}: "strict" must be true or false.'.format(source))
|
|
87
|
+
return {"layers": layers, "forbidden": forbidden, "strict": strict}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def load_declared_text(text, source):
|
|
91
|
+
try:
|
|
92
|
+
data = json.loads(text)
|
|
93
|
+
except json.JSONDecodeError as exc:
|
|
94
|
+
raise ValueError("{0} is not valid JSON: {1}".format(source, exc))
|
|
95
|
+
return parse_declared(data, source=source)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def load_declared(project_root):
|
|
99
|
+
"""Declared rules from the working tree; None when the file is absent."""
|
|
100
|
+
path = declared_path(project_root)
|
|
101
|
+
if not os.path.exists(path):
|
|
102
|
+
return None
|
|
103
|
+
if os.path.islink(path):
|
|
104
|
+
raise ValueError("{0} must not be a symlink.".format(declared_rel_path()))
|
|
105
|
+
try:
|
|
106
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
107
|
+
text = handle.read()
|
|
108
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
109
|
+
raise ValueError("{0} could not be read: {1}".format(declared_rel_path(), exc))
|
|
110
|
+
return load_declared_text(text, declared_rel_path())
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _matches(path, patterns):
|
|
114
|
+
return any(fnmatchcase(path, pattern) for pattern in patterns)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def layer_of(path, declared):
|
|
118
|
+
for layer in declared["layers"]:
|
|
119
|
+
if _matches(path, layer["paths"]):
|
|
120
|
+
return layer
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _adjacency(edges):
|
|
125
|
+
graph = {}
|
|
126
|
+
for source, target in edges:
|
|
127
|
+
graph.setdefault(source, set()).add(target)
|
|
128
|
+
return graph
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _bfs(graph, start, reverse=False):
|
|
132
|
+
"""Return {node: parent} for nodes reachable from start (start maps to None)."""
|
|
133
|
+
parents = {start: None}
|
|
134
|
+
queue = deque([start])
|
|
135
|
+
while queue:
|
|
136
|
+
node = queue.popleft()
|
|
137
|
+
for neighbor in sorted(graph.get(node, ())):
|
|
138
|
+
if neighbor not in parents:
|
|
139
|
+
parents[neighbor] = node
|
|
140
|
+
queue.append(neighbor)
|
|
141
|
+
return parents
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _path_to(parents, node):
|
|
145
|
+
path = [node]
|
|
146
|
+
while parents.get(path[-1]) is not None:
|
|
147
|
+
path.append(parents[path[-1]])
|
|
148
|
+
return path
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _reachable(graph, source, target):
|
|
152
|
+
if source == target:
|
|
153
|
+
return True
|
|
154
|
+
seen = {source}
|
|
155
|
+
queue = deque([source])
|
|
156
|
+
while queue:
|
|
157
|
+
node = queue.popleft()
|
|
158
|
+
for neighbor in graph.get(node, ()):
|
|
159
|
+
if neighbor == target:
|
|
160
|
+
return True
|
|
161
|
+
if neighbor not in seen:
|
|
162
|
+
seen.add(neighbor)
|
|
163
|
+
queue.append(neighbor)
|
|
164
|
+
return False
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _finding(issue_type, source, target, changed, established, reason, evidence, line=None, path=None):
|
|
168
|
+
item = {
|
|
169
|
+
"issue_type": issue_type,
|
|
170
|
+
"title": "Architectural drift",
|
|
171
|
+
"severity": "high",
|
|
172
|
+
"kind": "deterministic",
|
|
173
|
+
"classification": "declared",
|
|
174
|
+
"confidence": 1.0,
|
|
175
|
+
"file": source,
|
|
176
|
+
"imported": target,
|
|
177
|
+
"changed": changed,
|
|
178
|
+
"established": established,
|
|
179
|
+
"established_pattern": established,
|
|
180
|
+
"reason": reason,
|
|
181
|
+
"problem": reason,
|
|
182
|
+
"why_it_matters": "The declared architecture in {0} does not allow this dependency.".format(declared_rel_path()),
|
|
183
|
+
"evidence": evidence,
|
|
184
|
+
"affected_files": list(path or [source, target]),
|
|
185
|
+
"line": line,
|
|
186
|
+
}
|
|
187
|
+
return item
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _layer_order(declared):
|
|
191
|
+
return " -> ".join(layer["name"] for layer in declared["layers"])
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def check_declared(declared, current_graph, prior_edges, line_for=None):
|
|
195
|
+
"""Findings for new dependencies that break the declared architecture.
|
|
196
|
+
|
|
197
|
+
current_graph: {file: iterable of files} for the current tree.
|
|
198
|
+
prior_edges: set of (source, target) that already existed (renames applied).
|
|
199
|
+
line_for: optional callable (source, target) -> import line.
|
|
200
|
+
"""
|
|
201
|
+
if not declared:
|
|
202
|
+
return []
|
|
203
|
+
line_for = line_for or (lambda source, target: None)
|
|
204
|
+
current_edges = {
|
|
205
|
+
(source, target)
|
|
206
|
+
for source, targets in (current_graph or {}).items()
|
|
207
|
+
for target in targets
|
|
208
|
+
if source != target
|
|
209
|
+
}
|
|
210
|
+
new_edges = sorted(current_edges - set(prior_edges or ()))
|
|
211
|
+
order = _layer_order(declared)
|
|
212
|
+
findings = []
|
|
213
|
+
direct_keys = set()
|
|
214
|
+
|
|
215
|
+
for source, target in new_edges:
|
|
216
|
+
src_layer = layer_of(source, declared)
|
|
217
|
+
dst_layer = layer_of(target, declared)
|
|
218
|
+
if src_layer and dst_layer and src_layer["name"] != dst_layer["name"]:
|
|
219
|
+
reason = None
|
|
220
|
+
if dst_layer["rank"] < src_layer["rank"]:
|
|
221
|
+
reason = "{0} ({1}) imports {2} ({3}), a layer above it in the declared order {4}.".format(
|
|
222
|
+
source, src_layer["name"], target, dst_layer["name"], order
|
|
223
|
+
)
|
|
224
|
+
elif declared["strict"] and dst_layer["rank"] > src_layer["rank"] + 1:
|
|
225
|
+
reason = "{0} ({1}) skips a layer by importing {2} ({3}); strict layering only allows the next layer down in {4}.".format(
|
|
226
|
+
source, src_layer["name"], target, dst_layer["name"], order
|
|
227
|
+
)
|
|
228
|
+
if reason:
|
|
229
|
+
direct_keys.add((source, target))
|
|
230
|
+
findings.append(_finding(
|
|
231
|
+
"declared_violation", source, target,
|
|
232
|
+
"{0} -> {1}".format(source, target),
|
|
233
|
+
order, reason,
|
|
234
|
+
["{0} -> {1}".format(source, target), "Declared layers: {0}".format(order)],
|
|
235
|
+
line=line_for(source, target),
|
|
236
|
+
))
|
|
237
|
+
continue
|
|
238
|
+
for rule in declared["forbidden"]:
|
|
239
|
+
if _matches(source, rule["from"]) and _matches(target, rule["to"]):
|
|
240
|
+
direct_keys.add((source, target))
|
|
241
|
+
reason = rule["reason"] or "{0} -> {1} matches a forbidden dependency rule.".format(source, target)
|
|
242
|
+
findings.append(_finding(
|
|
243
|
+
"declared_violation", source, target,
|
|
244
|
+
"{0} -> {1}".format(source, target),
|
|
245
|
+
"forbidden: {0} -> {1}".format(", ".join(rule["from"]), ", ".join(rule["to"])),
|
|
246
|
+
reason,
|
|
247
|
+
["{0} -> {1}".format(source, target),
|
|
248
|
+
"{0} forbidden rule {1}".format(declared_rel_path(), rule["index"])],
|
|
249
|
+
line=line_for(source, target),
|
|
250
|
+
))
|
|
251
|
+
break
|
|
252
|
+
|
|
253
|
+
findings.extend(_indirect_findings(declared, current_edges, new_edges, prior_edges, direct_keys, line_for, order))
|
|
254
|
+
return findings
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _indirect_findings(declared, current_edges, new_edges, prior_edges, direct_keys, line_for, order):
|
|
258
|
+
"""New chains from a lower declared layer up to a higher one.
|
|
259
|
+
|
|
260
|
+
For each new edge u -> v, look for a lower-layer file a that reaches u and
|
|
261
|
+
a higher-layer file d reachable from v, where a could not reach d before.
|
|
262
|
+
One finding (the shortest such path) per new edge.
|
|
263
|
+
"""
|
|
264
|
+
if not declared["layers"] or not new_edges or len(new_edges) > MAX_INDIRECT_EDGES:
|
|
265
|
+
return []
|
|
266
|
+
forward = _adjacency(current_edges)
|
|
267
|
+
backward = _adjacency((target, source) for source, target in current_edges)
|
|
268
|
+
prior = _adjacency(prior_edges or ())
|
|
269
|
+
findings = []
|
|
270
|
+
reported_pairs = set()
|
|
271
|
+
for source, target in new_edges:
|
|
272
|
+
ancestors = _bfs(backward, source)
|
|
273
|
+
descendants = _bfs(forward, target)
|
|
274
|
+
best = None
|
|
275
|
+
for low in ancestors:
|
|
276
|
+
low_layer = layer_of(low, declared)
|
|
277
|
+
if not low_layer:
|
|
278
|
+
continue
|
|
279
|
+
for high in descendants:
|
|
280
|
+
high_layer = layer_of(high, declared)
|
|
281
|
+
if not high_layer or high_layer["rank"] >= low_layer["rank"]:
|
|
282
|
+
continue
|
|
283
|
+
if (low, high) in direct_keys or (low, high) in reported_pairs:
|
|
284
|
+
continue
|
|
285
|
+
if low == source and high == target:
|
|
286
|
+
continue # a direct upward edge is reported as declared_violation
|
|
287
|
+
path = _path_to(ancestors, low) # low ... source (forward order)
|
|
288
|
+
path += list(reversed(_path_to(descendants, high))) # target ... high
|
|
289
|
+
if best is not None and len(path) >= len(best[2]):
|
|
290
|
+
continue
|
|
291
|
+
if _reachable(prior, low, high):
|
|
292
|
+
continue
|
|
293
|
+
best = (low, high, path, low_layer, high_layer)
|
|
294
|
+
if not best:
|
|
295
|
+
continue
|
|
296
|
+
low, high, path, low_layer, high_layer = best
|
|
297
|
+
reported_pairs.add((low, high))
|
|
298
|
+
chain = " -> ".join(path)
|
|
299
|
+
finding = _finding(
|
|
300
|
+
"indirect_violation", source, target, chain, order,
|
|
301
|
+
"{0} ({1}) now reaches {2} ({3}) through {4} -> {5}; the declared order {6} does not allow a lower layer to depend on a higher one, even indirectly.".format(
|
|
302
|
+
low, low_layer["name"], high, high_layer["name"], source, target, order
|
|
303
|
+
),
|
|
304
|
+
[chain, "New import: {0} -> {1}".format(source, target)],
|
|
305
|
+
line=line_for(source, target),
|
|
306
|
+
path=path,
|
|
307
|
+
)
|
|
308
|
+
# The finding sits on the new import; chain_from/chain_to name the
|
|
309
|
+
# layers that are now connected the wrong way.
|
|
310
|
+
finding["chain_from"] = low
|
|
311
|
+
finding["chain_to"] = high
|
|
312
|
+
findings.append(finding)
|
|
313
|
+
return findings
|