pubrules 0.48.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.
- pubrules/__init__.py +14 -0
- pubrules/audit.py +116 -0
- pubrules/audit_draft.py +295 -0
- pubrules/audit_prepare.py +1128 -0
- pubrules/cache.py +319 -0
- pubrules/cbor.py +45 -0
- pubrules/ci.py +910 -0
- pubrules/cli.py +1069 -0
- pubrules/conform.py +295 -0
- pubrules/doc_coverage.py +235 -0
- pubrules/freshness.py +75 -0
- pubrules/gherkin.py +348 -0
- pubrules/hooks.py +59 -0
- pubrules/hosting.py +372 -0
- pubrules/ignores.py +86 -0
- pubrules/new.py +242 -0
- pubrules/nightly.py +1002 -0
- pubrules/paths.py +32 -0
- pubrules/protect.py +596 -0
- pubrules/providers.py +129 -0
- pubrules/refs.py +213 -0
- pubrules/release-commit +1 -0
- pubrules/releases.py +107 -0
- pubrules/repos.py +67 -0
- pubrules/ruleset.json +43 -0
- pubrules/secrets_config.py +165 -0
- pubrules/security.py +134 -0
- pubrules/service_needs.py +467 -0
- pubrules/standard.json +635 -0
- pubrules/standard.py +266 -0
- pubrules/supply_chain.py +188 -0
- pubrules/tag-ruleset.json +14 -0
- pubrules/templates/common/AGENTS.md +32 -0
- pubrules/templates/common/pubrules +26 -0
- pubrules/templates/common/tests/features/repository.feature +11 -0
- pubrules/templates/common/tests/install-lock +65 -0
- pubrules/templates/common/tests/pytest.ini +4 -0
- pubrules/templates/common/tests/requirements-pubrules.txt +17 -0
- pubrules/templates/common/tests/requirements.txt +3 -0
- pubrules/templates/common/tests/steps/test_repository.py +14 -0
- pubrules/templates/deploy/pubdeploy +28 -0
- pubrules/templates/new-rust/CHANGELOG.md +3 -0
- pubrules/templates/new-rust/Cargo.toml +46 -0
- pubrules/templates/new-rust/LICENSE +202 -0
- pubrules/templates/new-rust/Makefile +18 -0
- pubrules/templates/new-rust/README.md +34 -0
- pubrules/templates/new-rust/SECURITY.md +26 -0
- pubrules/templates/new-rust/corpus/corpus.json +11 -0
- pubrules/templates/new-rust/deny.toml +32 -0
- pubrules/templates/new-rust/fuzz/Cargo.toml +23 -0
- pubrules/templates/new-rust/fuzz/fuzz_targets/greet.rs +8 -0
- pubrules/templates/new-rust/fuzz/gitignore +4 -0
- pubrules/templates/new-rust/fuzz/regressions/README.md +4 -0
- pubrules/templates/new-rust/gitignore +10 -0
- pubrules/templates/new-rust/src/lib.rs +91 -0
- pubrules/templates/new-rust/src/main.rs +19 -0
- pubrules/templates/new-rust/supply-chain/audits.toml +4 -0
- pubrules/templates/new-rust/supply-chain/config.toml +23 -0
- pubrules/templates/new-rust/supply-chain/imports.lock +2 -0
- pubrules/templates/new-rust/tests/conftest.py +9 -0
- pubrules/templates/new-rust/tests/features/cli.feature +14 -0
- pubrules/templates/new-rust/tests/steps/test_cli.py +15 -0
- pubrules/templates/new-rust/tests/vectors.rs +30 -0
- pubrules/templates/new-rust/tools/vectors/generate.py +24 -0
- pubrules/templates/python/Makefile +5 -0
- pubrules/templates/python/pubrules-python.mk +47 -0
- pubrules/templates/rust/Makefile +9 -0
- pubrules/templates/rust/pubrules.mk +138 -0
- pubrules/templates/rust/rust-toolchain.toml +8 -0
- pubrules/templates/service/pubsec +27 -0
- pubrules/templates/service/with-secrets +20 -0
- pubrules/templates/service/with-secrets.json +8 -0
- pubrules/variables.py +45 -0
- pubrules-0.48.0.dist-info/METADATA +1241 -0
- pubrules-0.48.0.dist-info/RECORD +79 -0
- pubrules-0.48.0.dist-info/WHEEL +5 -0
- pubrules-0.48.0.dist-info/entry_points.txt +2 -0
- pubrules-0.48.0.dist-info/licenses/LICENSE +202 -0
- pubrules-0.48.0.dist-info/top_level.txt +1 -0
pubrules/gherkin.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""Every test is a Gherkin scenario: the rule `pubrules sync --check` holds
|
|
2
|
+
every repository to that has code (every kind but content).
|
|
3
|
+
|
|
4
|
+
- **TEST-01:** the repository has a Gherkin suite: a `.feature` file with a
|
|
5
|
+
scenario in it.
|
|
6
|
+
- **TEST-02:** no test runs outside a scenario. A Python test module's test
|
|
7
|
+
functions are pytest-bdd's scenario bindings (`scenarios(...)`, or a
|
|
8
|
+
function decorated with `@scenario` whose body is empty); there is no
|
|
9
|
+
`unittest.TestCase`, no `Test*` class, no Node test file (`*.test.js`,
|
|
10
|
+
`*.spec.ts`, or a script in a `test/` directory) and no test shell script
|
|
11
|
+
(`test-*.sh`). Rust's `#[test]`s and doc tests are the Rust crate
|
|
12
|
+
standard's, and stay.
|
|
13
|
+
- **TEST-03:** every feature file runs: a pytest-bdd binding names it, or the
|
|
14
|
+
directory it is in, or the repository runs cucumber-js, which runs every
|
|
15
|
+
feature file it is given.
|
|
16
|
+
- **TEST-04:** every scenario has a When among its own steps: it sets
|
|
17
|
+
something up, takes one action and checks what came of it (pubtest's
|
|
18
|
+
GRAMMAR.md). A When in a Background does not count, since a Background
|
|
19
|
+
builds the world. A step's `And` or `But` takes the keyword before it.
|
|
20
|
+
|
|
21
|
+
A repository that cannot meet a rule yet declares an exception in
|
|
22
|
+
pubrules.json, as for the Rust crate standard's rules:
|
|
23
|
+
`{"rule": "TEST-02", "reason": "...", "until": "YYYY-MM-DD"}`.
|
|
24
|
+
|
|
25
|
+
TEST-04 came after the repositories had suites, so the move to the pubrules
|
|
26
|
+
that brings it (`pubrules bump`, and the nightly's pins) writes its exception,
|
|
27
|
+
until 2026-12-31, into a repository that fails it (`grandfather`): no
|
|
28
|
+
repository's CI goes red on the bump, and one that passes, or moves later,
|
|
29
|
+
gets none.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import ast
|
|
35
|
+
import configparser
|
|
36
|
+
import json
|
|
37
|
+
import re
|
|
38
|
+
import subprocess
|
|
39
|
+
from pathlib import Path, PurePosixPath
|
|
40
|
+
|
|
41
|
+
RULES = {
|
|
42
|
+
"TEST-01": "the repository has a Gherkin suite",
|
|
43
|
+
"TEST-02": "no test runs outside a scenario",
|
|
44
|
+
"TEST-03": "every feature file runs",
|
|
45
|
+
"TEST-04": "every scenario has a When",
|
|
46
|
+
}
|
|
47
|
+
# The release that brings TEST-04, and how long a repository that moved to
|
|
48
|
+
# it failing the rule has to meet it.
|
|
49
|
+
WHEN_FROM = "0.43.3"
|
|
50
|
+
WHEN_UNTIL = "2026-12-31"
|
|
51
|
+
# Never the repository's own: tools, environments and what they fetched.
|
|
52
|
+
SKIPPED = {".git", ".venv", "venv", "node_modules", "__pycache__", ".pytest_cache", "target",
|
|
53
|
+
"dist", "build", "coverage", ".terraform", "vendor"}
|
|
54
|
+
SCENARIO = re.compile(r"^\s*(Scenario|Scenario Outline|Scenario Template|Example):", re.M)
|
|
55
|
+
NODE_TEST = re.compile(r"\.(test|spec)\.(m|c)?(j|t)sx?$")
|
|
56
|
+
NODE_SOURCE = re.compile(r"\.(m|c)?(j|t)sx?$")
|
|
57
|
+
NODE_TEST_DIRS = {"test", "tests", "__tests__"}
|
|
58
|
+
SHELL_TEST = re.compile(r"^(test[-_].*|.*[-_.]test)\.sh$")
|
|
59
|
+
# What a test module defines that pytest does not collect as a test.
|
|
60
|
+
NOT_TESTS = {"fixture", "given", "when", "then", "step"}
|
|
61
|
+
# A Node script in a test directory is a test when it loads a test runner;
|
|
62
|
+
# the rest there (fakes, setup, coverage helpers) serve the tests.
|
|
63
|
+
# The Gherkin runners for Node: a file that loads one defines steps or their
|
|
64
|
+
# support, whatever else it imports (node:test's mock, say), and each runs
|
|
65
|
+
# every feature file it is given.
|
|
66
|
+
GHERKIN_RUNNERS = ("@cucumber/cucumber", "quickpickle", "@amiceli/vitest-cucumber")
|
|
67
|
+
GHERKIN_RUNNER = re.compile(r"""(from\s+|require\(\s*|import\(\s*)['"](""" + "|".join(map(re.escape, GHERKIN_RUNNERS)) + r""")['"/]""")
|
|
68
|
+
NODE_RUNNER = re.compile(r"""(from\s+|require\(\s*|import\(\s*)['"](node:test|vitest|@playwright/test|mocha|jest|ava|tap|uvu)['"/]""")
|
|
69
|
+
PYTHON_TEST = re.compile(r"^(test_.*|.*_test)\.py$")
|
|
70
|
+
# A Gherkin file's lines that matter to TEST-04: the blocks, and the steps.
|
|
71
|
+
BLOCK = re.compile(r"^\s*(Feature|Rule|Background|Scenario Outline|Scenario Template|Scenario|Example|Examples|Scenarios):")
|
|
72
|
+
STEP = re.compile(r"^\s*(Given|When|Then|And|But|\*)\s")
|
|
73
|
+
DOCSTRING = re.compile(r'^\s*("""|```)')
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def files(root: Path) -> list[PurePosixPath]:
|
|
77
|
+
"""The repository's files: what git tracks or would add, or, outside a
|
|
78
|
+
git checkout, every file but the SKIPPED directories'."""
|
|
79
|
+
listed = subprocess.run(
|
|
80
|
+
["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
|
81
|
+
cwd=root, capture_output=True, check=False)
|
|
82
|
+
if listed.returncode == 0:
|
|
83
|
+
paths = [PurePosixPath(p) for p in listed.stdout.decode("utf-8", "replace").split("\0") if p]
|
|
84
|
+
else:
|
|
85
|
+
paths = [PurePosixPath(p.relative_to(root).as_posix()) for p in root.rglob("*") if p.is_file()]
|
|
86
|
+
return sorted(p for p in paths
|
|
87
|
+
if not SKIPPED.intersection(p.parts[:-1]) and (root / p).is_file())
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _decorator_name(node: ast.expr) -> str:
|
|
91
|
+
target = node.func if isinstance(node, ast.Call) else node
|
|
92
|
+
if isinstance(target, ast.Attribute):
|
|
93
|
+
return target.attr
|
|
94
|
+
return target.id if isinstance(target, ast.Name) else ""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _empty(body: list[ast.stmt]) -> bool:
|
|
98
|
+
"""A binding's body: pass, ..., or a docstring, nothing that tests."""
|
|
99
|
+
return all(isinstance(s, ast.Pass) or (isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant))
|
|
100
|
+
for s in body)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _bound(call: ast.Call) -> list[str | None]:
|
|
104
|
+
"""The feature paths a scenarios()/scenario() call names; None for one
|
|
105
|
+
that is not a literal string."""
|
|
106
|
+
return [a.value if isinstance(a, ast.Constant) and isinstance(a.value, str) else None
|
|
107
|
+
for a in call.args[: None if _decorator_name(call) == "scenarios" else 1]]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def python(root: Path, path: PurePosixPath) -> tuple[list[str], list[str | None]]:
|
|
111
|
+
"""(the tests outside a scenario in one Python file, the feature paths
|
|
112
|
+
it binds)."""
|
|
113
|
+
try:
|
|
114
|
+
tree = ast.parse((root / path).read_text(encoding="utf-8"), filename=str(path))
|
|
115
|
+
except (SyntaxError, UnicodeDecodeError, ValueError):
|
|
116
|
+
return [], []
|
|
117
|
+
outside: list[str] = []
|
|
118
|
+
bound: list[str | None] = []
|
|
119
|
+
for node in ast.walk(tree):
|
|
120
|
+
if isinstance(node, ast.Call) and _decorator_name(node) in ("scenarios", "scenario"):
|
|
121
|
+
bound += _bound(node)
|
|
122
|
+
if isinstance(node, ast.ClassDef):
|
|
123
|
+
bases = {_decorator_name(b) for b in node.bases}
|
|
124
|
+
if bases & {"TestCase", "IsolatedAsyncioTestCase"}:
|
|
125
|
+
outside.append(f"{path}:{node.lineno}: {node.name} is a unittest.TestCase")
|
|
126
|
+
if not PYTHON_TEST.match(path.name):
|
|
127
|
+
return outside, bound
|
|
128
|
+
for node in tree.body:
|
|
129
|
+
if isinstance(node, ast.ClassDef) and node.name.startswith("Test") and not any(
|
|
130
|
+
o.startswith(f"{path}:{node.lineno}:") for o in outside):
|
|
131
|
+
outside.append(f"{path}:{node.lineno}: {node.name} is a test class")
|
|
132
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith("test"):
|
|
133
|
+
decorators = {_decorator_name(d) for d in node.decorator_list}
|
|
134
|
+
if decorators & NOT_TESTS:
|
|
135
|
+
continue
|
|
136
|
+
binding = "scenario" in decorators
|
|
137
|
+
if not binding:
|
|
138
|
+
outside.append(f"{path}:{node.lineno}: {node.name} is a test function, not a scenario")
|
|
139
|
+
elif not _empty(node.body):
|
|
140
|
+
outside.append(f"{path}:{node.lineno}: {node.name} binds a scenario but tests in its "
|
|
141
|
+
f"body too; move that into a step")
|
|
142
|
+
return outside, bound
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _features_base(root: Path, listed: list[PurePosixPath]) -> dict[PurePosixPath, PurePosixPath]:
|
|
146
|
+
"""Each pytest.ini's directory, and the bdd_features_base_dir it sets."""
|
|
147
|
+
bases = {}
|
|
148
|
+
for path in listed:
|
|
149
|
+
if path.name != "pytest.ini":
|
|
150
|
+
continue
|
|
151
|
+
ini = configparser.ConfigParser()
|
|
152
|
+
try:
|
|
153
|
+
ini.read_string((root / path).read_text(encoding="utf-8"))
|
|
154
|
+
except (configparser.Error, UnicodeDecodeError):
|
|
155
|
+
continue
|
|
156
|
+
base = ini.get("pytest", "bdd_features_base_dir", fallback=None)
|
|
157
|
+
if base:
|
|
158
|
+
bases[path.parent] = PurePosixPath(_normal(path.parent / base.strip()))
|
|
159
|
+
return bases
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _normal(path: PurePosixPath) -> str:
|
|
163
|
+
parts: list[str] = []
|
|
164
|
+
for part in path.parts:
|
|
165
|
+
if part == "..":
|
|
166
|
+
if parts:
|
|
167
|
+
parts.pop()
|
|
168
|
+
elif part != ".":
|
|
169
|
+
parts.append(part)
|
|
170
|
+
return "/".join(parts) or "."
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _base_for(path: PurePosixPath, bases: dict[PurePosixPath, PurePosixPath]) -> PurePosixPath:
|
|
174
|
+
"""The features base a test module's bindings resolve against: its
|
|
175
|
+
nearest pytest.ini's, or else its own directory (pytest-bdd's default)."""
|
|
176
|
+
for parent in [path.parent, *path.parent.parents]:
|
|
177
|
+
if parent in bases:
|
|
178
|
+
return bases[parent]
|
|
179
|
+
return path.parent
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _cucumber(root: Path, listed: list[PurePosixPath]) -> bool:
|
|
183
|
+
"""The repository runs a Gherkin runner for Node: a cucumber config, or a
|
|
184
|
+
package.json (the repository's, or a package's in it) that depends on one."""
|
|
185
|
+
if any(p.name.startswith("cucumber.") for p in listed):
|
|
186
|
+
return True
|
|
187
|
+
for path in listed:
|
|
188
|
+
if path.name != "package.json":
|
|
189
|
+
continue
|
|
190
|
+
try:
|
|
191
|
+
data = json.loads((root / path).read_text(encoding="utf-8"))
|
|
192
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
193
|
+
continue
|
|
194
|
+
if any(runner in (data.get(k) or {}) for k in ("dependencies", "devDependencies")
|
|
195
|
+
for runner in GHERKIN_RUNNERS):
|
|
196
|
+
return True
|
|
197
|
+
return False
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def whenless(text: str) -> list[tuple[int, str]]:
|
|
201
|
+
"""(line, title) of each scenario in a feature file's text that has no
|
|
202
|
+
When of its own. An Outline is one scenario, whatever its Examples."""
|
|
203
|
+
found: list[tuple[int, str]] = []
|
|
204
|
+
scenario: tuple[int, str] | None = None
|
|
205
|
+
has_when = False
|
|
206
|
+
fence = None
|
|
207
|
+
for number, line in enumerate(text.splitlines(), 1):
|
|
208
|
+
if fence:
|
|
209
|
+
if line.strip().startswith(fence):
|
|
210
|
+
fence = None
|
|
211
|
+
continue
|
|
212
|
+
opened = DOCSTRING.match(line)
|
|
213
|
+
if opened:
|
|
214
|
+
fence = opened.group(1)
|
|
215
|
+
continue
|
|
216
|
+
block = BLOCK.match(line)
|
|
217
|
+
if block:
|
|
218
|
+
if block.group(1) in ("Examples", "Scenarios"):
|
|
219
|
+
continue
|
|
220
|
+
if scenario and not has_when:
|
|
221
|
+
found.append(scenario)
|
|
222
|
+
scenario = None
|
|
223
|
+
if block.group(1) not in ("Feature", "Rule", "Background"):
|
|
224
|
+
scenario, has_when = (number, line.strip()), False
|
|
225
|
+
continue
|
|
226
|
+
step = STEP.match(line)
|
|
227
|
+
if step and scenario and step.group(1) == "When":
|
|
228
|
+
has_when = True
|
|
229
|
+
if scenario and not has_when:
|
|
230
|
+
found.append(scenario)
|
|
231
|
+
return found
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def checks(root: Path) -> dict[str, list[str]]:
|
|
235
|
+
"""Each rule's problems here."""
|
|
236
|
+
listed = files(root)
|
|
237
|
+
problems: dict[str, list[str]] = {rule: [] for rule in RULES}
|
|
238
|
+
features = [p for p in listed if p.suffix == ".feature"]
|
|
239
|
+
with_scenarios = [p for p in features
|
|
240
|
+
if SCENARIO.search((root / p).read_text(encoding="utf-8", errors="replace"))]
|
|
241
|
+
if not with_scenarios:
|
|
242
|
+
problems["TEST-01"].append(
|
|
243
|
+
"there is no Gherkin suite: no .feature file with a scenario (tests/features/, "
|
|
244
|
+
"bound by tests/steps/test_*.py with pytest-bdd's scenarios())")
|
|
245
|
+
for path in features:
|
|
246
|
+
if path not in with_scenarios:
|
|
247
|
+
problems["TEST-01"].append(f"{path} has no scenario")
|
|
248
|
+
for line, title in whenless((root / path).read_text(encoding="utf-8", errors="replace")):
|
|
249
|
+
problems["TEST-04"].append(f"{path}:{line}: {title} has no When: give it the one action "
|
|
250
|
+
f"it tests (pubtest's GRAMMAR.md)")
|
|
251
|
+
bases = _features_base(root, listed)
|
|
252
|
+
named: set[str] = set()
|
|
253
|
+
unresolved = False
|
|
254
|
+
for path in listed:
|
|
255
|
+
if path.suffix == ".py":
|
|
256
|
+
outside, bound = python(root, path)
|
|
257
|
+
problems["TEST-02"] += outside
|
|
258
|
+
base = _base_for(path, bases)
|
|
259
|
+
for feature in bound:
|
|
260
|
+
if feature is None:
|
|
261
|
+
unresolved = True
|
|
262
|
+
else:
|
|
263
|
+
named.add(_normal(base / feature))
|
|
264
|
+
elif NODE_SOURCE.search(path.name) and (
|
|
265
|
+
NODE_TEST.search(path.name) or NODE_TEST_DIRS.intersection(path.parts[:-1])):
|
|
266
|
+
text = (root / path).read_text(encoding="utf-8", errors="replace")
|
|
267
|
+
if GHERKIN_RUNNER.search(text):
|
|
268
|
+
continue
|
|
269
|
+
if NODE_TEST.search(path.name) or NODE_RUNNER.search(text):
|
|
270
|
+
problems["TEST-02"].append(f"{path}: a Node test outside a scenario")
|
|
271
|
+
elif path.suffix == ".sh" and SHELL_TEST.match(path.name):
|
|
272
|
+
problems["TEST-02"].append(f"{path}: a test script outside a scenario")
|
|
273
|
+
if not unresolved and not _cucumber(root, listed):
|
|
274
|
+
for path in with_scenarios:
|
|
275
|
+
text = str(path)
|
|
276
|
+
if not any(text == n or n == "." or text.startswith(n.rstrip("/") + "/") for n in named):
|
|
277
|
+
problems["TEST-03"].append(f"{path}: no scenarios() or @scenario names it, so it never runs")
|
|
278
|
+
return {rule: texts for rule, texts in problems.items() if texts}
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def applies(config: dict) -> bool:
|
|
282
|
+
"""Every kind but content, whose own tooling checks what it holds."""
|
|
283
|
+
return config.get("kind") != "content"
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def grandfather(root: Path, package: str | None, before: str | None) -> list[str]:
|
|
287
|
+
"""On the move from a pubrules without TEST-04 (one before WHEN_FROM, or
|
|
288
|
+
any pubkit, as pubrules was called before 0.43.0), the TEST-04
|
|
289
|
+
exception a repository that fails the rule needs, written into its
|
|
290
|
+
pubrules.json; what was written, or nothing."""
|
|
291
|
+
from .conform import today # noqa: PLC0415
|
|
292
|
+
try:
|
|
293
|
+
older = bool(before) and (package == "pubkit" or _release(before) < _release(WHEN_FROM))
|
|
294
|
+
except ValueError:
|
|
295
|
+
older = False
|
|
296
|
+
path = root / "pubrules.json"
|
|
297
|
+
if not older or not path.is_file():
|
|
298
|
+
return []
|
|
299
|
+
config = json.loads(path.read_text(encoding="utf-8"))
|
|
300
|
+
declared = config.get("exceptions", [])
|
|
301
|
+
if (not applies(config) or any(isinstance(e, dict) and e.get("rule") == "TEST-04" for e in declared)
|
|
302
|
+
or str(today()) > WHEN_UNTIL):
|
|
303
|
+
return []
|
|
304
|
+
missing = checks(root).get("TEST-04", [])
|
|
305
|
+
if not missing:
|
|
306
|
+
return []
|
|
307
|
+
count = f"{len(missing)} scenario{'s' if len(missing) > 1 else ''}"
|
|
308
|
+
config["exceptions"] = [*declared, {
|
|
309
|
+
"rule": "TEST-04",
|
|
310
|
+
"reason": f"{count} had no When on the move from {package or 'pubrules'} {before}, before the rule; "
|
|
311
|
+
f"give each its one action, on pubtest's steps",
|
|
312
|
+
"until": WHEN_UNTIL}]
|
|
313
|
+
path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
|
|
314
|
+
return [f"pubrules.json: TEST-04 waived until {WHEN_UNTIL}, for the {count} with no When"]
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _release(version: str) -> tuple[int, ...]:
|
|
318
|
+
return tuple(int(n) for n in str(version).split(".")[:3])
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def run(root: Path, config: dict) -> tuple[list[str], list[str]]:
|
|
322
|
+
"""(lines to print, problems): this repository against the rule, less the
|
|
323
|
+
exceptions pubrules.json declares for it."""
|
|
324
|
+
from .conform import exceptions # noqa: PLC0415
|
|
325
|
+
if not applies(config):
|
|
326
|
+
return ["the Gherkin rule does not apply to a content repository"], []
|
|
327
|
+
waived, open_, problems = exceptions(config, set(RULES), family=lambda r: str(r).startswith("TEST-"))
|
|
328
|
+
for rule, texts in sorted(checks(root).items()):
|
|
329
|
+
if rule not in waived:
|
|
330
|
+
problems += [f"{rule}: {t}" for t in texts]
|
|
331
|
+
if problems:
|
|
332
|
+
lines = []
|
|
333
|
+
elif open_:
|
|
334
|
+
lines = [f"every test is a Gherkin scenario, but for {len(open_)} open exception{'s' if len(open_) > 1 else ''}"]
|
|
335
|
+
else:
|
|
336
|
+
lines = ["every test is a Gherkin scenario"]
|
|
337
|
+
lines += [f"open exception: {e}" for e in open_]
|
|
338
|
+
return lines, problems
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def main(root: Path, config: dict) -> int:
|
|
342
|
+
import sys # noqa: PLC0415
|
|
343
|
+
lines, problems = run(root, config)
|
|
344
|
+
for problem in problems:
|
|
345
|
+
print(f"pubrules: {problem}", file=sys.stderr)
|
|
346
|
+
if lines:
|
|
347
|
+
print("\n".join(lines))
|
|
348
|
+
return 1 if problems else 0
|
pubrules/hooks.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""What installed packages do when pubrules syncs or bumps a repository,
|
|
2
|
+
through two entry-point groups, so pubrules imports none of their code:
|
|
3
|
+
|
|
4
|
+
- `sustenaut.sync`: `check(root, config, check) -> (lines, failed)`, after
|
|
5
|
+
`pubrules sync`'s own work; `--check` fails when one says so. pubdeploy's is
|
|
6
|
+
the deploy block's offline check and the scheduled walk's caller.
|
|
7
|
+
- `sustenaut.bump`: `bump(root) -> lines`, after `pubrules bump` has moved
|
|
8
|
+
pubrules' own pins. pubdeploy's moves deploy.providers and the uses of
|
|
9
|
+
pubdeploy's workflows.
|
|
10
|
+
|
|
11
|
+
A hook that raises is said by its name and the error's type alone, never
|
|
12
|
+
its message, and fails `sync --check`. A repository with a deploy block and
|
|
13
|
+
no pubdeploy installed cannot be checked, which `--check` says, and fails.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from importlib.metadata import EntryPoint, entry_points
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
SYNC = "sustenaut.sync"
|
|
23
|
+
BUMP = "sustenaut.bump"
|
|
24
|
+
PUBDEPLOY = "pubdeploy"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def found(group: str, points: list[EntryPoint] | None = None) -> list[EntryPoint]:
|
|
28
|
+
return sorted(entry_points(group=group) if points is None else points, key=lambda p: (p.name, p.value))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def sync(root: Path, config: dict[str, Any], check: bool,
|
|
32
|
+
points: list[EntryPoint] | None = None) -> tuple[list[str], bool]:
|
|
33
|
+
hooks = found(SYNC, points)
|
|
34
|
+
out, failed = [], False
|
|
35
|
+
if isinstance(config.get("deploy"), dict) and not any(p.name == PUBDEPLOY for p in hooks):
|
|
36
|
+
out.append(f"pubrules: deploy: the deploy block is pubdeploy's to check, and pubdeploy is not installed: "
|
|
37
|
+
f"`pubrules sync` lists it in deploy.providers and tests/requirements-pubrules.txt; run "
|
|
38
|
+
f"`pubrules lock` and install the lock, or run ./pubrules, which runs with it")
|
|
39
|
+
failed = check
|
|
40
|
+
for point in hooks:
|
|
41
|
+
try:
|
|
42
|
+
lines, bad = point.load()(root, config, check)
|
|
43
|
+
except Exception as e: # noqa: BLE001 - a hook's failure is said, by its type alone
|
|
44
|
+
out.append(f"pubrules: the {SYNC} hook {point.name} failed ({type(e).__name__})")
|
|
45
|
+
failed = failed or check
|
|
46
|
+
continue
|
|
47
|
+
out += [str(line) for line in lines]
|
|
48
|
+
failed = failed or bool(bad)
|
|
49
|
+
return out, failed
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def bump(root: Path, points: list[EntryPoint] | None = None) -> list[str]:
|
|
53
|
+
out = []
|
|
54
|
+
for point in found(BUMP, points):
|
|
55
|
+
try:
|
|
56
|
+
out += [str(line) for line in point.load()(root)]
|
|
57
|
+
except Exception as e: # noqa: BLE001 - a hook's failure is said, by its type alone
|
|
58
|
+
out.append(f"pubrules: the {BUMP} hook {point.name} failed ({type(e).__name__})")
|
|
59
|
+
return out
|