adre-cli 0.1.0__tar.gz → 0.2.0__tar.gz
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_cli-0.1.0 → adre_cli-0.2.0}/PKG-INFO +17 -6
- {adre_cli-0.1.0 → adre_cli-0.2.0}/README.md +16 -5
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/__init__.py +1 -1
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/analyzers/architecture.py +3 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/cli.py +104 -5
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/accepted.py +74 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/config.py +16 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/declared.py +120 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/github_check.py +73 -5
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/incremental.py +5 -1
- adre_cli-0.2.0/adre/core/pr_comment.py +293 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/pr_review.py +63 -1
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/review.py +16 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/sarif.py +22 -2
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/scope.py +28 -0
- adre_cli-0.2.0/adre/core/severity.py +57 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/parsers/__init__.py +30 -4
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/web.py +614 -7
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre_cli.egg-info/PKG-INFO +17 -6
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre_cli.egg-info/SOURCES.txt +5 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_accepted.py +68 -1
- adre_cli-0.2.0/tests/test_fail_on.py +151 -0
- adre_cli-0.2.0/tests/test_file_limit.py +164 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_gaps.py +69 -1
- adre_cli-0.2.0/tests/test_pr_comment.py +215 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_web.py +228 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/LICENSE +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/analyzers/__init__.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/analyzers/findings.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/analyzers/inference.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/__init__.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/adaptive.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/baseline.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/decision_engine.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/evolution_intelligence.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/explainer.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/git_intelligence.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/layers.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/pr_intelligence.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/prioritization.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/project.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/refactor_intelligence.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/repositories.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/rules_shared.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/snapshots.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/core/stability_intelligence.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/graph/__init__.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/graph/dependencies.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/parsers/go.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/parsers/javascript.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/parsers/jvm.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/parsers/python.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/reports/__init__.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/reports/architecture.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre/rules.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre_cli.egg-info/dependency_links.txt +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre_cli.egg-info/entry_points.txt +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre_cli.egg-info/requires.txt +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/adre_cli.egg-info/top_level.txt +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/pyproject.toml +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/setup.cfg +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_architecture.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_baseline.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_ci_outputs.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_cycles.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_incremental.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_packaging.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_pr_review.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_realistic.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_recall.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_relationships.py +0 -0
- {adre_cli-0.1.0 → adre_cli-0.2.0}/tests/test_resolution.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: adre-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Architecture Drift Review Engine: learn a repository's architecture and flag pull requests that drift from it.
|
|
5
5
|
License: Apache-2.0
|
|
6
6
|
Project-URL: Homepage, https://github.com/christiangebru/architect-reviewer
|
|
@@ -87,7 +87,7 @@ pip install adre-cli # CLI only, no dependencies
|
|
|
87
87
|
pip install "adre-cli[web]" # plus the local web UI
|
|
88
88
|
```
|
|
89
89
|
|
|
90
|
-
|
|
90
|
+
To install an unreleased version from GitHub: `pip install "git+https://github.com/christiangebru/architect-reviewer@main"`.
|
|
91
91
|
|
|
92
92
|
This installs the `adre` command (the package is `adre-cli` because `adre` is taken on PyPI). From a source checkout, `./bin/adre` runs the same CLI without installing anything.
|
|
93
93
|
|
|
@@ -121,7 +121,7 @@ Start the local web UI (needs the `web` extra; binds to 127.0.0.1 by default):
|
|
|
121
121
|
adre web --port 8000
|
|
122
122
|
```
|
|
123
123
|
|
|
124
|
-
The web UI gives the same answers as the CLI: **Review against baseline** runs exactly what `adre review` runs (baseline, declared rules, accepted and stale exceptions), and **Review a branch** runs the same pull-request review as the GitHub Action for the checked-out branch against a base you choose.
|
|
124
|
+
The web UI gives the same answers as the CLI: **Review against baseline** runs exactly what `adre review` runs (baseline, declared rules, accepted and stale exceptions), and **Review a branch** runs the same pull-request review as the GitHub Action for the checked-out branch against a base you choose. On either page, **Accept with reason** records an intentional crossing in `.adre/accepted.json` (commit it so CI accepts it too). New repositories get a **Get started** checklist on the dashboard: save the baseline, commit it, review, and add the GitHub Action. The **Rules** page edits `.adre/architecture.json` visually: it starts from the layers ADRE found, lets you reorder, rename and add layers, turn on strict layering and add forbidden dependencies, and previews which files each layer claims and which current dependencies would break the rules before you save.
|
|
125
125
|
|
|
126
126
|
It only answers on localhost. Requests with another `Host` header or that the browser marks as cross-site are refused, and every action that changes something (saving a baseline, cloning or registering a repository, pinning, opening your editor) is a POST carrying a per-process token, so other websites cannot trigger them. Binding to another interface with `--host` prints a warning.
|
|
127
127
|
|
|
@@ -136,10 +136,15 @@ Statuses:
|
|
|
136
136
|
|
|
137
137
|
- `PASS` (exit 0) — no new drift versus the accepted baseline
|
|
138
138
|
- `DRIFT` (exit 2) — new architectural drift in the PR
|
|
139
|
+
- `INCOMPLETE` (exit 4) — the PR changes a source file that was not analyzed because the project has more source files than the file limit (see below)
|
|
139
140
|
- `BASELINE_REQUIRED` (exit 3) — no `.adre/baseline.json` on the base ref
|
|
140
141
|
- `BASELINE_INVALID` (exit 1) — baseline could not be loaded
|
|
141
142
|
- `ERROR` (exit 1) — git or analysis failure
|
|
142
143
|
|
|
144
|
+
**Which findings fail.** By default every finding fails the review. Set a threshold with `--fail-on critical|high|medium|low|none` (on `review`, `pr-review`, `pr-check` and `web`), the `ADRE_FAIL_ON` environment variable, or the action's `fail-on` input. Findings below it are still reported, as warnings (job summary, `::warning` annotations, SARIF level `note`, `warnings` in JSON), but do not fail. Severities: a new cycle is `critical`; layer skips, reversed layer dependencies, repository bypasses and declared-rule violations are `high`; an unexpected (inferred) dependency is `medium`. `--fail-on high` therefore keeps every proven violation blocking and turns inferred findings into warnings; `none` is an advisory mode for the first weeks of adoption.
|
|
145
|
+
|
|
146
|
+
**File limit.** ADRE analyzes at most 5,000 source files by default, in a stable (sorted) order. When a project has more, every output says how many files were left out, and a pull request that changes one of them gets `INCOMPLETE` instead of `PASS`. Raise the limit with `--max-files N` (any command), the `ADRE_MAX_FILES` environment variable, or the action's `max-files` input; `0` means no limit.
|
|
147
|
+
|
|
143
148
|
`pr-review` uses the baseline for the accepted architecture model (layers, directions, established paths), and analyzes the base commit in a throwaway clone to decide what is new. Only dependencies, cycles, and database imports that the PR adds relative to the base tree are reported. As a result:
|
|
144
149
|
|
|
145
150
|
- problems that already exist on the base branch are not blamed on the PR, even if they were merged after the baseline was saved
|
|
@@ -160,6 +165,7 @@ on:
|
|
|
160
165
|
|
|
161
166
|
permissions:
|
|
162
167
|
contents: read
|
|
168
|
+
pull-requests: write # lets ADRE keep one explanatory comment on the PR
|
|
163
169
|
|
|
164
170
|
jobs:
|
|
165
171
|
drift:
|
|
@@ -168,12 +174,12 @@ jobs:
|
|
|
168
174
|
- uses: actions/checkout@v4
|
|
169
175
|
with:
|
|
170
176
|
fetch-depth: 0 # the base commit and merge base must exist
|
|
171
|
-
- uses: christiangebru/architect-reviewer@v0.
|
|
177
|
+
- uses: christiangebru/architect-reviewer@v0.2.0 # or @v0 for the latest 0.x, or a commit SHA
|
|
172
178
|
with:
|
|
173
179
|
path: . # project directory inside the repository
|
|
174
180
|
```
|
|
175
181
|
|
|
176
|
-
The action compares the checked-out PR tree with the base commit, using `.adre/baseline.json` from the base commit as the accepted architecture, and fails the job on new drift. It writes the check summary to the job summary, adds an inline annotation on each finding (repository-relative paths, so projects in subdirectories work), and sets outputs `status`, `drift-count`, `accepted-count` and `sarif-file`.
|
|
182
|
+
The action compares the checked-out PR tree with the base commit, using `.adre/baseline.json` from the base commit as the accepted architecture, and fails the job on new drift. It writes the check summary to the job summary, adds an inline annotation on each finding (repository-relative paths, so projects in subdirectories work), and sets outputs `status`, `drift-count`, `warning-count`, `accepted-count` and `sarif-file`.
|
|
177
183
|
|
|
178
184
|
| Input | Default | |
|
|
179
185
|
|---|---|---|
|
|
@@ -182,13 +188,18 @@ The action compares the checked-out PR tree with the base commit, using `.adre/b
|
|
|
182
188
|
| `head` | `github.sha` | Checked-out commit |
|
|
183
189
|
| `baseline` | base commit's `.adre/baseline.json` | Baseline file |
|
|
184
190
|
| `sarif-file` | (none) | Also write SARIF 2.1.0 here |
|
|
191
|
+
| `max-files` | `5000` | Most source files to analyze; `0` = no limit |
|
|
192
|
+
| `comment` | `true` | Keep one ADRE comment on the PR, updated on every push; `false` to turn off |
|
|
193
|
+
| `fail-on` | `low` | Lowest severity that fails: `critical`, `high`, `medium`, `low`, or `none` (report only) |
|
|
185
194
|
| `python-version` | `3.12` | Python used to run ADRE |
|
|
186
195
|
| `setup-python` | `true` | `false` uses the runner's Python |
|
|
187
196
|
|
|
197
|
+
**PR comment.** With `pull-requests: write`, the action keeps a single comment on the pull request and edits it on every push instead of adding new ones. Each finding is explained in plain language (what happened, why it matters, how to fix it) with a ready-to-paste `.adre/accepted.json` entry for intentional crossings; warnings, accepted and stale exceptions are folded away. A clean PR gets no comment; a PR whose findings were fixed sees the comment flip to passed. Without the permission, or on pull requests from forks (read-only token), the comment is skipped with a warning and the check result is unchanged. Outside the action: `adre pr-review … --comment` (uses `GITHUB_TOKEN`) or `--comment-file comment.md` to get the markdown.
|
|
198
|
+
|
|
188
199
|
To show findings in GitHub code scanning, write SARIF and upload it even when the check fails (needs `security-events: write`; private repositories need GitHub Advanced Security):
|
|
189
200
|
|
|
190
201
|
```yaml
|
|
191
|
-
- uses: christiangebru/architect-reviewer@v0.
|
|
202
|
+
- uses: christiangebru/architect-reviewer@v0.2.0
|
|
192
203
|
id: adre
|
|
193
204
|
with:
|
|
194
205
|
sarif-file: adre.sarif
|
|
@@ -66,7 +66,7 @@ pip install adre-cli # CLI only, no dependencies
|
|
|
66
66
|
pip install "adre-cli[web]" # plus the local web UI
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
To install an unreleased version from GitHub: `pip install "git+https://github.com/christiangebru/architect-reviewer@main"`.
|
|
70
70
|
|
|
71
71
|
This installs the `adre` command (the package is `adre-cli` because `adre` is taken on PyPI). From a source checkout, `./bin/adre` runs the same CLI without installing anything.
|
|
72
72
|
|
|
@@ -100,7 +100,7 @@ Start the local web UI (needs the `web` extra; binds to 127.0.0.1 by default):
|
|
|
100
100
|
adre web --port 8000
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
-
The web UI gives the same answers as the CLI: **Review against baseline** runs exactly what `adre review` runs (baseline, declared rules, accepted and stale exceptions), and **Review a branch** runs the same pull-request review as the GitHub Action for the checked-out branch against a base you choose.
|
|
103
|
+
The web UI gives the same answers as the CLI: **Review against baseline** runs exactly what `adre review` runs (baseline, declared rules, accepted and stale exceptions), and **Review a branch** runs the same pull-request review as the GitHub Action for the checked-out branch against a base you choose. On either page, **Accept with reason** records an intentional crossing in `.adre/accepted.json` (commit it so CI accepts it too). New repositories get a **Get started** checklist on the dashboard: save the baseline, commit it, review, and add the GitHub Action. The **Rules** page edits `.adre/architecture.json` visually: it starts from the layers ADRE found, lets you reorder, rename and add layers, turn on strict layering and add forbidden dependencies, and previews which files each layer claims and which current dependencies would break the rules before you save.
|
|
104
104
|
|
|
105
105
|
It only answers on localhost. Requests with another `Host` header or that the browser marks as cross-site are refused, and every action that changes something (saving a baseline, cloning or registering a repository, pinning, opening your editor) is a POST carrying a per-process token, so other websites cannot trigger them. Binding to another interface with `--host` prints a warning.
|
|
106
106
|
|
|
@@ -115,10 +115,15 @@ Statuses:
|
|
|
115
115
|
|
|
116
116
|
- `PASS` (exit 0) — no new drift versus the accepted baseline
|
|
117
117
|
- `DRIFT` (exit 2) — new architectural drift in the PR
|
|
118
|
+
- `INCOMPLETE` (exit 4) — the PR changes a source file that was not analyzed because the project has more source files than the file limit (see below)
|
|
118
119
|
- `BASELINE_REQUIRED` (exit 3) — no `.adre/baseline.json` on the base ref
|
|
119
120
|
- `BASELINE_INVALID` (exit 1) — baseline could not be loaded
|
|
120
121
|
- `ERROR` (exit 1) — git or analysis failure
|
|
121
122
|
|
|
123
|
+
**Which findings fail.** By default every finding fails the review. Set a threshold with `--fail-on critical|high|medium|low|none` (on `review`, `pr-review`, `pr-check` and `web`), the `ADRE_FAIL_ON` environment variable, or the action's `fail-on` input. Findings below it are still reported, as warnings (job summary, `::warning` annotations, SARIF level `note`, `warnings` in JSON), but do not fail. Severities: a new cycle is `critical`; layer skips, reversed layer dependencies, repository bypasses and declared-rule violations are `high`; an unexpected (inferred) dependency is `medium`. `--fail-on high` therefore keeps every proven violation blocking and turns inferred findings into warnings; `none` is an advisory mode for the first weeks of adoption.
|
|
124
|
+
|
|
125
|
+
**File limit.** ADRE analyzes at most 5,000 source files by default, in a stable (sorted) order. When a project has more, every output says how many files were left out, and a pull request that changes one of them gets `INCOMPLETE` instead of `PASS`. Raise the limit with `--max-files N` (any command), the `ADRE_MAX_FILES` environment variable, or the action's `max-files` input; `0` means no limit.
|
|
126
|
+
|
|
122
127
|
`pr-review` uses the baseline for the accepted architecture model (layers, directions, established paths), and analyzes the base commit in a throwaway clone to decide what is new. Only dependencies, cycles, and database imports that the PR adds relative to the base tree are reported. As a result:
|
|
123
128
|
|
|
124
129
|
- problems that already exist on the base branch are not blamed on the PR, even if they were merged after the baseline was saved
|
|
@@ -139,6 +144,7 @@ on:
|
|
|
139
144
|
|
|
140
145
|
permissions:
|
|
141
146
|
contents: read
|
|
147
|
+
pull-requests: write # lets ADRE keep one explanatory comment on the PR
|
|
142
148
|
|
|
143
149
|
jobs:
|
|
144
150
|
drift:
|
|
@@ -147,12 +153,12 @@ jobs:
|
|
|
147
153
|
- uses: actions/checkout@v4
|
|
148
154
|
with:
|
|
149
155
|
fetch-depth: 0 # the base commit and merge base must exist
|
|
150
|
-
- uses: christiangebru/architect-reviewer@v0.
|
|
156
|
+
- uses: christiangebru/architect-reviewer@v0.2.0 # or @v0 for the latest 0.x, or a commit SHA
|
|
151
157
|
with:
|
|
152
158
|
path: . # project directory inside the repository
|
|
153
159
|
```
|
|
154
160
|
|
|
155
|
-
The action compares the checked-out PR tree with the base commit, using `.adre/baseline.json` from the base commit as the accepted architecture, and fails the job on new drift. It writes the check summary to the job summary, adds an inline annotation on each finding (repository-relative paths, so projects in subdirectories work), and sets outputs `status`, `drift-count`, `accepted-count` and `sarif-file`.
|
|
161
|
+
The action compares the checked-out PR tree with the base commit, using `.adre/baseline.json` from the base commit as the accepted architecture, and fails the job on new drift. It writes the check summary to the job summary, adds an inline annotation on each finding (repository-relative paths, so projects in subdirectories work), and sets outputs `status`, `drift-count`, `warning-count`, `accepted-count` and `sarif-file`.
|
|
156
162
|
|
|
157
163
|
| Input | Default | |
|
|
158
164
|
|---|---|---|
|
|
@@ -161,13 +167,18 @@ The action compares the checked-out PR tree with the base commit, using `.adre/b
|
|
|
161
167
|
| `head` | `github.sha` | Checked-out commit |
|
|
162
168
|
| `baseline` | base commit's `.adre/baseline.json` | Baseline file |
|
|
163
169
|
| `sarif-file` | (none) | Also write SARIF 2.1.0 here |
|
|
170
|
+
| `max-files` | `5000` | Most source files to analyze; `0` = no limit |
|
|
171
|
+
| `comment` | `true` | Keep one ADRE comment on the PR, updated on every push; `false` to turn off |
|
|
172
|
+
| `fail-on` | `low` | Lowest severity that fails: `critical`, `high`, `medium`, `low`, or `none` (report only) |
|
|
164
173
|
| `python-version` | `3.12` | Python used to run ADRE |
|
|
165
174
|
| `setup-python` | `true` | `false` uses the runner's Python |
|
|
166
175
|
|
|
176
|
+
**PR comment.** With `pull-requests: write`, the action keeps a single comment on the pull request and edits it on every push instead of adding new ones. Each finding is explained in plain language (what happened, why it matters, how to fix it) with a ready-to-paste `.adre/accepted.json` entry for intentional crossings; warnings, accepted and stale exceptions are folded away. A clean PR gets no comment; a PR whose findings were fixed sees the comment flip to passed. Without the permission, or on pull requests from forks (read-only token), the comment is skipped with a warning and the check result is unchanged. Outside the action: `adre pr-review … --comment` (uses `GITHUB_TOKEN`) or `--comment-file comment.md` to get the markdown.
|
|
177
|
+
|
|
167
178
|
To show findings in GitHub code scanning, write SARIF and upload it even when the check fails (needs `security-events: write`; private repositories need GitHub Advanced Security):
|
|
168
179
|
|
|
169
180
|
```yaml
|
|
170
|
-
- uses: christiangebru/architect-reviewer@v0.
|
|
181
|
+
- uses: christiangebru/architect-reviewer@v0.2.0
|
|
171
182
|
id: adre
|
|
172
183
|
with:
|
|
173
184
|
sarif-file: adre.sarif
|
|
@@ -121,6 +121,9 @@ def analyze_project_architecture(
|
|
|
121
121
|
)
|
|
122
122
|
scope["excluded_directories"] = sorted(SKIP_DIRS)
|
|
123
123
|
scope["incremental"] = incremental
|
|
124
|
+
scope["max_files"] = index_meta.get("max_files")
|
|
125
|
+
scope["total_source_files"] = index_meta.get("total_files", scope.get("indexed_file_count", 0))
|
|
126
|
+
scope["skipped_files"] = index_meta.get("skipped_files", 0)
|
|
124
127
|
|
|
125
128
|
analyzed_files = scope["analyzed_files"]
|
|
126
129
|
analyzed_graph = {path: dependency_graph[path] for path in analyzed_files if path in dependency_graph}
|
|
@@ -6,7 +6,9 @@ from contextlib import redirect_stdout
|
|
|
6
6
|
|
|
7
7
|
from adre.analyzers.architecture import analyze_project_architecture
|
|
8
8
|
from adre import __version__
|
|
9
|
-
from adre.core.config import ANALYZER_VERSION
|
|
9
|
+
from adre.core.config import ANALYZER_VERSION, MAX_ANALYZED_FILES, MAX_FILES_ENV
|
|
10
|
+
from adre.core.scope import truncation_info, truncation_message
|
|
11
|
+
from adre.core.severity import DEFAULT_FAIL_ON, FAIL_ON_CHOICES, FAIL_ON_ENV
|
|
10
12
|
from adre.core.baseline import (
|
|
11
13
|
save_architecture_baseline,
|
|
12
14
|
)
|
|
@@ -23,6 +25,7 @@ from adre.core.git_intelligence import (
|
|
|
23
25
|
from adre.core.review import review_working_tree
|
|
24
26
|
from adre.core.github_check import format_github_check, write_github_output, write_step_outputs
|
|
25
27
|
from adre.core.sarif import write_sarif
|
|
28
|
+
from adre.core.pr_comment import PRCommentError, comment_context, format_pr_comment, publish_pr_comment
|
|
26
29
|
from adre.core.pr_review import exit_code_for, review_pull_request
|
|
27
30
|
from adre.core.snapshots import compare_snapshot_data, load_snapshot_file, snapshot_from_analysis
|
|
28
31
|
from adre.core.stability_intelligence import analyze_architecture_stability
|
|
@@ -129,6 +132,8 @@ def print_review(comparison):
|
|
|
129
132
|
print_header("Architecture Review")
|
|
130
133
|
print("Comparing current analysis against the saved baseline.")
|
|
131
134
|
print(comparison.get("summary") or "No comparison summary.")
|
|
135
|
+
if (comparison.get("truncation") or {}).get("message"):
|
|
136
|
+
print("Warning: {0}".format(comparison["truncation"]["message"]))
|
|
132
137
|
if comparison.get("analyzer_version_mismatch"):
|
|
133
138
|
print(
|
|
134
139
|
"Note: baseline analyzer {0} differs from current {1}.".format(
|
|
@@ -166,8 +171,15 @@ def print_review(comparison):
|
|
|
166
171
|
for rule in stale:
|
|
167
172
|
print("- entry {0}: {1} -> {2} ({3})".format(rule["index"], rule["from"], rule["to"], rule["reason"]))
|
|
168
173
|
drift = comparison.get("drift") or []
|
|
174
|
+
warnings = comparison.get("warnings") or []
|
|
175
|
+
if warnings:
|
|
176
|
+
print("\nWarnings below the fail-on threshold ({0}; {1}):".format(
|
|
177
|
+
comparison.get("fail_on"), comparison.get("fail_on_description") or ""
|
|
178
|
+
))
|
|
179
|
+
for item in warnings:
|
|
180
|
+
print_issue(item)
|
|
169
181
|
if not drift:
|
|
170
|
-
print("\nNo architectural drift findings.")
|
|
182
|
+
print("\nNo architectural drift findings." if not warnings else "\nNo findings at or above the fail-on threshold.")
|
|
171
183
|
return
|
|
172
184
|
print("\nDrift findings:")
|
|
173
185
|
for item in drift:
|
|
@@ -210,8 +222,9 @@ def print_scope(scope):
|
|
|
210
222
|
print("Expanded from dependencies: {0}".format(", ".join(scope["expanded_files"][:20])))
|
|
211
223
|
if scope.get("missing_paths"):
|
|
212
224
|
print("Missing selection: {0}".format(", ".join(scope["missing_paths"])))
|
|
213
|
-
|
|
214
|
-
|
|
225
|
+
truncation = truncation_info(scope)
|
|
226
|
+
if truncation:
|
|
227
|
+
print("Warning: {0}".format(truncation_message(truncation)))
|
|
215
228
|
if scope.get("unsupported_files"):
|
|
216
229
|
print("Unsupported source files skipped: {0}".format(scope["unsupported_files"]))
|
|
217
230
|
if scope.get("parse_errors"):
|
|
@@ -742,9 +755,32 @@ def command_pr_check(args):
|
|
|
742
755
|
else:
|
|
743
756
|
write_github_output(result)
|
|
744
757
|
write_step_outputs(result, sarif_path)
|
|
758
|
+
comment_file = getattr(args, "comment_file", None)
|
|
759
|
+
if comment_file:
|
|
760
|
+
with open(comment_file, "w", encoding="utf-8") as handle:
|
|
761
|
+
handle.write(format_pr_comment(result))
|
|
762
|
+
if getattr(args, "comment", False):
|
|
763
|
+
post_pr_comment(result, json_output=getattr(args, "format", "text") == "json")
|
|
745
764
|
return exit_code_for(result)
|
|
746
765
|
|
|
747
766
|
|
|
767
|
+
def post_pr_comment(result, json_output=False):
|
|
768
|
+
"""Create or update the sticky PR comment. Problems are warnings: the
|
|
769
|
+
comment never changes the check result."""
|
|
770
|
+
try:
|
|
771
|
+
action, url = publish_pr_comment(result, *comment_context())
|
|
772
|
+
except PRCommentError as exc:
|
|
773
|
+
message = "PR comment not posted: {0}".format(exc)
|
|
774
|
+
if os.environ.get("GITHUB_ACTIONS"):
|
|
775
|
+
# Workflow command; stdout stays pure JSON with --format json.
|
|
776
|
+
print("::warning title=ADRE::{0}".format(message.replace("\n", " ")), file=sys.stderr if json_output else sys.stdout)
|
|
777
|
+
else:
|
|
778
|
+
print("Warning: {0}".format(message), file=sys.stderr)
|
|
779
|
+
return
|
|
780
|
+
if action != "skipped":
|
|
781
|
+
print("PR comment {0}: {1}".format(action, url), file=sys.stderr)
|
|
782
|
+
|
|
783
|
+
|
|
748
784
|
def command_evolution(args):
|
|
749
785
|
snapshots = extract_git_snapshots(args.path)
|
|
750
786
|
evolution = analyze_architecture_evolution(snapshots)
|
|
@@ -808,6 +844,7 @@ def build_parser():
|
|
|
808
844
|
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
809
845
|
|
|
810
846
|
analyze_parser = subparsers.add_parser("analyze", help="Analyze current code. Does not update the saved baseline.")
|
|
847
|
+
add_max_files_argument(analyze_parser)
|
|
811
848
|
analyze_parser.add_argument("path")
|
|
812
849
|
analyze_parser.add_argument(
|
|
813
850
|
"--select",
|
|
@@ -823,6 +860,7 @@ def build_parser():
|
|
|
823
860
|
analyze_parser.set_defaults(func=command_analyze)
|
|
824
861
|
|
|
825
862
|
baseline_parser = subparsers.add_parser("baseline", help="Save the current architecture as the accepted baseline")
|
|
863
|
+
add_max_files_argument(baseline_parser)
|
|
826
864
|
baseline_parser.add_argument("path")
|
|
827
865
|
baseline_parser.add_argument("--select", nargs="+", default=None)
|
|
828
866
|
baseline_parser.add_argument("--no-expand", action="store_true")
|
|
@@ -830,6 +868,8 @@ def build_parser():
|
|
|
830
868
|
baseline_parser.set_defaults(func=command_baseline)
|
|
831
869
|
|
|
832
870
|
review_parser = subparsers.add_parser("review", help="Compare current analysis against a saved architecture baseline")
|
|
871
|
+
add_max_files_argument(review_parser)
|
|
872
|
+
add_fail_on_argument(review_parser)
|
|
833
873
|
review_parser.add_argument("path")
|
|
834
874
|
review_parser.add_argument("--select", nargs="+", default=None)
|
|
835
875
|
review_parser.add_argument("--no-expand", action="store_true")
|
|
@@ -837,6 +877,7 @@ def build_parser():
|
|
|
837
877
|
review_parser.set_defaults(func=command_review)
|
|
838
878
|
|
|
839
879
|
report_parser = subparsers.add_parser("report", help="Print a terminal architecture report")
|
|
880
|
+
add_max_files_argument(report_parser)
|
|
840
881
|
report_parser.add_argument("path")
|
|
841
882
|
report_parser.add_argument("--select", nargs="+", default=None)
|
|
842
883
|
report_parser.add_argument("--no-expand", action="store_true")
|
|
@@ -879,6 +920,8 @@ def build_parser():
|
|
|
879
920
|
"pr-check",
|
|
880
921
|
help="Review HEAD against the accepted architecture baseline for a pull request",
|
|
881
922
|
)
|
|
923
|
+
add_max_files_argument(pr_check_parser)
|
|
924
|
+
add_fail_on_argument(pr_check_parser)
|
|
882
925
|
pr_check_parser.add_argument("base_branch")
|
|
883
926
|
pr_check_parser.add_argument("head_branch", nargs="?", default="HEAD")
|
|
884
927
|
pr_check_parser.add_argument(
|
|
@@ -889,18 +932,34 @@ def build_parser():
|
|
|
889
932
|
pr_check_parser.add_argument("--against", help="Baseline JSON path (default: base ref .adre/baseline.json)")
|
|
890
933
|
pr_check_parser.add_argument("--format", choices=["text", "json"], default="text", help="Output format (default: text)")
|
|
891
934
|
pr_check_parser.add_argument("--sarif", metavar="PATH", help="Also write findings as SARIF 2.1.0 to PATH")
|
|
935
|
+
pr_check_parser.add_argument(
|
|
936
|
+
"--comment",
|
|
937
|
+
action="store_true",
|
|
938
|
+
help="In GitHub Actions, create or update one ADRE comment on the pull request (needs pull-requests: write)",
|
|
939
|
+
)
|
|
940
|
+
pr_check_parser.add_argument("--comment-file", metavar="PATH", help="Also write the PR comment markdown to PATH")
|
|
892
941
|
pr_check_parser.set_defaults(func=command_pr_check)
|
|
893
942
|
|
|
894
943
|
pr_review_parser = subparsers.add_parser("pr-review", help="Same as pr-check: compare a PR against the accepted baseline")
|
|
944
|
+
add_max_files_argument(pr_review_parser)
|
|
945
|
+
add_fail_on_argument(pr_review_parser)
|
|
895
946
|
pr_review_parser.add_argument("base_branch")
|
|
896
947
|
pr_review_parser.add_argument("head_branch", nargs="?", default="HEAD")
|
|
897
948
|
pr_review_parser.add_argument("--path", default=".")
|
|
898
949
|
pr_review_parser.add_argument("--against", default=None)
|
|
899
950
|
pr_review_parser.add_argument("--format", choices=["text", "json"], default="text", help="Output format (default: text)")
|
|
900
951
|
pr_review_parser.add_argument("--sarif", metavar="PATH", help="Also write findings as SARIF 2.1.0 to PATH")
|
|
952
|
+
pr_review_parser.add_argument(
|
|
953
|
+
"--comment",
|
|
954
|
+
action="store_true",
|
|
955
|
+
help="In GitHub Actions, create or update one ADRE comment on the pull request (needs pull-requests: write)",
|
|
956
|
+
)
|
|
957
|
+
pr_review_parser.add_argument("--comment-file", metavar="PATH", help="Also write the PR comment markdown to PATH")
|
|
901
958
|
pr_review_parser.set_defaults(func=command_pr_check)
|
|
902
959
|
|
|
903
960
|
web_parser = subparsers.add_parser("web", help="Start the local web UI (needs: pip install 'adre-cli[web]')")
|
|
961
|
+
add_max_files_argument(web_parser)
|
|
962
|
+
add_fail_on_argument(web_parser)
|
|
904
963
|
web_parser.add_argument("--host", default="127.0.0.1", help="Interface to bind (default: 127.0.0.1, local only)")
|
|
905
964
|
web_parser.add_argument("--port", type=int, default=8000)
|
|
906
965
|
web_parser.set_defaults(func=command_web)
|
|
@@ -908,15 +967,55 @@ def build_parser():
|
|
|
908
967
|
return parser
|
|
909
968
|
|
|
910
969
|
|
|
970
|
+
def add_max_files_argument(parser):
|
|
971
|
+
parser.add_argument(
|
|
972
|
+
"--max-files",
|
|
973
|
+
type=int,
|
|
974
|
+
metavar="N",
|
|
975
|
+
default=None,
|
|
976
|
+
help="Analyze at most N source files (default {0}, or ADRE_MAX_FILES; 0 = no limit)".format(MAX_ANALYZED_FILES),
|
|
977
|
+
)
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def add_fail_on_argument(parser):
|
|
981
|
+
parser.add_argument(
|
|
982
|
+
"--fail-on",
|
|
983
|
+
choices=FAIL_ON_CHOICES,
|
|
984
|
+
default=None,
|
|
985
|
+
help=(
|
|
986
|
+
"Lowest finding severity that fails the review (default {0}, or ADRE_FAIL_ON). "
|
|
987
|
+
"Lower-severity findings are reported as warnings; 'none' never fails on drift."
|
|
988
|
+
).format(DEFAULT_FAIL_ON),
|
|
989
|
+
)
|
|
990
|
+
|
|
991
|
+
|
|
911
992
|
def main(argv=None):
|
|
912
993
|
parser = build_parser()
|
|
913
994
|
args = parser.parse_args(argv)
|
|
914
|
-
|
|
995
|
+
max_files = getattr(args, "max_files", None)
|
|
996
|
+
if max_files is not None and max_files < 0:
|
|
997
|
+
print("Error: --max-files must be 0 (no limit) or a positive number.", file=sys.stderr)
|
|
998
|
+
return 1
|
|
999
|
+
# Command-line settings apply to this call only, so in-process callers
|
|
1000
|
+
# (tests, the web UI) keep their own environment.
|
|
1001
|
+
overrides = {}
|
|
1002
|
+
if max_files is not None:
|
|
1003
|
+
overrides[MAX_FILES_ENV] = str(max_files)
|
|
1004
|
+
if getattr(args, "fail_on", None):
|
|
1005
|
+
overrides[FAIL_ON_ENV] = args.fail_on
|
|
1006
|
+
previous = {name: os.environ.get(name) for name in overrides}
|
|
1007
|
+
os.environ.update(overrides)
|
|
915
1008
|
try:
|
|
916
1009
|
return args.func(args)
|
|
917
1010
|
except Exception as exc:
|
|
918
1011
|
print(f"Error: {exc}", file=sys.stderr)
|
|
919
1012
|
return 1
|
|
1013
|
+
finally:
|
|
1014
|
+
for name, value in previous.items():
|
|
1015
|
+
if value is None:
|
|
1016
|
+
os.environ.pop(name, None)
|
|
1017
|
+
else:
|
|
1018
|
+
os.environ[name] = value
|
|
920
1019
|
|
|
921
1020
|
|
|
922
1021
|
if __name__ == "__main__":
|
|
@@ -223,3 +223,77 @@ def stale_accepted_rules(rules, analysis):
|
|
|
223
223
|
for rule in rules or []
|
|
224
224
|
if not _rule_still_applies(rule, analysis)
|
|
225
225
|
]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
MAX_REASON_LENGTH = 500
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def glob_escape(path):
|
|
232
|
+
"""Escape fnmatch special characters so a path matches only itself."""
|
|
233
|
+
return "".join("[{0}]".format(char) if char in "*?[" else char for char in _norm(path))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def suggested_entry(finding):
|
|
237
|
+
"""The narrowest accepted.json entry that covers this finding.
|
|
238
|
+
|
|
239
|
+
Returns {"from", "to", "type"} or None when one entry cannot cover it
|
|
240
|
+
exactly (a cycle that several files joined at once).
|
|
241
|
+
"""
|
|
242
|
+
issue_type = finding.get("issue_type")
|
|
243
|
+
if issue_type not in ISSUE_TYPES or not finding.get("file"):
|
|
244
|
+
return None
|
|
245
|
+
if issue_type == "cycle":
|
|
246
|
+
joined = [item for item in finding.get("joined_files") or [] if item]
|
|
247
|
+
if len(joined) > 1:
|
|
248
|
+
return None
|
|
249
|
+
source = joined[0] if joined else finding.get("file")
|
|
250
|
+
return {"from": glob_escape(source), "to": "*", "type": issue_type}
|
|
251
|
+
target = finding.get("imported")
|
|
252
|
+
if not target:
|
|
253
|
+
return None
|
|
254
|
+
# For repository_bypass, `to` is the database module name, not a path.
|
|
255
|
+
return {"from": glob_escape(finding["file"]), "to": glob_escape(target), "type": issue_type}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def add_accepted_entry(project_root, source, target, issue_type, reason):
|
|
259
|
+
"""Append one entry to .adre/accepted.json, creating the file if needed.
|
|
260
|
+
|
|
261
|
+
Returns "added", or "exists" when an entry with the same from/to/type is
|
|
262
|
+
already there. Raises ValueError for invalid input or an invalid existing
|
|
263
|
+
file (it is never overwritten in that case).
|
|
264
|
+
"""
|
|
265
|
+
reason = (reason or "").strip()
|
|
266
|
+
if not reason:
|
|
267
|
+
raise ValueError("Give a reason so reviewers know why this crossing is accepted.")
|
|
268
|
+
if len(reason) > MAX_REASON_LENGTH:
|
|
269
|
+
raise ValueError("Keep the reason under {0} characters.".format(MAX_REASON_LENGTH))
|
|
270
|
+
if issue_type not in ISSUE_TYPES:
|
|
271
|
+
raise ValueError("Unknown finding type: {0}".format(issue_type))
|
|
272
|
+
for value in (source, target):
|
|
273
|
+
if not isinstance(value, str) or not value.strip() or len(value) > 1000 or "\n" in value:
|
|
274
|
+
raise ValueError("Invalid accepted.json pattern.")
|
|
275
|
+
|
|
276
|
+
path = accepted_path(project_root)
|
|
277
|
+
if os.path.islink(path) or os.path.islink(os.path.dirname(path)):
|
|
278
|
+
raise ValueError("{0} must not be a symlink.".format(accepted_rel_path()))
|
|
279
|
+
data = {"accepted": []}
|
|
280
|
+
if os.path.exists(path):
|
|
281
|
+
try:
|
|
282
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
283
|
+
data = json.load(handle)
|
|
284
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
285
|
+
raise ValueError("{0} could not be read: {1}".format(accepted_rel_path(), exc))
|
|
286
|
+
|
|
287
|
+
for rule in parse_accepted(data, source=accepted_rel_path()):
|
|
288
|
+
if rule["from"] == source and rule["to"] == target and rule["type"] == [issue_type]:
|
|
289
|
+
return "exists"
|
|
290
|
+
|
|
291
|
+
data["accepted"].append({"from": source, "to": target, "type": issue_type, "reason": reason})
|
|
292
|
+
parse_accepted(data, source=accepted_rel_path())
|
|
293
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
294
|
+
temporary = path + ".tmp"
|
|
295
|
+
with open(temporary, "w", encoding="utf-8") as handle:
|
|
296
|
+
json.dump(data, handle, indent=2)
|
|
297
|
+
handle.write("\n")
|
|
298
|
+
os.replace(temporary, path)
|
|
299
|
+
return "added"
|
|
@@ -48,6 +48,7 @@ SEVERITY_WEIGHTS = {
|
|
|
48
48
|
}
|
|
49
49
|
MAX_FILE_BYTES = 512_000
|
|
50
50
|
MAX_ANALYZED_FILES = 5000
|
|
51
|
+
MAX_FILES_ENV = "ADRE_MAX_FILES"
|
|
51
52
|
MAX_GIT_COMMITS = 20
|
|
52
53
|
MAX_INDIRECT_CHAINS = 200
|
|
53
54
|
MAX_INDIRECT_GRAPH_SIZE = 300
|
|
@@ -58,3 +59,18 @@ BASELINE_FILENAME = "baseline.json"
|
|
|
58
59
|
PARSE_CACHE_FILENAME = "parse-cache.json"
|
|
59
60
|
PARSE_CACHE_SCHEMA_VERSION = 1
|
|
60
61
|
ANALYZER_VERSION = "0.9.0"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def max_analyzed_files():
|
|
65
|
+
"""The source-file limit: ADRE_MAX_FILES if set (0 means no limit),
|
|
66
|
+
otherwise MAX_ANALYZED_FILES. Raises ValueError for an invalid value."""
|
|
67
|
+
raw = os.environ.get(MAX_FILES_ENV, "").strip()
|
|
68
|
+
if not raw:
|
|
69
|
+
return MAX_ANALYZED_FILES
|
|
70
|
+
try:
|
|
71
|
+
value = int(raw)
|
|
72
|
+
except ValueError:
|
|
73
|
+
value = -1
|
|
74
|
+
if value < 0:
|
|
75
|
+
raise ValueError("{0} must be a whole number of files (0 for no limit), got {1!r}.".format(MAX_FILES_ENV, raw))
|
|
76
|
+
return value
|
|
@@ -311,3 +311,123 @@ def _indirect_findings(declared, current_edges, new_edges, prior_edges, direct_k
|
|
|
311
311
|
finding["chain_to"] = high
|
|
312
312
|
findings.append(finding)
|
|
313
313
|
return findings
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# --- Rules editor support (web UI) ---------------------------------------
|
|
317
|
+
|
|
318
|
+
ROLE_RANK = {"presentation": 0, "application": 1, "data": 2, "domain": 3, "shared": 4}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _cluster_patterns(layer):
|
|
322
|
+
"""Glob patterns covering an inferred layer's files."""
|
|
323
|
+
name = (layer.get("name") or "").strip("/")
|
|
324
|
+
files = [_norm_path(item) for item in layer.get("files") or []]
|
|
325
|
+
if name and files and all(item.startswith(name + "/") for item in files):
|
|
326
|
+
return [name + "/*"]
|
|
327
|
+
patterns = []
|
|
328
|
+
for item in files:
|
|
329
|
+
directory = os.path.dirname(item)
|
|
330
|
+
pattern = directory + "/*" if directory else item
|
|
331
|
+
if pattern not in patterns:
|
|
332
|
+
patterns.append(pattern)
|
|
333
|
+
return patterns
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _norm_path(value):
|
|
337
|
+
return (value or "").replace("\\", "/")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def draft_declared(architecture):
|
|
341
|
+
"""A starting architecture.json from the inferred layers.
|
|
342
|
+
|
|
343
|
+
Layers follow the inferred dependency order (summary path) where known,
|
|
344
|
+
otherwise their role: presentation, application, data, domain, shared.
|
|
345
|
+
Layers without a known role are left out for the user to place.
|
|
346
|
+
"""
|
|
347
|
+
architecture = architecture or {}
|
|
348
|
+
summary = [item.strip() for item in (architecture.get("summary_path") or "").split("->") if item.strip()]
|
|
349
|
+
candidates = [layer for layer in architecture.get("layers") or [] if layer.get("role") in ROLE_RANK]
|
|
350
|
+
|
|
351
|
+
def order(layer):
|
|
352
|
+
name = layer.get("name")
|
|
353
|
+
if name in summary:
|
|
354
|
+
return (0, summary.index(name), 0)
|
|
355
|
+
return (1, ROLE_RANK[layer["role"]], name or "")
|
|
356
|
+
|
|
357
|
+
layers = []
|
|
358
|
+
used_names = set()
|
|
359
|
+
for layer in sorted(candidates, key=order):
|
|
360
|
+
patterns = _cluster_patterns(layer)
|
|
361
|
+
if not patterns:
|
|
362
|
+
continue
|
|
363
|
+
name = layer["role"] if layer["role"] not in used_names else layer.get("name") or layer["role"]
|
|
364
|
+
if name in used_names:
|
|
365
|
+
continue
|
|
366
|
+
used_names.add(name)
|
|
367
|
+
layers.append({"name": name, "paths": patterns})
|
|
368
|
+
return {"layers": layers, "strict": False, "forbidden": []}
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def declared_to_json(declared):
|
|
372
|
+
"""Parsed rules back to the file format (drops internal keys)."""
|
|
373
|
+
data = {
|
|
374
|
+
"layers": [{"name": layer["name"], "paths": list(layer["paths"])} for layer in declared["layers"]],
|
|
375
|
+
"strict": bool(declared["strict"]),
|
|
376
|
+
}
|
|
377
|
+
forbidden = []
|
|
378
|
+
for rule in declared["forbidden"]:
|
|
379
|
+
item = {"from": list(rule["from"]), "to": list(rule["to"])}
|
|
380
|
+
if rule.get("reason"):
|
|
381
|
+
item["reason"] = rule["reason"]
|
|
382
|
+
forbidden.append(item)
|
|
383
|
+
if forbidden:
|
|
384
|
+
data["forbidden"] = forbidden
|
|
385
|
+
return data
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def save_declared(project_root, data):
|
|
389
|
+
"""Validate and write .adre/architecture.json. Returns the parsed rules.
|
|
390
|
+
|
|
391
|
+
Raises ValueError (nothing is written) when the rules are invalid.
|
|
392
|
+
"""
|
|
393
|
+
declared = parse_declared(data, source=declared_rel_path())
|
|
394
|
+
path = declared_path(project_root)
|
|
395
|
+
if os.path.islink(path) or os.path.islink(os.path.dirname(path)):
|
|
396
|
+
raise ValueError("{0} must not be a symlink.".format(declared_rel_path()))
|
|
397
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
398
|
+
temporary = path + ".tmp"
|
|
399
|
+
with open(temporary, "w", encoding="utf-8") as handle:
|
|
400
|
+
json.dump(declared_to_json(declared), handle, indent=2)
|
|
401
|
+
handle.write("\n")
|
|
402
|
+
os.replace(temporary, path)
|
|
403
|
+
return declared
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def preview_declared(declared, analysis, sample=8):
|
|
407
|
+
"""What the rules mean for the current code.
|
|
408
|
+
|
|
409
|
+
layers: [{name, count, sample}] files each layer claims;
|
|
410
|
+
unassigned: source files no layer claims;
|
|
411
|
+
violations: current dependencies that break the rules (all of them, as if
|
|
412
|
+
nothing were in a baseline);
|
|
413
|
+
"""
|
|
414
|
+
graph = (analysis or {}).get("resolved_graph") or {}
|
|
415
|
+
files = sorted(set(graph) | {target for targets in graph.values() for target in targets})
|
|
416
|
+
claimed = {layer["name"]: [] for layer in declared["layers"]}
|
|
417
|
+
unassigned = []
|
|
418
|
+
for path in files:
|
|
419
|
+
layer = layer_of(path, declared)
|
|
420
|
+
if layer is None:
|
|
421
|
+
unassigned.append(path)
|
|
422
|
+
else:
|
|
423
|
+
claimed[layer["name"]].append(path)
|
|
424
|
+
violations = check_declared(declared, graph, set())
|
|
425
|
+
return {
|
|
426
|
+
"layers": [
|
|
427
|
+
{"name": layer["name"], "count": len(claimed[layer["name"]]), "sample": claimed[layer["name"]][:sample]}
|
|
428
|
+
for layer in declared["layers"]
|
|
429
|
+
],
|
|
430
|
+
"file_count": len(files),
|
|
431
|
+
"unassigned": unassigned,
|
|
432
|
+
"violations": violations,
|
|
433
|
+
}
|