pkgdx 0.5.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.
@@ -0,0 +1,380 @@
1
+ """CLI commands for a canonical standards interface and pre-commit hooks.
2
+
3
+ NOTE: The `__main__` `argparse.ArgumentParser` pgkdx CLI entry point uses this
4
+ module to register subcommands (`add_subparser`) for managing canonical
5
+ standards and pre-commit hooks.
6
+ """
7
+
8
+ import dataclasses
9
+ import os
10
+ import time
11
+ from collections.abc import Callable, Sequence
12
+ from functools import partial
13
+ from pathlib import Path
14
+ from typing import TYPE_CHECKING, Any, Optional
15
+
16
+ from rich.text import Text
17
+
18
+ from pkgdx import _core, exceptions, standards
19
+ from pkgdx._core import (
20
+ Change,
21
+ CLIContext,
22
+ CLIGFormatter,
23
+ ExitCode,
24
+ Outcome,
25
+ StepResult,
26
+ )
27
+ from pkgdx.logging import GLOBAL_CONSOLE
28
+
29
+ if TYPE_CHECKING:
30
+ import argparse
31
+
32
+ _BADGES = {
33
+ Outcome.OK: ("ok", "green"),
34
+ Outcome.WARN: ("warn", "bold yellow"),
35
+ Outcome.FAIL: ("FAIL", "bold red"),
36
+ }
37
+ _STOP = ("stop", "bold red")
38
+ _CHANGED = frozenset({Change.CREATED, Change.UPDATED})
39
+ _KIND = max(map(len, Change)) + 2 # widest change word, then a gap
40
+ _INDENT = 8
41
+
42
+
43
+ def _row(badge: tuple[str, str], label: str, detail: Text, width: int) -> None:
44
+ """Print one aligned ledger line for a step.
45
+
46
+ NOTE: The line is never wrapped, so a long path stays whole (a terminal
47
+ may still soft-wrap it on screen) and a piped log has one line per step.
48
+
49
+ Args:
50
+ badge: The state word and its Rich style.
51
+ label: The step label.
52
+ detail: The detail column text.
53
+ width: The label column width.
54
+ """
55
+ word, style = badge
56
+ row = Text.assemble(
57
+ (f" {word}".ljust(8), style),
58
+ " ",
59
+ label.ljust(width),
60
+ " ",
61
+ detail,
62
+ )
63
+ GLOBAL_CONSOLE.print(row, soft_wrap=True)
64
+
65
+
66
+ def _note(text: str) -> None:
67
+ """Print an indented continuation line under a ledger line.
68
+
69
+ NOTE: Printed as `Text`, so markup, backticks and Windows paths are
70
+ shown as written. Like `_row`, the line is never wrapped, so a long path
71
+ stays whole (a terminal may still soft-wrap it on screen).
72
+
73
+ Args:
74
+ text: The line text.
75
+ """
76
+ GLOBAL_CONSOLE.print(Text(" " * _INDENT + text), soft_wrap=True)
77
+
78
+
79
+ def _detail(result: StepResult) -> Text:
80
+ """Build the detail column for a step result.
81
+
82
+ Args:
83
+ result: The step result.
84
+
85
+ Returns:
86
+ The detail text, or the padded change word followed by the subject.
87
+ """
88
+ if result.change is None:
89
+ return Text(result.detail)
90
+ style = "bold" if result.change in _CHANGED else "dim"
91
+ return Text.assemble((f"{result.change:<{_KIND}}", style), result.subject)
92
+
93
+
94
+ def _report(label: str, result: StepResult, width: int) -> None:
95
+ """Print a ledger line, plus the cause & hint for a WARN or FAIL result.
96
+
97
+ Args:
98
+ label: The step label.
99
+ result: The step result.
100
+ width: The label column width.
101
+ """
102
+ _row(_BADGES[result.outcome], label, _detail(result), width)
103
+ if result.outcome is not Outcome.OK:
104
+ if result.message:
105
+ _note(result.message)
106
+ _note(f"-> {result.hint}")
107
+
108
+
109
+ @dataclasses.dataclass(slots=True)
110
+ class _InitState:
111
+ """The paths found by the first init steps, for the later steps.
112
+
113
+ Attributes:
114
+ reset: Clean installation flag (`--reset`).
115
+ root: The project root, set by the first step.
116
+ git_toplevel: The Git top-level, or None outside a Git repository.
117
+ """
118
+
119
+ reset: bool
120
+ root: Path = Path()
121
+ git_toplevel: Path | None = None
122
+
123
+
124
+ def _find_project_root(state: _InitState) -> StepResult:
125
+ """Find the project root & record it on the init state.
126
+
127
+ Args:
128
+ state: The init state to update.
129
+
130
+ Returns:
131
+ An OK result naming the root, or FAIL if no root is found.
132
+ """
133
+ try:
134
+ state.root = _core.get_project_root()
135
+ except exceptions.ProjectRootNotFoundError as e:
136
+ return StepResult(
137
+ Outcome.FAIL,
138
+ "project root not found",
139
+ str(e),
140
+ "Run `pkgdx init` from inside a Python project",
141
+ )
142
+ return StepResult(Outcome.OK, f"{state.root} (pyproject.toml)")
143
+
144
+
145
+ def _find_git_toplevel(state: _InitState) -> StepResult:
146
+ """Find the Git top-level & record it on the init state.
147
+
148
+ Args:
149
+ state: The init state to update.
150
+
151
+ Returns:
152
+ An OK result naming the top-level (or `same as project root`), or
153
+ WARN outside a Git repository.
154
+ """
155
+ try:
156
+ state.git_toplevel = _core.get_git_toplevel()
157
+ except exceptions.GitTopLevelError:
158
+ return StepResult(
159
+ Outcome.WARN,
160
+ "not a Git repository, using project root",
161
+ hint="Run `git init` to enable pre-commit hooks",
162
+ )
163
+ if state.git_toplevel == state.root:
164
+ return StepResult(Outcome.OK, "same as project root")
165
+ return StepResult(Outcome.OK, str(state.git_toplevel))
166
+
167
+
168
+ # Lambdas look up `_core.<fn>` when called, so tests can patch them
169
+ _STEPS: tuple[tuple[str, Callable[[_InitState], StepResult]], ...] = (
170
+ ("identify project root", _find_project_root),
171
+ ("identify Git top-level", _find_git_toplevel),
172
+ (
173
+ "configure pre-commit hooks",
174
+ lambda s: _core.setup_prek_config(s.root, s.reset),
175
+ ),
176
+ (
177
+ "prek install",
178
+ lambda s: _core.install_prek_hooks(s.root, s.git_toplevel),
179
+ ),
180
+ ("prek update --check", lambda s: _core.update_prek_hooks(s.root)),
181
+ ("detect-secrets scan", lambda s: _core.create_secrets_baseline(s.root)),
182
+ )
183
+
184
+
185
+ def _run_steps(
186
+ command: str, steps: Sequence[tuple[str, Callable[[], StepResult]]]
187
+ ) -> int:
188
+ """Run ledger steps in order, printing one line per step & a summary.
189
+
190
+ NOTE: Prints to STDERR (`GLOBAL_CONSOLE`), with a transient spinner only
191
+ when STDERR is a TTY. Debug log lines (`-d`) appear above the line of
192
+ the step that emitted them. Stops at the first FAIL.
193
+
194
+ Args:
195
+ command: The `pkgdx` subcommand, named in the closing line.
196
+ steps: The step labels & callables, in run order.
197
+
198
+ Returns:
199
+ The integer process exit code. 0 on success (with or without
200
+ warnings), 1 on a failed step and 130 on Ctrl-C. Uses
201
+ `_core.ExitCode`.
202
+ """
203
+ interactive = GLOBAL_CONSOLE.is_terminal
204
+ width = max(len(label) for label, _ in steps)
205
+ start = time.monotonic()
206
+ warnings = changed = unchanged = 0
207
+ label = ""
208
+ try:
209
+ for number, (label, run) in enumerate(steps, 1):
210
+ if interactive:
211
+ with GLOBAL_CONSOLE.status(f"{label} ...", spinner="dots"):
212
+ result = run()
213
+ else:
214
+ result = run()
215
+
216
+ _report(label, result, width)
217
+ if result.outcome is Outcome.FAIL:
218
+ closing = (
219
+ f"pkgdx {command}: failed at step {number}/{len(steps)}"
220
+ )
221
+ if unrun := [name for name, _ in steps[number:]]:
222
+ _note(f"not run: {', '.join(unrun)}")
223
+ count = f"{len(unrun)} step{'s' * (len(unrun) != 1)}"
224
+ closing += f" ({count} not run)"
225
+ GLOBAL_CONSOLE.print(Text(closing))
226
+ return ExitCode.EX_FAILURE
227
+
228
+ warnings += result.outcome is Outcome.WARN
229
+ changed += result.change in _CHANGED
230
+ unchanged += result.change is Change.UNCHANGED
231
+ except KeyboardInterrupt:
232
+ _row(_STOP, label, Text("interrupted"), width)
233
+ GLOBAL_CONSOLE.print(
234
+ Text(f"pkgdx {command}: interrupted, no cleanup performed")
235
+ )
236
+ return ExitCode.EX_INTERRUPT
237
+
238
+ tail = (
239
+ f" with {warnings} warning{'s' * (warnings != 1)}" if warnings else ""
240
+ )
241
+ counts = (
242
+ f"{changed} changed, {unchanged} unchanged"
243
+ if changed
244
+ else "nothing to change"
245
+ )
246
+ elapsed = time.monotonic() - start
247
+ GLOBAL_CONSOLE.print(
248
+ Text(f"pkgdx {command}: done in {elapsed:.1f}s{tail} ({counts})")
249
+ )
250
+ return ExitCode.EX_OK
251
+
252
+
253
+ def command_init(ctx: CLIContext) -> int:
254
+ """Configure a consuming repo with `pkgdx` standards.
255
+
256
+ Attempts to identify the root of the consuming repo and ensures that
257
+ `Prek` is configured with the expected `pkgdx` hooks.
258
+
259
+ NOTE: Prints one ledger line per step to STDERR (`_run_steps`).
260
+
261
+ Args:
262
+ ctx: The CLI context.
263
+
264
+ Returns:
265
+ The integer process exit code. 0 on success (with or without
266
+ warnings), 1 on a failed step and 130 on Ctrl-C. Uses
267
+ `_core.ExitCode`.
268
+ """
269
+ state = _InitState(reset=ctx.args.reset)
270
+ return _run_steps(
271
+ "init", [(label, partial(run, state)) for label, run in _STEPS]
272
+ )
273
+
274
+
275
+ def command_config(ctx: CLIContext) -> int:
276
+ """Show resolved config sources, or export bundled configs.
277
+
278
+ NOTE: Source rows go to STDOUT (`ctx.console`). The closing line, the
279
+ `--export` ledger and errors go to STDERR (`GLOBAL_CONSOLE`).
280
+
281
+ Args:
282
+ ctx: The CLI context.
283
+
284
+ Returns:
285
+ The integer process exit code. 0 on success, 1 on an invalid
286
+ `PKGDX_CONFIG_DIR` or a failed copy and 130 on Ctrl-C during
287
+ `--export`. Uses `_core.ExitCode`.
288
+ """
289
+ env = standards.CONFIG_DIR_ENV
290
+ try:
291
+ user_dir = standards.user_config_dir()
292
+ except exceptions.ConfigDirError as e:
293
+ _report(env, _core.config_dir_failure(e), len(env))
294
+ GLOBAL_CONSOLE.print(Text("pkgdx config: failed"))
295
+ return ExitCode.EX_FAILURE
296
+
297
+ if ctx.args.export:
298
+ return _run_steps(
299
+ "config",
300
+ [
301
+ (bundled.name, partial(_core.export_config, bundled, user_dir))
302
+ for bundled in standards.BUNDLED_CONFIGS
303
+ ],
304
+ )
305
+
306
+ width = max(len(bundled.name) for bundled in standards.BUNDLED_CONFIGS)
307
+ users = 0
308
+ for bundled in standards.BUNDLED_CONFIGS:
309
+ resolved = standards.resolve_config(bundled)
310
+ is_user = resolved != bundled
311
+ users += is_user
312
+ source, style = ("user", "bold") if is_user else ("bundled", "dim")
313
+ row = Text.assemble(
314
+ " ",
315
+ bundled.name.ljust(width),
316
+ " ",
317
+ (f"{source:<{_KIND}}", style),
318
+ str(resolved),
319
+ )
320
+ ctx.console.print(row, soft_wrap=True)
321
+
322
+ via = f"from {env}" if os.environ.get(env) else f"{env} not set"
323
+ sources = f"{users} user, {len(standards.BUNDLED_CONFIGS) - users} bundled"
324
+ GLOBAL_CONSOLE.print(
325
+ Text(f"pkgdx config: user config dir {user_dir}, {via} ({sources})"),
326
+ soft_wrap=True,
327
+ )
328
+ return ExitCode.EX_OK
329
+
330
+
331
+ def add_subparser(
332
+ subparsers: "argparse._SubParsersAction[Any]",
333
+ parent: Optional["argparse.ArgumentParser"] = None,
334
+ ) -> None:
335
+ """Add the `init` & `config` subcommands to the shared `pkgdx` parser.
336
+
337
+ Args:
338
+ subparsers: The main CLI parser's subparsers action.
339
+ parent: A parent parser to include for shared arguments.
340
+ """
341
+
342
+ init_text = "Setup canonical standards & pre-commit hooks"
343
+ parser_init = subparsers.add_parser(
344
+ "init",
345
+ help=init_text,
346
+ description=init_text,
347
+ usage="USAGE:\n %(prog)s [options]",
348
+ add_help=False,
349
+ parents=[parent] if parent else [],
350
+ formatter_class=CLIGFormatter,
351
+ )
352
+
353
+ parser_init._optionals.title = "OPTIONS"
354
+
355
+ parser_init.add_argument(
356
+ "--reset", action="store_true", help="Reset existing pre-commit hooks"
357
+ )
358
+
359
+ parser_init.set_defaults(func=command_init)
360
+
361
+ config_text = "Show config sources or export bundled configs"
362
+ parser_config = subparsers.add_parser(
363
+ "config",
364
+ help=config_text,
365
+ description=config_text,
366
+ usage="USAGE:\n %(prog)s [options]",
367
+ add_help=False,
368
+ parents=[parent] if parent else [],
369
+ formatter_class=CLIGFormatter,
370
+ )
371
+
372
+ parser_config._optionals.title = "OPTIONS"
373
+
374
+ parser_config.add_argument(
375
+ "--export",
376
+ action="store_true",
377
+ help="Copy bundled configs into the user config directory",
378
+ )
379
+
380
+ parser_config.set_defaults(func=command_config)
@@ -0,0 +1,53 @@
1
+ """Core pre-commit hook logic for the `pkgdx` canonical standards."""
2
+
3
+ import os
4
+ import subprocess
5
+
6
+ from pkgdx import standards
7
+
8
+ # CORE HOOK LOGIC
9
+
10
+
11
+ def core_ruff_format(args: list[str]) -> int:
12
+ """Core logic for ruff formatting."""
13
+ config = standards.resolve_config(standards.RUFF_CONFIG).as_posix()
14
+ cmd = ["ruff", "format", "--config", config] + args
15
+ return subprocess.run(cmd).returncode
16
+
17
+
18
+ def core_ruff_lint(args: list[str]) -> int:
19
+ """Core logic for ruff linting."""
20
+ config = standards.resolve_config(standards.RUFF_CONFIG).as_posix()
21
+ cmd = ["ruff", "check", "--config", config] + args
22
+ return subprocess.run(cmd).returncode
23
+
24
+
25
+ def core_mypy_typing(args: list[str]) -> int:
26
+ """Core logic for mypy type checking."""
27
+ config = standards.resolve_config(standards.MYPY_CONFIG).as_posix()
28
+ cmd = ["mypy", "--config-file", config] + args
29
+ return subprocess.run(cmd).returncode
30
+
31
+
32
+ def core_detect_secrets(args: list[str]) -> int:
33
+ """Core logic for detect-secrets."""
34
+ if "--baseline" not in args:
35
+ args = ["--baseline", ".secrets.baseline"] + args
36
+ cmd = ["detect-secrets-hook"] + args
37
+ # detect-secrets opens files with the locale encoding & silently skips
38
+ # files that fail to decode (cp1252 on Windows), so force UTF-8 mode.
39
+ env = os.environ | {"PYTHONUTF8": "1"}
40
+ return subprocess.run(cmd, env=env).returncode
41
+
42
+
43
+ def core_pymarkdown_lint(args: list[str]) -> int:
44
+ """Core logic for pymarkdown linting."""
45
+ config = standards.resolve_config(standards.PYMARKDOWN_CONFIG).as_posix()
46
+ cmd = [
47
+ "pymarkdown",
48
+ "--config",
49
+ config,
50
+ "--continue-on-error",
51
+ "scan",
52
+ ] + args
53
+ return subprocess.run(cmd).returncode
@@ -0,0 +1,50 @@
1
+ #:schema https://raw.githubusercontent.com/j178/prek/refs/heads/master/prek.schema.json
2
+
3
+ [[repos]]
4
+ repo = "https://gitlab.com/andyrids/pkgdx"
5
+ rev = "v0.5.0"
6
+
7
+ [[repos.hooks]]
8
+ id = "pkgdx-lint"
9
+ name = "Lint [Ruff]"
10
+
11
+ [[repos.hooks]]
12
+ id = "pkgdx-format"
13
+ name = "Format [Ruff]"
14
+
15
+ [[repos.hooks]]
16
+ id = "pkgdx-markdown"
17
+ name = "Check Markdown [PyMarkdown]"
18
+
19
+ [[repos.hooks]]
20
+ id = "pkgdx-secrets"
21
+ name = "Detect Secrets [detect-secrets]"
22
+
23
+ [[repos]]
24
+ repo = "local"
25
+
26
+ [[repos.hooks]]
27
+ id = "pkgdx-typing"
28
+ name = "Typing [Mypy]"
29
+ entry = "uv run pkgdx-typing-hook"
30
+ language = "system"
31
+ types_or = ["python", "pyi"]
32
+ exclude = "tests/"
33
+ require_serial = true
34
+ pass_filenames = false
35
+ verbose = true
36
+
37
+ [[repos]]
38
+ repo = "builtin"
39
+
40
+ [[repos.hooks]]
41
+ id = "check-toml"
42
+ name = "Check TOML [Builtin]"
43
+
44
+ [[repos.hooks]]
45
+ id = "check-yaml"
46
+ name = "Check YAML [Builtin]"
47
+
48
+ [[repos.hooks]]
49
+ id = "detect-private-key"
50
+ name = "Detect PEM [Builtin]"
@@ -0,0 +1,44 @@
1
+ [mypy]
2
+ # Require fully-typed function signatures
3
+ disallow_untyped_defs = true
4
+ disallow_incomplete_defs = true
5
+ disallow_untyped_calls = true
6
+ disallow_untyped_decorators = true
7
+
8
+ # Disallow implicit Any — forces explicit handling of untyped imports
9
+ disallow_any_generics = true
10
+ disallow_any_unimported = true
11
+ disallow_subclassing_any = true
12
+
13
+ # Warn when Any propagates through return values
14
+ warn_return_any = true
15
+
16
+ # Enforce clean type: ignore hygiene
17
+ warn_unused_ignores = true
18
+ warn_redundant_casts = true
19
+ warn_unused_configs = true
20
+
21
+ # Enforce explicit Optional and equality semantics
22
+ strict_equality = true
23
+ no_implicit_optional = true
24
+
25
+ # Check bodies of functions even without annotations
26
+ check_untyped_defs = true
27
+
28
+ # Prevent accidental public re-exports
29
+ no_implicit_reexport = true
30
+
31
+ # Additional strict checks (e.g. TypeVar variance)
32
+ extra_checks = true
33
+
34
+ # Show error codes to enable precise type: ignore[<code>] annotations
35
+ show_error_codes = true
36
+
37
+ warn_unreachable = true
38
+
39
+ warn_no_return = true
40
+
41
+ # Default target when none is given (hooks run with pass_filenames: false);
42
+ # resolved from the working directory, so the whole project is checked
43
+ files = .
44
+ exclude = (^|/)tests/
@@ -0,0 +1,9 @@
1
+ [tool.pymarkdown]
2
+ extensions.markdown-tables.enabled = true
3
+ extensions.front-matter.enabled = true
4
+ extensions.front-matter.allow_blank_lines = true
5
+ plugins.line-length.enabled = true
6
+ plugins.line-length.heading_line_length = 120
7
+ plugins.line-length.line_length = 100
8
+ plugins.line-length.table_line_length = 100
9
+ plugins.table-column-style.enabled = false
@@ -0,0 +1,57 @@
1
+ exclude = []
2
+ indent-width = 4
3
+ line-length = 79
4
+
5
+ [format]
6
+ indent-style = "space"
7
+ line-ending = "auto"
8
+ quote-style = "double"
9
+
10
+ [lint]
11
+ select = [
12
+ "A", # flake8-builtins (ruleset)
13
+ "ANN001", # flake8-annotations (missing-type-function-argument)
14
+ "ANN002", # flake8-annotations (missing-type-args)
15
+ "ANN003", # flake8-annotations (missing-type-kwargs)
16
+ "ANN201", # flake8-annotations (missing-return-type-undocumented-public-function)
17
+ "ANN202", # flake8-annotations (missing-return-type-private-function)
18
+ "D1", # pydocstyle (undocumented-* ruleset)
19
+ "D400", # pydocstyle (missing-trailing-period)
20
+ "D401", # pydocstyle (non-imperative-mood)
21
+ "D403", # pydocstyle (first-word-uncapitalized)
22
+ "D417", # pydocstyle (undocumented-param)
23
+ "D419", # pydocstyle (empty-docstring)
24
+ "E", # pycodestyle-error (ruleset)
25
+ "ERA", # eradicate (ruleset)
26
+ "F541", # pyflakes (f-string-missing-placeholders)
27
+ "F401", # pyflakes (unused-import)
28
+ "F841", # pyflakes (unused-variable)
29
+ "G", # flake8-logging-format (ruleset)
30
+ "I001", # isort (unsorted-imports)
31
+ "I002", # isort (missing-required-import)
32
+ "ISC", # flake8-implicit-str-concat (ruleset)
33
+ "LOG", # flake8-logging (logging ruleset)
34
+ "N804", # pep8-naming (invalid-first-argument-name-for-class-method)
35
+ "N805", # pep8-naming (invalid-first-argument-name-for-method)
36
+ "NPY001", # NumPy-specific rules (numpy-deprecated-type-alias)
37
+ "NPY003", # NumPy-specific rules (numpy-deprecated-function)
38
+ "PERF", # perflint (ruleset)
39
+ "PYI034", # flake8-pyi (non-self-return-type
40
+ "RET", # flake8-return (ruleset)
41
+ "T100", # flake8-debugger (debugger)
42
+ "T201", # flake8-print (print)
43
+ "TC001", # flake8-type-checking (typing-only-first-party-import)
44
+ "TC002", # flake8-type-checking (typing-only-third-party-import)
45
+ "TC003", # flake8-type-checking (typing-only-standard-library-import)
46
+ "TC004", # flake8-type-checking (runtime-import-in-type-checking-block)
47
+ "TRY002", # tryceratops (raise-vanilla-class)
48
+ "TRY004", # tryceratops (type-check-without-type-error)
49
+ "TRY300", # tryceratops (try-consider-else)
50
+ "TRY401", # tryceratops (verbose-log-message)
51
+ "UP", # pyupgrade (lru-cache-with-maxsize-none)
52
+ "W", # pycodestyle-warning (ruleset)
53
+ "C90", # McCabe complexity (complex-structure)
54
+ ]
55
+
56
+ [lint.pydocstyle]
57
+ convention = "google"