pkgdx 0.6.0__tar.gz → 0.8.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.
@@ -45,4 +45,6 @@ ICM/**/output/*
45
45
  # skill-creator — eval workspaces
46
46
  .claude/skills/*-workspace/
47
47
 
48
- .mcp.json
48
+ .mcp.json
49
+
50
+ .env*
@@ -18,6 +18,50 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [0.8.0] - 2026-11-03
22
+
23
+ ### Added
24
+
25
+ - `-q`, `--no-color` & `--no-input` run flags, `GLOBAL OPTIONS:` in `--help` & `-h` after a usage
26
+ error, from `pyclig` 0.3.0.
27
+ - `test_cli_conforms_to_the_guidelines` runs `pyclig`'s conformance kit against the CLI.
28
+
29
+ ### Changed
30
+
31
+ - `pyclig` is pinned to `~=0.3.0` (was `~=0.2`).
32
+ - `--help` lists `EXAMPLES:` before `OPTIONS:`.
33
+ - `ToolNotFoundError` carries a `hint`. A hook shim whose tool is missing from `PATH` prints
34
+ `error:` with the fact, then the remedy on the next line.
35
+
36
+ ### Fixed
37
+
38
+ - `-q` on `pkgdx init` & `pkgdx config` drops the OK rows & the closing line. Warnings, failures &
39
+ `config`'s STDOUT rows stay.
40
+
41
+ ## [0.7.0] - 2026-11-02
42
+
43
+ ### Added
44
+
45
+ - `[tool.pkgdx] exclude` in `pyproject.toml` lists paths the lint, format, typing & markdown hooks
46
+ skip.
47
+ - `pkgdx config` lists each excluded path, marking one that does not exist `(not found)`.
48
+
49
+ ### Changed
50
+
51
+ - `docs/guidance/toolchain-pkgdx.md` (1.1.0) & `toolchain-mypy.md` (1.0.1) describe the exclude
52
+ list.
53
+
54
+ ### Fixed
55
+
56
+ - The lint, format & typing hooks can skip submodules & vendored code (#5). This needs no reset, but
57
+ both a `pkgdx` lock upgrade & `prek update`.
58
+ - The bundled `ruff.toml` no longer clears Ruff's default exclusions. A directory Ruff skips by
59
+ default, e.g. `dist`, `_build`, `venv` or `node_modules`, is no longer linted or formatted at any
60
+ depth, even when not gitignored. Exported user copies keep the old `exclude = []` until that line
61
+ is deleted.
62
+ - The `prek.toml` template's `#:schema` URL points at prek's `main` branch (it returned a 404).
63
+ - `pkgdx init` creates `.secrets.baseline` with the same exclude pattern as the `pkgdx-secrets` hook.
64
+
21
65
  ## [0.6.0] - 2026-10-31
22
66
 
23
67
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pkgdx
3
- Version: 0.6.0
3
+ Version: 0.8.0
4
4
  Summary: A package to centralise standards across Python projects.
5
5
  Project-URL: Documentation, https://gitlab.com/andyrids/pkgdx/blob/main/README.md
6
6
  Project-URL: Repository, https://gitlab.com/andyrids/pkgdx
@@ -27,7 +27,7 @@ Requires-Dist: click~=8.5
27
27
  Requires-Dist: detect-secrets>=1.5.0
28
28
  Requires-Dist: mypy>=2.1.0
29
29
  Requires-Dist: prek~=0.4.8
30
- Requires-Dist: pyclig~=0.2
30
+ Requires-Dist: pyclig~=0.3.0
31
31
  Requires-Dist: pymarkdownlnt>=0.9.37
32
32
  Requires-Dist: rich>=15.0.0
33
33
  Requires-Dist: ruff>=0.15.20
@@ -170,7 +170,7 @@ uv add --dev git+https://gitlab.com/andyrids/pkgdx.git
170
170
  ```
171
171
 
172
172
  ```bash
173
- uv add --dev git+https://gitlab.com/andyrids/pkgdx.git@v0.6.0
173
+ uv add --dev git+https://gitlab.com/andyrids/pkgdx.git@v0.8.0
174
174
  ```
175
175
 
176
176
  ## CI/CD integration
@@ -182,6 +182,30 @@ heavy boilerplate across each CI/CD YAML config.
182
182
  > See `ruff-lint-job` in the project
183
183
  > [.gitlab-ci.yml](https://gitlab.com/andyrids/pkgdx/-/blob/main/.gitlab-ci.yml) for an example.
184
184
 
185
+ ## Excluding files and folders
186
+
187
+ The lint, format and typing hooks walk your project themselves, so they check and auto-fix
188
+ everything they find. To leave submodules, vendored code or generated files alone, list them in your
189
+ project's `pyproject.toml`:
190
+
191
+ ```toml
192
+ [tool.pkgdx]
193
+ exclude = ["submodules", "vendor", "src/app/_gen.py"]
194
+ ```
195
+
196
+ Entries are literal paths relative to that file, `/` separated and case-sensitive. A folder covers
197
+ everything below it, and `vendor` never matches `src/vendor`. Globs are rejected, and an invalid
198
+ list fails the hook before any tool runs.
199
+
200
+ The list is committed, so it applies in CI and survives `pkgdx init --reset` and hook updates. It
201
+ also applies to the markdown hook, but `pkgdx-secrets` keeps scanning listed paths, because a secret
202
+ in vendored code is still a leaked secret. Run `uv run pkgdx config` to see the list in effect.
203
+
204
+ > [!NOTE]
205
+ > See [the guidance](https://gitlab.com/andyrids/pkgdx/-/blob/main/docs/guidance/toolchain-pkgdx.md)
206
+ > for the full rules. When upgrading, move both the `pkgdx` lock and the hook `rev` before relying
207
+ > on the list.
208
+
185
209
  ## Adopting your own standards (external users)
186
210
 
187
211
  `pkgdx` ships bundled canonical standards. To change them without forking, place your own files in a
@@ -230,8 +254,8 @@ uv run pkgdx config
230
254
  ```
231
255
 
232
256
  This prints one row per file on standard output: its name, its source (`user` or `bundled`) and
233
- its resolved path. A summary line on standard error names the user config directory and whether
234
- `PKGDX_CONFIG_DIR` set it.
257
+ its resolved path, then one row per [excluded path](#excluding-files-and-folders). A summary line on
258
+ standard error names the user config directory and whether `PKGDX_CONFIG_DIR` set it.
235
259
 
236
260
  To start from the bundled files, export them into the user config directory:
237
261
 
@@ -134,7 +134,7 @@ uv add --dev git+https://gitlab.com/andyrids/pkgdx.git
134
134
  ```
135
135
 
136
136
  ```bash
137
- uv add --dev git+https://gitlab.com/andyrids/pkgdx.git@v0.6.0
137
+ uv add --dev git+https://gitlab.com/andyrids/pkgdx.git@v0.8.0
138
138
  ```
139
139
 
140
140
  ## CI/CD integration
@@ -146,6 +146,30 @@ heavy boilerplate across each CI/CD YAML config.
146
146
  > See `ruff-lint-job` in the project
147
147
  > [.gitlab-ci.yml](https://gitlab.com/andyrids/pkgdx/-/blob/main/.gitlab-ci.yml) for an example.
148
148
 
149
+ ## Excluding files and folders
150
+
151
+ The lint, format and typing hooks walk your project themselves, so they check and auto-fix
152
+ everything they find. To leave submodules, vendored code or generated files alone, list them in your
153
+ project's `pyproject.toml`:
154
+
155
+ ```toml
156
+ [tool.pkgdx]
157
+ exclude = ["submodules", "vendor", "src/app/_gen.py"]
158
+ ```
159
+
160
+ Entries are literal paths relative to that file, `/` separated and case-sensitive. A folder covers
161
+ everything below it, and `vendor` never matches `src/vendor`. Globs are rejected, and an invalid
162
+ list fails the hook before any tool runs.
163
+
164
+ The list is committed, so it applies in CI and survives `pkgdx init --reset` and hook updates. It
165
+ also applies to the markdown hook, but `pkgdx-secrets` keeps scanning listed paths, because a secret
166
+ in vendored code is still a leaked secret. Run `uv run pkgdx config` to see the list in effect.
167
+
168
+ > [!NOTE]
169
+ > See [the guidance](https://gitlab.com/andyrids/pkgdx/-/blob/main/docs/guidance/toolchain-pkgdx.md)
170
+ > for the full rules. When upgrading, move both the `pkgdx` lock and the hook `rev` before relying
171
+ > on the list.
172
+
149
173
  ## Adopting your own standards (external users)
150
174
 
151
175
  `pkgdx` ships bundled canonical standards. To change them without forking, place your own files in a
@@ -194,8 +218,8 @@ uv run pkgdx config
194
218
  ```
195
219
 
196
220
  This prints one row per file on standard output: its name, its source (`user` or `bundled`) and
197
- its resolved path. A summary line on standard error names the user config directory and whether
198
- `PKGDX_CONFIG_DIR` set it.
221
+ its resolved path, then one row per [excluded path](#excluding-files-and-folders). A summary line on
222
+ standard error names the user config directory and whether `PKGDX_CONFIG_DIR` set it.
199
223
 
200
224
  To start from the bundled files, export them into the user config directory:
201
225
 
@@ -27,7 +27,7 @@ dependencies = [
27
27
  "detect-secrets>=1.5.0",
28
28
  "mypy>=2.1.0",
29
29
  "prek~=0.4.8",
30
- "pyclig~=0.2",
30
+ "pyclig~=0.3.0",
31
31
  "pymarkdownlnt>=0.9.37",
32
32
  "rich>=15.0.0",
33
33
  "ruff>=0.15.20",
@@ -557,7 +557,7 @@ def create_secrets_baseline(root: Path) -> StepResult:
557
557
  "detect_secrets",
558
558
  "scan",
559
559
  "--exclude-files",
560
- r"(.*\.lock)",
560
+ r"(\.venv|\.secrets\.baseline|.*\.lock)",
561
561
  ],
562
562
  cwd=root,
563
563
  env=os.environ | {"PYTHONUTF8": "1"},
@@ -41,5 +41,18 @@ class ConfigDirError(Error):
41
41
  """Raised on an invalid `PKGDX_CONFIG_DIR`."""
42
42
 
43
43
 
44
+ class ProjectConfigError(Error):
45
+ """Raised on an invalid `[tool.pkgdx]` table in `pyproject.toml`."""
46
+
47
+
44
48
  class ToolNotFoundError(Error):
45
- """Raised when a hook tool executable is not found on `PATH`."""
49
+ """Raised when a hook tool executable is not found on `PATH`.
50
+
51
+ Attributes:
52
+ hint: The remedy, printed by the CLI after the error.
53
+ """
54
+
55
+ hint = (
56
+ "Run the hook in the environment pkgdx is installed in, "
57
+ "e.g. via `uv run`"
58
+ )
@@ -8,7 +8,7 @@ import logging
8
8
  import os
9
9
  import sys
10
10
  from functools import lru_cache
11
- from pathlib import Path
11
+ from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath
12
12
  from typing import Any
13
13
 
14
14
  logger = logging.getLogger(__package__)
@@ -26,6 +26,7 @@ BUNDLED_CONFIGS: tuple[Path, ...] = (
26
26
  PYMARKDOWN_CONFIG,
27
27
  RUFF_CONFIG,
28
28
  )
29
+ _EXCLUDE_CHARS = frozenset("\\*?[]{}\x7f") | set(map(chr, range(32)))
29
30
 
30
31
 
31
32
  def user_config_dir() -> Path:
@@ -80,6 +81,102 @@ def resolve_config(bundled: Path) -> Path:
80
81
  return bundled
81
82
 
82
83
 
84
+ def _relative_exclude(entry: str, below: Path) -> str:
85
+ """Make an `exclude` entry relative to the working directory.
86
+
87
+ NOTE: Built from path parts, as Windows path functions rewrite names such
88
+ as `NUL`. From at or inside the entry it stays whole, as a bare `..` would
89
+ match everything above the working directory.
90
+
91
+ Args:
92
+ entry: The validated entry, relative to the project root.
93
+ below: The working directory, relative to the project root.
94
+
95
+ Returns:
96
+ The `/` separated path, relative to the working directory.
97
+ """
98
+ parts = PurePosixPath(entry).parts
99
+ shared = len(PurePath(os.path.commonpath([below, entry])).parts)
100
+ if shared == len(parts):
101
+ shared = 0
102
+ return "/".join([".."] * (len(below.parts) - shared) + [*parts[shared:]])
103
+
104
+
105
+ def project_excludes() -> list[str]:
106
+ """Get the paths the project excludes from the hooks.
107
+
108
+ NOTE: Reads `[tool.pkgdx] exclude` from the nearest `pyproject.toml`,
109
+ from the working directory up. Entries are literal paths, as those
110
+ translate exactly into each tool's syntax, & rejecting glob characters
111
+ keeps glob support addable without breaking a config. A path that does
112
+ not exist is allowed, as an uninitialised submodule or an ungenerated
113
+ folder is normal.
114
+
115
+ Raises:
116
+ ProjectConfigError: If the `pyproject.toml` or its table is invalid.
117
+
118
+ Returns:
119
+ The paths, `/` separated & relative to the working directory, or an
120
+ empty list if the project sets none.
121
+ """
122
+ import tomllib
123
+
124
+ from pkgdx.exceptions import ProjectConfigError
125
+
126
+ cwd = Path.cwd()
127
+ for directory in (cwd, *cwd.parents):
128
+ pyproject = directory / "pyproject.toml"
129
+ # `lexists`: anything unreadable here fails closed below, unskipped
130
+ if os.path.lexists(pyproject):
131
+ break
132
+ else:
133
+ return []
134
+
135
+ try:
136
+ with pyproject.open("rb") as f:
137
+ document = tomllib.load(f)
138
+ except (OSError, ValueError) as e:
139
+ msg = f"Could not read {pyproject}: {e}"
140
+ raise ProjectConfigError(msg) from e
141
+
142
+ tool = document.get("tool", {})
143
+ table = tool.get("pkgdx", {}) if isinstance(tool, dict) else tool
144
+ if not isinstance(table, dict):
145
+ msg = f"`tool.pkgdx` must be a table, not {table!r}, in {pyproject}"
146
+ raise ProjectConfigError(msg)
147
+
148
+ if unknown := table.keys() - {"exclude"}:
149
+ msg = f"Unknown `[tool.pkgdx]` keys in {pyproject}: {sorted(unknown)}"
150
+ raise ProjectConfigError(msg)
151
+
152
+ entries = table.get("exclude", [])
153
+ if not isinstance(entries, list):
154
+ msg = (
155
+ f"`[tool.pkgdx] exclude` must be a list, not {entries!r},"
156
+ f" in {pyproject}"
157
+ )
158
+ raise ProjectConfigError(msg)
159
+
160
+ for entry in entries:
161
+ parts = PurePosixPath(entry).parts if isinstance(entry, str) else ()
162
+ # `rstrip` covers `..` & a name Windows would rewrite, e.g. `vendor.`
163
+ if (
164
+ not parts
165
+ or not _EXCLUDE_CHARS.isdisjoint(entry)
166
+ or PureWindowsPath(entry).anchor
167
+ or any(part != part.rstrip(". ") for part in parts)
168
+ ):
169
+ msg = (
170
+ f"`[tool.pkgdx] exclude` entry {entry!r} in {pyproject} must"
171
+ " be a literal relative path, `/` separated, with no globs,"
172
+ " control characters or names ending in a dot or space"
173
+ )
174
+ raise ProjectConfigError(msg)
175
+
176
+ below = cwd.relative_to(directory)
177
+ return [_relative_exclude(entry, below) for entry in entries]
178
+
179
+
83
180
  @lru_cache(maxsize=1)
84
181
  def _load_prek_config() -> dict[str, Any]:
85
182
  """Load Prek config.
@@ -177,6 +274,7 @@ __all__: list[str] = [
177
274
  "PREK_CONFIG",
178
275
  "PYMARKDOWN_CONFIG",
179
276
  "RUFF_CONFIG",
277
+ "project_excludes",
180
278
  "resolve_config",
181
279
  "user_config_dir",
182
280
  ]
@@ -2,7 +2,8 @@
2
2
 
3
3
  NOTE: `pkgdx.__main__` adds these commands (`command_init`,
4
4
  `command_config`) to the `pkgdx` group. The ledger, notes & closing lines go
5
- to the run's STDERR console (`ctx.err`); `config` source rows to STDOUT.
5
+ to the run's STDERR console (`ctx.err`); `config` source & exclude rows
6
+ to STDOUT.
6
7
  """
7
8
 
8
9
  import dataclasses
@@ -194,17 +195,20 @@ def _run_steps(
194
195
  console: Console,
195
196
  command: str,
196
197
  steps: Sequence[tuple[str, Callable[[], StepResult]]],
198
+ quiet: bool = False,
197
199
  ) -> int:
198
200
  """Run ledger steps in order, printing one line per step & a summary.
199
201
 
200
202
  NOTE: Prints to STDERR, with a transient spinner only when STDERR is an
201
203
  interactive terminal. Debug log lines (`-d`) appear above the line of
202
- the step that emitted them. Stops at the first FAIL.
204
+ the step that emitted them. Stops at the first FAIL. With `quiet`, OK
205
+ rows & the `done` line are skipped; warnings & failures stay.
203
206
 
204
207
  Args:
205
208
  console: The STDERR console, shared with logging.
206
209
  command: The `pkgdx` subcommand, named in the closing line.
207
210
  steps: The step labels & callables, in run order.
211
+ quiet: Skip OK rows & the `done` line (`-q`).
208
212
 
209
213
  Returns:
210
214
  The integer process exit code. 0 on success (with or without
@@ -222,7 +226,8 @@ def _run_steps(
222
226
  else:
223
227
  result = run()
224
228
 
225
- _report(console, label, result, width)
229
+ if not (quiet and result.outcome is Outcome.OK):
230
+ _report(console, label, result, width)
226
231
  if result.outcome is Outcome.FAIL:
227
232
  closing = (
228
233
  f"pkgdx {command}: failed at step {number}/{len(steps)}"
@@ -253,9 +258,10 @@ def _run_steps(
253
258
  else "nothing to change"
254
259
  )
255
260
  elapsed = time.monotonic() - start
256
- console.print(
257
- Text(f"pkgdx {command}: done in {elapsed:.1f}s{tail} ({counts})")
258
- )
261
+ if not quiet:
262
+ console.print(
263
+ Text(f"pkgdx {command}: done in {elapsed:.1f}s{tail} ({counts})")
264
+ )
259
265
  return pyclig.ExitCode.OK
260
266
 
261
267
 
@@ -288,6 +294,7 @@ def command_init(ctx: pyclig.Context, reset: bool) -> int:
288
294
  ctx.err,
289
295
  "init",
290
296
  [(label, partial(run, state)) for label, run in _STEPS],
297
+ ctx.quiet,
291
298
  )
292
299
 
293
300
 
@@ -303,11 +310,11 @@ def command_init(ctx: pyclig.Context, reset: bool) -> int:
303
310
  )
304
311
  @pyclig.pass_context
305
312
  def command_config(ctx: pyclig.Context, export: bool) -> int:
306
- """Show config sources or export bundled configs.
313
+ """Show config sources & excludes or export bundled configs.
307
314
 
308
315
  \f
309
- NOTE: Source rows go to STDOUT (`ctx.out`). The closing line, the
310
- `--export` ledger and errors go to STDERR (`ctx.err`).
316
+ NOTE: Source & project exclude rows go to STDOUT (`ctx.out`). The closing
317
+ line, the `--export` ledger and errors go to STDERR (`ctx.err`).
311
318
 
312
319
  Args:
313
320
  ctx: The CLI context.
@@ -315,8 +322,12 @@ def command_config(ctx: pyclig.Context, export: bool) -> int:
315
322
 
316
323
  Returns:
317
324
  The integer process exit code. 0 on success, 1 on an invalid
318
- `PKGDX_CONFIG_DIR` or a failed copy and 130 on Ctrl-C during
319
- `--export`.
325
+ `PKGDX_CONFIG_DIR`, an invalid `[tool.pkgdx]` table or a failed copy
326
+ and 130 on Ctrl-C during `--export`.
327
+
328
+ Raises:
329
+ exceptions.ProjectConfigError: If the `[tool.pkgdx]` table is invalid,
330
+ before any row prints.
320
331
  """
321
332
  env = standards.CONFIG_DIR_ENV
322
333
  try:
@@ -334,8 +345,10 @@ def command_config(ctx: pyclig.Context, export: bool) -> int:
334
345
  (bundled.name, partial(_core.export_config, bundled, user_dir))
335
346
  for bundled in standards.BUNDLED_CONFIGS
336
347
  ],
348
+ ctx.quiet,
337
349
  )
338
350
 
351
+ excludes = standards.project_excludes()
339
352
  width = max(len(bundled.name) for bundled in standards.BUNDLED_CONFIGS)
340
353
  users = 0
341
354
  for bundled in standards.BUNDLED_CONFIGS:
@@ -352,10 +365,24 @@ def command_config(ctx: pyclig.Context, export: bool) -> int:
352
365
  )
353
366
  ctx.out.print(row, soft_wrap=True)
354
367
 
368
+ for path in excludes:
369
+ row = Text.assemble(
370
+ " ",
371
+ "exclude".ljust(width),
372
+ " ",
373
+ (f"{'project':<{_KIND}}", "bold"),
374
+ path,
375
+ "" if Path(path).exists() else " (not found)",
376
+ )
377
+ ctx.out.print(row, soft_wrap=True)
378
+
355
379
  via = f"from {env}" if os.environ.get(env) else f"{env} not set"
356
380
  sources = f"{users} user, {len(standards.BUNDLED_CONFIGS) - users} bundled"
357
- ctx.err.print(
358
- Text(f"pkgdx config: user config dir {user_dir}, {via} ({sources})"),
359
- soft_wrap=True,
360
- )
381
+ if not ctx.quiet:
382
+ ctx.err.print(
383
+ Text(
384
+ f"pkgdx config: user config dir {user_dir}, {via} ({sources})"
385
+ ),
386
+ soft_wrap=True,
387
+ )
361
388
  return pyclig.ExitCode.OK
@@ -1,6 +1,8 @@
1
1
  """Core pre-commit hook logic for the `pkgdx` canonical standards."""
2
2
 
3
+ import json
3
4
  import os
5
+ import re
4
6
  import subprocess
5
7
  from itertools import islice
6
8
  from typing import Any
@@ -46,36 +48,110 @@ def _run_tool(cmd: list[str], **kwargs: Any) -> int:
46
48
  try:
47
49
  proc = subprocess.run(cmd, **kwargs)
48
50
  except FileNotFoundError as e:
49
- msg = (
50
- f"`{cmd[0]}` not found on PATH - run the hook in the environment"
51
- " pkgdx is installed in, e.g. via `uv run`"
52
- )
53
- raise exceptions.ToolNotFoundError(msg) from e
51
+ raise exceptions.ToolNotFoundError(
52
+ f"`{cmd[0]}` not found on PATH"
53
+ ) from e
54
54
  else:
55
55
  return proc.returncode
56
56
 
57
57
 
58
+ # PROJECT EXCLUDES
59
+
60
+
61
+ def _ruff_exclude_args() -> list[str]:
62
+ """Translate the project excludes into Ruff arguments.
63
+
64
+ NOTE: Inline `--config`, as `ruff format --extend-exclude` needs ruff
65
+ 0.15.21 & Ruff glob-expands flag values on Windows. `./` anchors a path
66
+ to the working directory; a bare name would match at any depth. Never
67
+ `--exclude`, which would replace Ruff's default exclusions.
68
+
69
+ Returns:
70
+ The arguments, empty if the project excludes nothing.
71
+
72
+ Raises:
73
+ exceptions.ProjectConfigError: If the project list is invalid.
74
+ """
75
+ excludes = standards.project_excludes()
76
+ if not excludes:
77
+ return []
78
+ paths = [f"./{path}" for path in excludes]
79
+ value = json.dumps(paths, ensure_ascii=False)
80
+ return ["--config", f"extend-exclude={value}"]
81
+
82
+
83
+ def _mypy_exclude_args(args: list[str]) -> list[str]:
84
+ """Translate the project excludes into Mypy arguments.
85
+
86
+ NOTE: `--exclude` adds to the config's `exclude` & only filters discovery.
87
+ With no args the whole project is checked, so `--follow-imports=silent`
88
+ only hides errors in excluded code the project imports, which a consumer
89
+ cannot do as the shim pins the config file. Args may narrow the target,
90
+ where the flag would hide errors in first-party code too, so it stays off.
91
+
92
+ Args:
93
+ args: The hook arguments.
94
+
95
+ Returns:
96
+ The arguments, empty if the project excludes nothing.
97
+
98
+ Raises:
99
+ exceptions.ProjectConfigError: If the project list is invalid.
100
+ """
101
+ excludes = standards.project_excludes()
102
+ patterns = [
103
+ arg
104
+ for path in excludes
105
+ for arg in ("--exclude", f"^{re.escape(path)}(/|$)")
106
+ ]
107
+ silent = excludes and not args
108
+ return [*patterns, "--follow-imports=silent"] if silent else patterns
109
+
110
+
111
+ def _is_excluded(arg: str, excludes: list[str]) -> bool:
112
+ """Check whether a hook argument is a path under an excluded path.
113
+
114
+ NOTE: Compares strings, as Mypy does, so that a match is case-sensitive
115
+ on every platform.
116
+
117
+ Args:
118
+ arg: The hook argument.
119
+ excludes: The project excludes, relative to the working directory.
120
+
121
+ Returns:
122
+ True if the argument is an excluded path or is below one.
123
+ """
124
+ try:
125
+ path = os.path.relpath(arg).replace(os.sep, "/")
126
+ except ValueError: # on another Windows drive, so outside the project
127
+ return False
128
+ return any(
129
+ path == exclude or path.startswith(f"{exclude}/")
130
+ for exclude in excludes
131
+ )
132
+
133
+
58
134
  # CORE HOOK LOGIC
59
135
 
60
136
 
61
137
  def core_ruff_format(args: list[str]) -> int:
62
138
  """Core logic for ruff formatting."""
63
139
  config = standards.resolve_config(standards.RUFF_CONFIG).as_posix()
64
- cmd = ["ruff", "format", "--config", config] + args
140
+ cmd = ["ruff", "format", "--config", config, *_ruff_exclude_args(), *args]
65
141
  return _run_tool(cmd)
66
142
 
67
143
 
68
144
  def core_ruff_lint(args: list[str]) -> int:
69
145
  """Core logic for ruff linting."""
70
146
  config = standards.resolve_config(standards.RUFF_CONFIG).as_posix()
71
- cmd = ["ruff", "check", "--config", config] + args
147
+ cmd = ["ruff", "check", "--config", config, *_ruff_exclude_args(), *args]
72
148
  return _run_tool(cmd)
73
149
 
74
150
 
75
151
  def core_mypy_typing(args: list[str]) -> int:
76
152
  """Core logic for mypy type checking."""
77
153
  config = standards.resolve_config(standards.MYPY_CONFIG).as_posix()
78
- cmd = ["mypy", "--config-file", config] + args
154
+ cmd = ["mypy", "--config-file", config, *_mypy_exclude_args(args), *args]
79
155
  return _run_tool(cmd)
80
156
 
81
157
 
@@ -100,13 +176,19 @@ def core_pymarkdown_lint(args: list[str]) -> int:
100
176
  The rest - paths & `scan`'s own options, e.g. `-r` or `-e` (`--exclude`)
101
177
  - follow `scan` in order, as before.
102
178
 
179
+ Project excludes are dropped from a plain list of paths, which is what
180
+ prek passes, not passed as `-e`: PyMarkdown exits 1 silently when `-e`
181
+ leaves it nothing to scan, so the hook returns 0. A command with `scan`
182
+ options is hand-written & runs as given, as an option's value is no path.
183
+
103
184
  Args:
104
185
  args: The hook arguments: paths, `scan` & global options.
105
186
 
106
187
  Returns:
107
- The PyMarkdown return code.
188
+ The PyMarkdown return code, or 0 if every path was dropped.
108
189
 
109
190
  Raises:
191
+ exceptions.ProjectConfigError: If the project list is invalid.
110
192
  exceptions.ToolNotFoundError: If `pymarkdown` is not on `PATH`.
111
193
  """
112
194
  config = standards.resolve_config(standards.PYMARKDOWN_CONFIG).as_posix()
@@ -123,6 +205,16 @@ def core_pymarkdown_lint(args: list[str]) -> int:
123
205
  options.append(arg)
124
206
  else:
125
207
  scan_args.append(arg)
208
+
209
+ excludes = standards.project_excludes()
210
+ has_options = any(
211
+ arg.startswith("-") and not os.path.lexists(arg) for arg in scan_args
212
+ )
213
+ if scan_args and not has_options:
214
+ scan_args = [a for a in scan_args if not _is_excluded(a, excludes)]
215
+ if not scan_args:
216
+ return 0
217
+
126
218
  cmd = [
127
219
  "pymarkdown",
128
220
  "--config",
@@ -1,8 +1,8 @@
1
- #:schema https://raw.githubusercontent.com/j178/prek/refs/heads/master/prek.schema.json
1
+ #:schema https://raw.githubusercontent.com/j178/prek/refs/heads/main/prek.schema.json
2
2
 
3
3
  [[repos]]
4
4
  repo = "https://gitlab.com/andyrids/pkgdx"
5
- rev = "v0.6.0"
5
+ rev = "v0.8.0"
6
6
 
7
7
  [[repos.hooks]]
8
8
  id = "pkgdx-lint"
@@ -1,4 +1,3 @@
1
- exclude = []
2
1
  indent-width = 4
3
2
  line-length = 79
4
3
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes