preen 0.6.2__tar.gz → 0.7.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.
Files changed (48) hide show
  1. {preen-0.6.2 → preen-0.7.0}/PKG-INFO +34 -3
  2. {preen-0.6.2 → preen-0.7.0}/README.md +32 -2
  3. {preen-0.6.2 → preen-0.7.0}/pyproject.toml +2 -1
  4. {preen-0.6.2 → preen-0.7.0}/pyproject.toml.orig +3 -1
  5. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/__init__.py +2 -0
  6. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/base.py +106 -0
  7. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/codespell.py +19 -56
  8. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/deps.py +3 -21
  9. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/dropped_args.py +1 -1
  10. preen-0.7.0/src/preen/checks/duplicates.py +175 -0
  11. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/examples.py +1 -12
  12. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/license.py +3 -2
  13. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/links.py +1 -27
  14. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/pydoclint.py +8 -26
  15. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/pyright.py +8 -24
  16. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/ruff.py +3 -21
  17. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/tests.py +3 -21
  18. {preen-0.6.2 → preen-0.7.0}/src/preen/cli.py +9 -1
  19. {preen-0.6.2 → preen-0.7.0}/src/preen/commands/release.py +3 -3
  20. {preen-0.6.2 → preen-0.7.0}/src/preen/interactive.py +1 -1
  21. {preen-0.6.2 → preen-0.7.0}/LICENSE +0 -0
  22. {preen-0.6.2 → preen-0.7.0}/src/preen/__init__.py +0 -0
  23. {preen-0.6.2 → preen-0.7.0}/src/preen/__main__.py +0 -0
  24. {preen-0.6.2 → preen-0.7.0}/src/preen/adopt.py +0 -0
  25. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/audit.py +0 -0
  26. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/changelog.py +0 -0
  27. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/ci_matrix.py +0 -0
  28. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/citation.py +0 -0
  29. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/depgroups.py +0 -0
  30. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/deptree.py +0 -0
  31. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/files.py +0 -0
  32. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/metadata.py +0 -0
  33. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/precommit.py +0 -0
  34. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/pytest_config.py +0 -0
  35. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/python_floor.py +0 -0
  36. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/runner.py +0 -0
  37. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/runtime_assets.py +0 -0
  38. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/structure.py +0 -0
  39. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/template.py +0 -0
  40. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/version.py +0 -0
  41. {preen-0.6.2 → preen-0.7.0}/src/preen/checks/workflows.py +0 -0
  42. {preen-0.6.2 → preen-0.7.0}/src/preen/commands/__init__.py +0 -0
  43. {preen-0.6.2 → preen-0.7.0}/src/preen/commands/adopt.py +0 -0
  44. {preen-0.6.2 → preen-0.7.0}/src/preen/commands/fix.py +0 -0
  45. {preen-0.6.2 → preen-0.7.0}/src/preen/commands/new.py +0 -0
  46. {preen-0.6.2 → preen-0.7.0}/src/preen/commands/update.py +0 -0
  47. {preen-0.6.2 → preen-0.7.0}/src/preen/config.py +0 -0
  48. {preen-0.6.2 → preen-0.7.0}/src/preen/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: preen
3
- Version: 0.6.2
3
+ Version: 0.7.0
4
4
  Summary: Conformance and adoption CLI for the py-canon fleet standard
5
5
  Keywords: packaging,release,conformance,copier,cli,python
6
6
  Author: Gaurav Sood
@@ -21,6 +21,7 @@ Requires-Dist: ruff>=0.15.21
21
21
  Requires-Dist: pyright>=1.1.411
22
22
  Requires-Dist: pydoclint>=0.9.1
23
23
  Requires-Dist: codespell>=2.4.3
24
+ Requires-Dist: pylint>=4.1
24
25
  Requires-Dist: deptry>=0.20
25
26
  Requires-Dist: validate-pyproject>=0.26
26
27
  Requires-Dist: lychee-bin>=0.24.2
@@ -66,6 +67,31 @@ The bundled skill teaches Claude Code to reach for the preen CLI —
66
67
  scaffolding, adoption, checks, and releases — instead of reimplementing
67
68
  its logic.
68
69
 
70
+ ## Authority and assessment scope
71
+
72
+ [py-canon STANDARD.md](https://github.com/gojiplus/py-canon/blob/main/STANDARD.md)
73
+ defines fleet requirements. Preen implements checks and adoption for that
74
+ standard; its version identifies the implementation, not a new standard
75
+ revision. The bundled skill guides use of the CLI and does not duplicate its
76
+ checks or establish conformance by itself. Appellation separately governs
77
+ name-analysis results and empirical evidence.
78
+
79
+ A check run reports the checks executed and explicit exclusions. `--only`
80
+ is a partial assessment. Excluding every check exits with an error, and a
81
+ successful subset reports only that the executed checks passed. Individual
82
+ checks may also report unavailable subchecks; retain those notices in evidence.
83
+ Record the consumer commit, preen version, resolved canon/template revision,
84
+ configuration, and command alongside the output. A waiver or skip does not
85
+ prove the underlying requirement is satisfied.
86
+
87
+ Check implementations live in `src/preen/checks`; behavioral tests live in
88
+ `tests/test_*_check.py` and `tests/test_cli.py`. Adoption/update fixtures test
89
+ managed files and preservation of project-owned content. Changes to a fleet
90
+ rule must coordinate the py-canon requirement and template with the preen
91
+ implementation and regression tests. Synchronization tests detect copied
92
+ policy drift; if their remote source cannot be checked, report that test as
93
+ unverified rather than treating its skip as proof of synchronization.
94
+
69
95
  ## Commands
70
96
 
71
97
  | Command | What it does |
@@ -114,14 +140,16 @@ py-canon tag), `workflows` (the four canon workflows are callers of the
114
140
  reusable workflows, not stale copies), `ruff`, `tests`, `citation`,
115
141
  `changelog` (Keep a Changelog structure), `deps` (deptry), `deptree`
116
142
  (circular imports), `depgroups` (PEP 735 dependency-groups usage),
117
- `dropped-args` (a parameter a caller accepts but never forwards), `audit`
143
+ `dropped-args` (a parameter a caller accepts but never forwards),
144
+ `duplicate-code` (12+ lines of package code copied across modules), `audit`
118
145
  (pip-audit over the locked dependencies), `ci-matrix` (canon shim, or a
119
146
  matrix covering the requires-python floor), `structure`, `runtime-assets`
120
147
  (schema-bearing data formats, pinned Hugging Face revisions), `files`
121
148
  (README and `.gitignore` exist), `precommit` (`.pre-commit-config.yaml`
122
149
  exists and parses), `pytest-config` (pytest settings the standard requires), `examples` (documented examples still name symbols the package defines), `python-floor` (requires-python meets the floor the standard declares; off until the fleet migration lands), `version` (hardcoded version strings), `license` (PEP
123
150
  639 license metadata), `links`, `metadata` (build backend, requires-python
124
- upper bound, PEP 561 `py.typed`), `pydoclint`, `pyright`, and `codespell`.
151
+ upper bound, PEP 561 `py.typed`), `pydoclint`, `pyright`, and `codespell`
152
+ (typos and British spellings; the standard is US English).
125
153
 
126
154
  Issues carry an impact level: **critical** blocks release, **important** can
127
155
  be overridden with informed consent, **info** is advisory. `preen release`
@@ -175,6 +203,9 @@ audit_ignore = ["GHSA-8mgp-746c-j5xp"]
175
203
  the codes), but they're still preview-only, so `pydoclint` stays until
176
204
  ruff stabilizes them.
177
205
  - `codespell` stays: ruff has no spelling-check rules.
206
+ - `duplicate-code` runs pylint's similarity checker (R0801), the one pylint
207
+ rule kept: ruff has no duplicate detector. Mark a deliberate copy with
208
+ `# pylint: disable=duplicate-code`.
178
209
 
179
210
  ## License
180
211
 
@@ -33,6 +33,31 @@ The bundled skill teaches Claude Code to reach for the preen CLI —
33
33
  scaffolding, adoption, checks, and releases — instead of reimplementing
34
34
  its logic.
35
35
 
36
+ ## Authority and assessment scope
37
+
38
+ [py-canon STANDARD.md](https://github.com/gojiplus/py-canon/blob/main/STANDARD.md)
39
+ defines fleet requirements. Preen implements checks and adoption for that
40
+ standard; its version identifies the implementation, not a new standard
41
+ revision. The bundled skill guides use of the CLI and does not duplicate its
42
+ checks or establish conformance by itself. Appellation separately governs
43
+ name-analysis results and empirical evidence.
44
+
45
+ A check run reports the checks executed and explicit exclusions. `--only`
46
+ is a partial assessment. Excluding every check exits with an error, and a
47
+ successful subset reports only that the executed checks passed. Individual
48
+ checks may also report unavailable subchecks; retain those notices in evidence.
49
+ Record the consumer commit, preen version, resolved canon/template revision,
50
+ configuration, and command alongside the output. A waiver or skip does not
51
+ prove the underlying requirement is satisfied.
52
+
53
+ Check implementations live in `src/preen/checks`; behavioral tests live in
54
+ `tests/test_*_check.py` and `tests/test_cli.py`. Adoption/update fixtures test
55
+ managed files and preservation of project-owned content. Changes to a fleet
56
+ rule must coordinate the py-canon requirement and template with the preen
57
+ implementation and regression tests. Synchronization tests detect copied
58
+ policy drift; if their remote source cannot be checked, report that test as
59
+ unverified rather than treating its skip as proof of synchronization.
60
+
36
61
  ## Commands
37
62
 
38
63
  | Command | What it does |
@@ -81,14 +106,16 @@ py-canon tag), `workflows` (the four canon workflows are callers of the
81
106
  reusable workflows, not stale copies), `ruff`, `tests`, `citation`,
82
107
  `changelog` (Keep a Changelog structure), `deps` (deptry), `deptree`
83
108
  (circular imports), `depgroups` (PEP 735 dependency-groups usage),
84
- `dropped-args` (a parameter a caller accepts but never forwards), `audit`
109
+ `dropped-args` (a parameter a caller accepts but never forwards),
110
+ `duplicate-code` (12+ lines of package code copied across modules), `audit`
85
111
  (pip-audit over the locked dependencies), `ci-matrix` (canon shim, or a
86
112
  matrix covering the requires-python floor), `structure`, `runtime-assets`
87
113
  (schema-bearing data formats, pinned Hugging Face revisions), `files`
88
114
  (README and `.gitignore` exist), `precommit` (`.pre-commit-config.yaml`
89
115
  exists and parses), `pytest-config` (pytest settings the standard requires), `examples` (documented examples still name symbols the package defines), `python-floor` (requires-python meets the floor the standard declares; off until the fleet migration lands), `version` (hardcoded version strings), `license` (PEP
90
116
  639 license metadata), `links`, `metadata` (build backend, requires-python
91
- upper bound, PEP 561 `py.typed`), `pydoclint`, `pyright`, and `codespell`.
117
+ upper bound, PEP 561 `py.typed`), `pydoclint`, `pyright`, and `codespell`
118
+ (typos and British spellings; the standard is US English).
92
119
 
93
120
  Issues carry an impact level: **critical** blocks release, **important** can
94
121
  be overridden with informed consent, **info** is advisory. `preen release`
@@ -142,6 +169,9 @@ audit_ignore = ["GHSA-8mgp-746c-j5xp"]
142
169
  the codes), but they're still preview-only, so `pydoclint` stays until
143
170
  ruff stabilizes them.
144
171
  - `codespell` stays: ruff has no spelling-check rules.
172
+ - `duplicate-code` runs pylint's similarity checker (R0801), the one pylint
173
+ rule kept: ruff has no duplicate detector. Mark a deliberate copy with
174
+ `# pylint: disable=duplicate-code`.
145
175
 
146
176
  ## License
147
177
 
@@ -5,7 +5,7 @@ readme = "README.md"
5
5
  license = "MIT"
6
6
  license-files = ["LICENSE"]
7
7
  requires-python = ">=3.12"
8
- version = "0.6.2"
8
+ version = "0.7.0"
9
9
  keywords = [
10
10
  "packaging",
11
11
  "release",
@@ -31,6 +31,7 @@ dependencies = [
31
31
  "pyright>=1.1.411",
32
32
  "pydoclint>=0.9.1",
33
33
  "codespell>=2.4.3",
34
+ "pylint>=4.1",
34
35
  "deptry>=0.20",
35
36
  "validate-pyproject>=0.26",
36
37
  "lychee-bin>=0.24.2",
@@ -6,7 +6,7 @@ license = "MIT"
6
6
  license-files = ["LICENSE"]
7
7
  authors = [{ name = "Gaurav Sood", email = "contact@gsood.com" }]
8
8
  requires-python = ">=3.12"
9
- version = "0.6.2"
9
+ version = "0.7.0"
10
10
  keywords = ["packaging", "release", "conformance", "copier", "cli", "python"]
11
11
  classifiers = [
12
12
  "Intended Audience :: Developers",
@@ -29,6 +29,8 @@ dependencies = [
29
29
  "pyright>=1.1.411",
30
30
  "pydoclint>=0.9.1",
31
31
  "codespell>=2.4.3",
32
+ # duplicate-code (R0801); ruff has no duplicate detector.
33
+ "pylint>=4.1",
32
34
  "deptry>=0.20",
33
35
  # The `metadata` check validates pyproject.toml against PyPA's own
34
36
  # schemas before reading it, so a malformed table is named as such
@@ -14,6 +14,7 @@ from .depgroups import DepgroupsCheck
14
14
  from .deps import DepsCheck
15
15
  from .deptree import DeptreeCheck
16
16
  from .dropped_args import DroppedArgsCheck
17
+ from .duplicates import DuplicateCodeCheck
17
18
  from .examples import ExamplesCheck
18
19
  from .files import RequiredFilesCheck
19
20
  from .license import LicenseCheck
@@ -43,6 +44,7 @@ ALL_CHECKS: list[type[Check]] = [
43
44
  DeptreeCheck,
44
45
  DepgroupsCheck,
45
46
  DroppedArgsCheck,
47
+ DuplicateCodeCheck,
46
48
  AuditCheck,
47
49
  CIMatrixCheck,
48
50
  StructureCheck,
@@ -1,5 +1,6 @@
1
1
  """Base classes for the check framework."""
2
2
 
3
+ import subprocess
3
4
  from abc import ABC, abstractmethod
4
5
  from collections.abc import Callable
5
6
  from dataclasses import dataclass, field
@@ -193,6 +194,111 @@ class Check(ABC):
193
194
  self._lint_excluded_dirs = frozenset(names)
194
195
  return self._lint_excluded_dirs
195
196
 
197
+ def missing_tool(
198
+ self,
199
+ version_cmd: list[str],
200
+ tool: str,
201
+ *,
202
+ explanation: str = "",
203
+ impact: Impact = Impact.IMPORTANT,
204
+ ) -> "CheckResult | None":
205
+ """Return a failed result if a tool this check runs is not installed.
206
+
207
+ Args:
208
+ version_cmd: The tool's ``--version`` command line.
209
+ tool: The tool's name, as installed with pip.
210
+ explanation: Why the check needs it.
211
+ impact: How seriously a missing tool counts.
212
+
213
+ Returns:
214
+ None when ``version_cmd`` runs, otherwise a failed CheckResult.
215
+ """
216
+ try:
217
+ subprocess.run(
218
+ version_cmd, capture_output=True, check=True, cwd=self.project_dir
219
+ )
220
+ except (subprocess.SubprocessError, FileNotFoundError):
221
+ return CheckResult(
222
+ check=self.name,
223
+ passed=False,
224
+ issues=[
225
+ Issue(
226
+ check=self.name,
227
+ severity=Severity.ERROR,
228
+ description=(
229
+ f"{tool} is not installed. Install with: pip install {tool}"
230
+ ),
231
+ impact=impact,
232
+ explanation=explanation,
233
+ )
234
+ ],
235
+ )
236
+ return None
237
+
238
+ def package_dirs(self) -> list[Path]:
239
+ """Locate the project's import packages.
240
+
241
+ A directory under ``src/`` holding an ``__init__.py``, or, without
242
+ ``src/``, such a directory at the project root outside the excluded
243
+ ones. Scripts, notebooks and loose modules beside the package are not
244
+ package code.
245
+
246
+ Returns:
247
+ The package directories, absolute, sorted by name.
248
+ """
249
+ # Under src/ every child is a package, even one named like an
250
+ # artifact directory ("build"); at the root those names are artifacts.
251
+ src = self.project_dir / "src"
252
+ if src.is_dir():
253
+ return sorted(d for d in src.iterdir() if (d / "__init__.py").exists())
254
+ return sorted(
255
+ d
256
+ for d in self.project_dir.iterdir()
257
+ if d.is_dir()
258
+ and d.name not in self.excluded_dirs()
259
+ and (d / "__init__.py").exists()
260
+ )
261
+
262
+ def project_files(self) -> list[Path]:
263
+ """List the project's files: what Git tracks or would track.
264
+
265
+ Untracked files count unless ignored, so a check sees new work before
266
+ it is committed; a tracked file deleted from the working tree does not.
267
+ Outside a Git checkout, every file counts.
268
+
269
+ Returns:
270
+ Project-relative paths, in no particular order.
271
+ """
272
+ if (self.project_dir / ".git").exists():
273
+ try:
274
+ result = subprocess.run(
275
+ [
276
+ "git",
277
+ "ls-files",
278
+ "-z",
279
+ "--cached",
280
+ "--others",
281
+ "--exclude-standard",
282
+ ],
283
+ capture_output=True,
284
+ text=True,
285
+ check=True,
286
+ cwd=self.project_dir,
287
+ )
288
+ except (subprocess.SubprocessError, FileNotFoundError):
289
+ pass
290
+ else:
291
+ return [
292
+ Path(value)
293
+ for value in result.stdout.split("\0")
294
+ if value and (self.project_dir / value).is_file()
295
+ ]
296
+ return [
297
+ path.relative_to(self.project_dir)
298
+ for path in self.project_dir.rglob("*")
299
+ if path.is_file()
300
+ ]
301
+
196
302
  def is_excluded(self, path: Path) -> bool:
197
303
  """Return True if a project-relative path lies under an excluded dir.
198
304
 
@@ -39,7 +39,7 @@ def is_auto_fixable(file_path: Path) -> bool:
39
39
 
40
40
 
41
41
  class CodespellCheck(Check):
42
- """Check for spelling errors in documentation and comments using codespell."""
42
+ """Check spelling, in US English, in documentation and code using codespell."""
43
43
 
44
44
  @property
45
45
  def name(self) -> str:
@@ -49,7 +49,7 @@ class CodespellCheck(Check):
49
49
  @property
50
50
  def description(self) -> str:
51
51
  """Return a description of what this check does."""
52
- return "Check spelling in documentation and comments with codespell"
52
+ return "Check spelling, in US English, with codespell"
53
53
 
54
54
  def _parse_codespell_output(self, output: str) -> list[Issue]:
55
55
  """Parse codespell output and convert to Issue objects."""
@@ -147,6 +147,12 @@ class CodespellCheck(Check):
147
147
 
148
148
  # Focus on text files and code
149
149
  # Don't spell check binary files, images, etc.
150
+ # The standard is US English. codespell's default dictionaries are
151
+ # "clear,rare", and en-GB_to_en-US adds British spellings. Data and
152
+ # fixture directories are never read, so a place name in a gazetteer
153
+ # keeps its spelling.
154
+ cmd.extend(["--builtin", "clear,rare,en-GB_to_en-US"])
155
+
150
156
  cmd.extend(
151
157
  [
152
158
  "--check-filenames", # Also check file names
@@ -170,33 +176,7 @@ class CodespellCheck(Check):
170
176
  Returns:
171
177
  Sorted repo-relative paths suitable for passing to codespell.
172
178
  """
173
- paths: list[Path] | None = None
174
- if (self.project_dir / ".git").exists():
175
- try:
176
- result = subprocess.run(
177
- [
178
- "git",
179
- "ls-files",
180
- "-z",
181
- "--cached",
182
- "--others",
183
- "--exclude-standard",
184
- ],
185
- capture_output=True,
186
- text=True,
187
- check=True,
188
- cwd=self.project_dir,
189
- )
190
- except (subprocess.SubprocessError, FileNotFoundError):
191
- pass
192
- else:
193
- paths = [Path(value) for value in result.stdout.split("\0") if value]
194
- if paths is None:
195
- paths = [
196
- path.relative_to(self.project_dir)
197
- for path in self.project_dir.rglob("*")
198
- if path.is_file()
199
- ]
179
+ paths = self.project_files()
200
180
 
201
181
  return sorted(
202
182
  path
@@ -211,33 +191,16 @@ class CodespellCheck(Check):
211
191
  issues: list[Issue] = []
212
192
 
213
193
  # Check if codespell is available
214
- try:
215
- subprocess.run(
216
- ["codespell", "--version"],
217
- capture_output=True,
218
- check=True,
219
- cwd=self.project_dir,
220
- )
221
- except (subprocess.SubprocessError, FileNotFoundError):
222
- return CheckResult(
223
- check=self.name,
224
- passed=False,
225
- issues=[
226
- Issue(
227
- check=self.name,
228
- severity=Severity.ERROR,
229
- description=(
230
- "codespell is not installed. "
231
- "Install with: pip install codespell"
232
- ),
233
- impact=Impact.CRITICAL,
234
- explanation=(
235
- "codespell is required for spell checking "
236
- "documentation and comments"
237
- ),
238
- )
239
- ],
240
- )
194
+ missing = self.missing_tool(
195
+ ["codespell", "--version"],
196
+ "codespell",
197
+ explanation=(
198
+ "codespell is required for spell checking documentation and comments"
199
+ ),
200
+ impact=Impact.CRITICAL,
201
+ )
202
+ if missing is not None:
203
+ return missing
241
204
 
242
205
  candidates = self._candidate_files()
243
206
  for start in range(0, len(candidates), COMMAND_BATCH_SIZE):
@@ -23,27 +23,9 @@ class DepsCheck(Check):
23
23
  issues = []
24
24
 
25
25
  # Check if deptry is available
26
- try:
27
- subprocess.run(
28
- ["deptry", "--version"],
29
- capture_output=True,
30
- check=True,
31
- cwd=self.project_dir,
32
- )
33
- except (subprocess.SubprocessError, FileNotFoundError):
34
- return CheckResult(
35
- check=self.name,
36
- passed=False,
37
- issues=[
38
- Issue(
39
- check=self.name,
40
- severity=Severity.ERROR,
41
- description=(
42
- "deptry is not installed. Install with: pip install deptry"
43
- ),
44
- )
45
- ],
46
- )
26
+ missing = self.missing_tool(["deptry", "--version"], "deptry")
27
+ if missing is not None:
28
+ return missing
47
29
 
48
30
  # Run deptry
49
31
  result = subprocess.run(
@@ -12,7 +12,7 @@ signatures gives it away.
12
12
 
13
13
  This is worth its own check because the failure is silent and the blast radius
14
14
  is whatever the parameter controlled. One package shipped three of them: a
15
- confidence level that left one interval at 95% while its neighbour honoured the
15
+ confidence level that left one interval at 95% while its neighbor honored the
16
16
  request, a subsampling cap that never reached the routine that subsamples, and
17
17
  a coverage simulation whose bootstrap arm reported identical coverage at every
18
18
  nominal level because the level never arrived.
@@ -0,0 +1,175 @@
1
+ """Find copied blocks of package code with pylint's duplicate-code detector.
2
+
3
+ ruff is the standard's only linter, and ruff has no duplicate-code rule, so a
4
+ block pasted into a second module passed every check. Copies drift: the fix
5
+ lands in one and not the other. In rank-preserving-calibration, three
6
+ copies of one isotonic regression diverged until one mishandled weights.
7
+
8
+ pylint's similarity checker (R0801) is the established tool for this, so this
9
+ check runs it rather than reimplementing it, on the import package only:
10
+ tests, docs, examples, and scripts or notebooks outside the package
11
+ repeat setup by design. The threshold is 12
12
+ matching lines, ignoring imports, docstrings, comments and signatures; at 6,
13
+ half the fleet flagged boilerplate, and at 12 every hit sampled was a real
14
+ copy.
15
+
16
+ Suppress a deliberate duplicate with pylint's own marker,
17
+ ``# pylint: disable=duplicate-code``, in one of the two blocks.
18
+ """
19
+
20
+ import json
21
+ import re
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ from .base import Check, CheckResult, Impact, Issue, Severity
27
+
28
+ MIN_SIMILARITY_LINES = 12
29
+
30
+ NOT_PACKAGE_DIRS = frozenset({"tests", "test", "docs", "examples", "benchmarks"})
31
+
32
+ _BLOCK = re.compile(r"^==(?P<module>[\w.]+):\[(?P<start>\d+):(?P<end>\d+)\]$")
33
+
34
+
35
+ class DuplicateCodeCheck(Check):
36
+ """Report blocks of package code duplicated across modules."""
37
+
38
+ @property
39
+ def name(self) -> str:
40
+ """Return the name of this check."""
41
+ return "duplicate-code"
42
+
43
+ @property
44
+ def description(self) -> str:
45
+ """Return a description of what this check does."""
46
+ return "Find copied blocks of package code (pylint duplicate-code)"
47
+
48
+ def _package_files(self) -> list[Path]:
49
+ """Return the Python files of the project's import packages.
50
+
51
+ Returns:
52
+ Sorted project-relative paths inside the package directories,
53
+ skipping lint-excluded and test directories within them.
54
+ """
55
+ # In a src/ layout everything under src/ is package code, including a
56
+ # namespace package with no top-level __init__.py.
57
+ src = self.project_dir / "src"
58
+ roots = [src] if src.is_dir() else self.package_dirs()
59
+ packages = [p.relative_to(self.project_dir) for p in roots]
60
+ files = []
61
+ # project_files() respects .gitignore, so ignored files inside a
62
+ # package are not package code either.
63
+ for rel in self.project_files():
64
+ if rel.suffix != ".py" or not any(
65
+ rel.is_relative_to(package) for package in packages
66
+ ):
67
+ continue
68
+ if self.is_lint_excluded(rel):
69
+ continue
70
+ if any(part in NOT_PACKAGE_DIRS for part in rel.parts[:-1]):
71
+ continue
72
+ if rel.name.startswith("test_") or rel.name == "conftest.py":
73
+ continue
74
+ files.append(rel)
75
+ return sorted(files)
76
+
77
+ def run(self) -> CheckResult:
78
+ """Run pylint's duplicate-code checker over the package.
79
+
80
+ Returns:
81
+ CheckResult with one issue per duplicated block.
82
+ """
83
+ files = self._package_files()
84
+ if len(files) < 2:
85
+ return CheckResult(check=self.name, passed=True, issues=[])
86
+
87
+ # Through this interpreter, not a bare `pylint`: `uv tool install` and
88
+ # pipx put only preen's own entry point on PATH, not its dependencies'.
89
+ cmd = [
90
+ sys.executable,
91
+ "-m",
92
+ "pylint",
93
+ "--disable=all",
94
+ "--enable=duplicate-code",
95
+ # pylint flags runs strictly longer than this, so 12+ needs 11.
96
+ f"--min-similarity-lines={MIN_SIMILARITY_LINES - 1}",
97
+ "--ignore-imports=y",
98
+ "--ignore-docstrings=y",
99
+ "--ignore-comments=y",
100
+ "--ignore-signatures=y",
101
+ "--output-format=json",
102
+ "--score=n",
103
+ *(str(f) for f in files),
104
+ ]
105
+ # A missing pylint module is exit status 1 with "No module named
106
+ # pylint", which the exit-status check below reports.
107
+ result = subprocess.run(
108
+ cmd, capture_output=True, text=True, cwd=self.project_dir
109
+ )
110
+
111
+ # pylint's exit status is a bitmask: 8 means refactor messages were
112
+ # found. 1 (fatal), 32 (usage error, e.g. a bad .pylintrc) and, with
113
+ # every other message disabled, 2 (a file that failed to parse) mean
114
+ # the analysis did not complete; reading that as "no findings" would
115
+ # pass a check that did not happen.
116
+ if result.returncode & (1 | 2 | 32):
117
+ return CheckResult(
118
+ check=self.name,
119
+ passed=False,
120
+ issues=[
121
+ Issue(
122
+ check=self.name,
123
+ severity=Severity.ERROR,
124
+ description=f"pylint failed to run (exit {result.returncode})",
125
+ impact=Impact.CRITICAL,
126
+ explanation=(result.stderr or result.stdout)[:500],
127
+ )
128
+ ],
129
+ )
130
+
131
+ try:
132
+ messages = json.loads(result.stdout or "[]")
133
+ except json.JSONDecodeError:
134
+ return CheckResult(
135
+ check=self.name,
136
+ passed=False,
137
+ issues=[
138
+ Issue(
139
+ check=self.name,
140
+ severity=Severity.ERROR,
141
+ description=f"pylint exited {result.returncode} "
142
+ "without JSON output",
143
+ impact=Impact.CRITICAL,
144
+ explanation=(result.stderr or result.stdout)[:500],
145
+ )
146
+ ],
147
+ )
148
+
149
+ # pylint files R0801 under whichever module it read last, often neither
150
+ # of the two copies, so the location is the blocks named here, not a
151
+ # file and line.
152
+ issues = []
153
+ for message in messages:
154
+ if message.get("symbol") != "duplicate-code":
155
+ continue
156
+ lines = message.get("message", "").splitlines()
157
+ blocks = [m for m in (_BLOCK.match(line) for line in lines) if m]
158
+ where = ", ".join(
159
+ f"{b['module']} lines {b['start']}-{b['end']}" for b in blocks
160
+ )
161
+ size = int(blocks[0]["end"]) - int(blocks[0]["start"]) if blocks else 0
162
+ issues.append(
163
+ Issue(
164
+ check=self.name,
165
+ severity=Severity.WARNING,
166
+ description=f"{size} duplicated lines: {where}",
167
+ impact=Impact.IMPORTANT,
168
+ explanation=(
169
+ "Copied code drifts: a fix lands in one copy and not "
170
+ "the other. Extract the shared block, or mark a "
171
+ "deliberate copy `# pylint: disable=duplicate-code`."
172
+ ),
173
+ )
174
+ )
175
+ return CheckResult(check=self.name, passed=not issues, issues=issues)
@@ -953,18 +953,7 @@ class ExamplesCheck(Check):
953
953
  An ``(import name, path)`` pair, or None where there is no single
954
954
  obvious package to check against.
955
955
  """
956
- src = self.project_dir / "src"
957
- candidates = (
958
- [d for d in src.iterdir() if (d / "__init__.py").exists()]
959
- if src.is_dir()
960
- else [
961
- d
962
- for d in self.project_dir.iterdir()
963
- if d.is_dir()
964
- and d.name not in self.excluded_dirs()
965
- and (d / "__init__.py").exists()
966
- ]
967
- )
956
+ candidates = self.package_dirs()
968
957
  if len(candidates) != 1:
969
958
  return None
970
959
  return candidates[0].name, candidates[0] / "__init__.py"
@@ -52,7 +52,8 @@ LEGACY_TEXT_ALIASES = {
52
52
  "Apache License, Version 2.0": "Apache-2.0",
53
53
  }
54
54
 
55
- LICENSE_FILE_STEMS = ("license", "licence", "copying")
55
+ # British spelling on purpose: it is a filename this check must recognize.
56
+ LICENSE_FILE_STEMS = ("license", "licence", "copying") # codespell:ignore licence
56
57
 
57
58
  # The operator alternatives need a trailing word-boundary guard, or an
58
59
  # identifier that merely starts with one (a hypothetical "ANDover-1.0") would
@@ -366,7 +367,7 @@ class LicenseCheck(Check):
366
367
  )
367
368
 
368
369
  def _find_license_file(self) -> Path | None:
369
- """Return a LICENSE/LICENCE/COPYING file at the repo root, if any."""
370
+ """Return the repo-root license file, by any stem above, if there is one."""
370
371
  for entry in sorted(self.project_dir.iterdir()):
371
372
  if entry.is_file() and entry.stem.lower() in LICENSE_FILE_STEMS:
372
373
  return entry
@@ -158,33 +158,7 @@ class LinkCheck(Check):
158
158
  Returns:
159
159
  Sorted list of absolute paths.
160
160
  """
161
- paths: list[Path] | None = None
162
- if (self.project_dir / ".git").exists():
163
- try:
164
- result = subprocess.run(
165
- [
166
- "git",
167
- "ls-files",
168
- "-z",
169
- "--cached",
170
- "--others",
171
- "--exclude-standard",
172
- ],
173
- capture_output=True,
174
- text=True,
175
- check=True,
176
- cwd=self.project_dir,
177
- )
178
- except (subprocess.SubprocessError, FileNotFoundError):
179
- pass
180
- else:
181
- paths = [Path(value) for value in result.stdout.split("\0") if value]
182
- if paths is None:
183
- paths = [
184
- path.relative_to(self.project_dir)
185
- for path in self.project_dir.rglob("*")
186
- if path.is_file()
187
- ]
161
+ paths = self.project_files()
188
162
 
189
163
  return sorted(
190
164
  self.project_dir / path
@@ -253,32 +253,14 @@ class PydoclintCheck(Check):
253
253
  issues = []
254
254
 
255
255
  # Check if pydoclint is available
256
- try:
257
- subprocess.run(
258
- ["pydoclint", "--version"],
259
- capture_output=True,
260
- check=True,
261
- cwd=self.project_dir,
262
- )
263
- except (subprocess.SubprocessError, FileNotFoundError):
264
- return CheckResult(
265
- check=self.name,
266
- passed=False,
267
- issues=[
268
- Issue(
269
- check=self.name,
270
- severity=Severity.ERROR,
271
- description=(
272
- "pydoclint is not installed. "
273
- "Install with: pip install pydoclint"
274
- ),
275
- impact=Impact.CRITICAL,
276
- explanation=(
277
- "pydoclint is required for docstring quality checking"
278
- ),
279
- )
280
- ],
281
- )
256
+ missing = self.missing_tool(
257
+ ["pydoclint", "--version"],
258
+ "pydoclint",
259
+ explanation="pydoclint is required for docstring quality checking",
260
+ impact=Impact.CRITICAL,
261
+ )
262
+ if missing is not None:
263
+ return missing
282
264
 
283
265
  # Run pydoclint on the project directory
284
266
  # Use --quiet to suppress file scanning output, only show violations
@@ -153,30 +153,14 @@ class PyrightCheck(Check):
153
153
  else:
154
154
  pyright_cmd = ["pyright"]
155
155
 
156
- try:
157
- subprocess.run(
158
- [*pyright_cmd, "--version"],
159
- capture_output=True,
160
- check=True,
161
- cwd=self.project_dir,
162
- )
163
- except (subprocess.SubprocessError, FileNotFoundError):
164
- return CheckResult(
165
- check=self.name,
166
- passed=False,
167
- issues=[
168
- Issue(
169
- check=self.name,
170
- severity=Severity.ERROR,
171
- description=(
172
- "pyright is not installed. "
173
- "Install with: pip install pyright"
174
- ),
175
- impact=Impact.CRITICAL,
176
- explanation="pyright is required for static type checking",
177
- )
178
- ],
179
- )
156
+ missing = self.missing_tool(
157
+ [*pyright_cmd, "--version"],
158
+ "pyright",
159
+ explanation="pyright is required for static type checking",
160
+ impact=Impact.CRITICAL,
161
+ )
162
+ if missing is not None:
163
+ return missing
180
164
 
181
165
  # Run pyright with JSON output for easier parsing
182
166
  # No explicit path: let pyright use the repo's own include/exclude
@@ -28,27 +28,9 @@ class RuffCheck(Check):
28
28
  issues = []
29
29
 
30
30
  # Check if ruff is available
31
- try:
32
- subprocess.run(
33
- [*ruff_cmd, "--version"],
34
- capture_output=True,
35
- check=True,
36
- cwd=self.project_dir,
37
- )
38
- except (subprocess.SubprocessError, FileNotFoundError):
39
- return CheckResult(
40
- check=self.name,
41
- passed=False,
42
- issues=[
43
- Issue(
44
- check=self.name,
45
- severity=Severity.ERROR,
46
- description=(
47
- "ruff is not installed. Install with: pip install ruff"
48
- ),
49
- )
50
- ],
51
- )
31
+ missing = self.missing_tool([*ruff_cmd, "--version"], "ruff")
32
+ if missing is not None:
33
+ return missing
52
34
 
53
35
  # Run ruff check
54
36
  lint_result = subprocess.run(
@@ -28,27 +28,9 @@ class TestsCheck(Check):
28
28
  else:
29
29
  pytest_cmd = ["python3", "-m", "pytest"]
30
30
 
31
- try:
32
- subprocess.run(
33
- [*pytest_cmd, "--version"],
34
- capture_output=True,
35
- check=True,
36
- cwd=self.project_dir,
37
- )
38
- except (subprocess.SubprocessError, FileNotFoundError):
39
- return CheckResult(
40
- check=self.name,
41
- passed=False,
42
- issues=[
43
- Issue(
44
- check=self.name,
45
- severity=Severity.ERROR,
46
- description=(
47
- "pytest is not installed. Install with: pip install pytest"
48
- ),
49
- )
50
- ],
51
- )
31
+ missing = self.missing_tool([*pytest_cmd, "--version"], "pytest")
32
+ if missing is not None:
33
+ return missing
52
34
 
53
35
  # Run pytest
54
36
  result = subprocess.run(
@@ -146,6 +146,14 @@ def check(
146
146
  except ValueError as error:
147
147
  console.print(f"[bold red]{error}[/bold red]")
148
148
  raise typer.Exit(2) from error
149
+ if merged_skip:
150
+ console.print(f"Skipped checks: {escape(', '.join(sorted(set(merged_skip))))}")
151
+ if only:
152
+ console.print(f"Requested checks: {escape(', '.join(only))}")
153
+ if not results:
154
+ console.print("[bold red]No checks ran; conformance is unassessed.[/bold red]")
155
+ raise typer.Exit(2)
156
+ console.print(f"Executed {len(results)} check(s).")
149
157
  educator = EducationalPrompt(console)
150
158
 
151
159
  table = Table(show_header=True, header_style="bold cyan")
@@ -198,7 +206,7 @@ def check(
198
206
  console.print(table)
199
207
 
200
208
  if total_issues == 0:
201
- console.print("\n[bold green]All checks passed.[/bold green]\n")
209
+ console.print("\n[bold green]All executed checks passed.[/bold green]\n")
202
210
  else:
203
211
  console.print(f"\n[bold]Found {total_issues} issue(s)[/bold]")
204
212
  if critical_count > 0:
@@ -423,7 +423,7 @@ def release_package(
423
423
  # Dry runs are fully non-interactive: no confirmation gates, no prompts.
424
424
  if not dry_run:
425
425
  if not workflow.run_release_checks(results, "GitHub (tag push)"):
426
- console.print("\n[red]Release cancelled[/red]")
426
+ console.print("\n[red]Release canceled[/red]")
427
427
  raise typer.Exit(1)
428
428
 
429
429
  dirty = _git(project_dir, "status", "--porcelain").stdout.strip()
@@ -544,7 +544,7 @@ def release_package(
544
544
  f"[{version}] - {today}?",
545
545
  default=True,
546
546
  ):
547
- console.print("[red]Release cancelled[/red]")
547
+ console.print("[red]Release canceled[/red]")
548
548
  raise typer.Exit(1)
549
549
 
550
550
  bumps = [
@@ -557,7 +557,7 @@ def release_package(
557
557
  ]
558
558
 
559
559
  if not Confirm.ask(f"\nTag and push [bold]{tag}[/bold]?", default=False):
560
- console.print("[red]Release cancelled[/red]")
560
+ console.print("[red]Release canceled[/red]")
561
561
  raise typer.Exit(1)
562
562
 
563
563
  release_paths: list[str] = []
@@ -104,7 +104,7 @@ class InteractiveReleaseWorkflow:
104
104
  )
105
105
 
106
106
  if not Confirm.ask(question, default=False):
107
- self.console.print("❌ [red]Release cancelled by user[/red]")
107
+ self.console.print("❌ [red]Release canceled by user[/red]")
108
108
  return False
109
109
  self.console.print(" ⚠️ [yellow]Proceeding despite issue[/yellow]")
110
110
  self.overrides[f"{issue.check}:{issue.description}"] = True
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes