pycraftbox-tools 4.0.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,5 @@
1
+ """Reusable command-line development tools."""
2
+
3
+ from .prepare_commit import PrepareCommitError, PrepareCommitRunner
4
+
5
+ __all__ = ["PrepareCommitError", "PrepareCommitRunner"]
@@ -0,0 +1,208 @@
1
+ """Generic prepare-commit workflow for uv-based Python repositories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import tomllib
11
+ from collections.abc import Sequence
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+
16
+ class PrepareCommitError(RuntimeError):
17
+ """Raised when repository preparation cannot be completed."""
18
+
19
+
20
+ class PrepareCommitRunner:
21
+ """Format, test and optionally version an arbitrary uv repository."""
22
+
23
+ _logger = logging.getLogger(__name__)
24
+
25
+ BUMP_RULES = ("major", "minor", "patch")
26
+
27
+ def __init__(self, project_root: Path | None = None) -> None:
28
+ """Create a runner rooted at a repository or the current directory."""
29
+ self._project_root = project_root
30
+
31
+ def run(self, args: Sequence[str] | None = None) -> int:
32
+ """Parse command-line arguments and prepare the target repository."""
33
+ parser = self._build_parser()
34
+ options = parser.parse_args(args)
35
+ root = self._resolve_project_root()
36
+
37
+ self._run([sys.executable, "-m", "black", "."], root)
38
+ self._run([sys.executable, "-m", "pytest"], root)
39
+
40
+ if options.bump_rule is not None:
41
+ self._bump_versions(root, options.bump_rule)
42
+ else:
43
+ self._logger.info("Version bump skipped.")
44
+
45
+ self._logger.info("Preparation complete.")
46
+ return 0
47
+
48
+ @classmethod
49
+ def _build_parser(cls) -> argparse.ArgumentParser:
50
+ """Build the public command-line parser."""
51
+ parser = argparse.ArgumentParser(
52
+ prog="prepare-commit",
53
+ description=(
54
+ "Format a repository with Black, run pytest, and optionally "
55
+ "bump every uv workspace package."
56
+ ),
57
+ )
58
+ parser.add_argument(
59
+ "bump_rule",
60
+ nargs="?",
61
+ choices=cls.BUMP_RULES,
62
+ help="optional synchronized version bump rule",
63
+ )
64
+ return parser
65
+
66
+ def _resolve_project_root(self) -> Path:
67
+ """Resolve the Git repository root or fail with an actionable error."""
68
+ if self._project_root is not None:
69
+ root = self._project_root.expanduser().resolve()
70
+ else:
71
+ completed = subprocess.run(
72
+ ["git", "rev-parse", "--show-toplevel"],
73
+ check=True,
74
+ capture_output=True,
75
+ text=True,
76
+ )
77
+ root = Path(completed.stdout.strip()).resolve()
78
+
79
+ if not root.joinpath("pyproject.toml").is_file():
80
+ raise PrepareCommitError(
81
+ f"No pyproject.toml was found at repository root: {root}"
82
+ )
83
+ return root
84
+
85
+ def _bump_versions(self, root: Path, bump_rule: str) -> None:
86
+ """Bump a root project and every member of a uv workspace."""
87
+ uv = shutil.which("uv")
88
+ if uv is None:
89
+ raise PrepareCommitError(
90
+ "The 'uv' executable is required for version bumping."
91
+ )
92
+
93
+ manifests = self._workspace_manifests(root)
94
+ for manifest in manifests:
95
+ package_name = self._project_name(manifest)
96
+ self._run(
97
+ [uv, "version", "--package", package_name, "--bump", bump_rule],
98
+ root,
99
+ )
100
+
101
+ if self._optional_project_name(root / "pyproject.toml") is not None:
102
+ self._run([uv, "version", "--bump", bump_rule], root)
103
+ self._run([uv, "lock"], root)
104
+
105
+ tracked_manifests = [root / "pyproject.toml", *manifests]
106
+ tracked_paths = [
107
+ path.relative_to(root) for path in tracked_manifests if path.is_file()
108
+ ]
109
+ lock_path = root / "uv.lock"
110
+ if lock_path.is_file():
111
+ tracked_paths.append(lock_path.relative_to(root))
112
+ self._run(["git", "add", "--", *(str(path) for path in tracked_paths)], root)
113
+
114
+ version = self._read_project_version(root / "pyproject.toml")
115
+ self._logger.info("Version updated to %s.", version or bump_rule)
116
+
117
+ @classmethod
118
+ def _workspace_manifests(cls, root: Path) -> list[Path]:
119
+ """Return project manifests for all configured workspace members."""
120
+ data = cls._load_toml(root / "pyproject.toml")
121
+ workspace = data.get("tool", {}).get("uv", {}).get("workspace", {})
122
+ members = workspace.get("members", [])
123
+ if not isinstance(members, list):
124
+ raise PrepareCommitError("tool.uv.workspace.members must be a list.")
125
+
126
+ manifests: set[Path] = set()
127
+ for pattern in members:
128
+ if not isinstance(pattern, str):
129
+ raise PrepareCommitError(
130
+ "Every tool.uv.workspace.members entry must be a string."
131
+ )
132
+ manifests.update(
133
+ path.joinpath("pyproject.toml").resolve()
134
+ for path in root.glob(pattern)
135
+ if path.is_dir() and path.joinpath("pyproject.toml").is_file()
136
+ )
137
+
138
+ exclusions = workspace.get("exclude", [])
139
+ if not isinstance(exclusions, list):
140
+ raise PrepareCommitError("tool.uv.workspace.exclude must be a list.")
141
+ for pattern in exclusions:
142
+ if not isinstance(pattern, str):
143
+ raise PrepareCommitError(
144
+ "Every tool.uv.workspace.exclude entry must be a string."
145
+ )
146
+ excluded = {
147
+ path.joinpath("pyproject.toml").resolve()
148
+ for path in root.glob(pattern)
149
+ if path.is_dir()
150
+ }
151
+ manifests.difference_update(excluded)
152
+
153
+ return sorted(manifests, key=lambda path: str(path.relative_to(root)))
154
+
155
+ @staticmethod
156
+ def _load_toml(path: Path) -> dict[str, Any]:
157
+ """Load a TOML file or raise a preparation error."""
158
+ try:
159
+ with path.open("rb") as file:
160
+ return tomllib.load(file)
161
+ except (OSError, tomllib.TOMLDecodeError) as error:
162
+ raise PrepareCommitError(f"Could not read {path}: {error}") from error
163
+
164
+ @classmethod
165
+ def _project_name(cls, manifest: Path) -> str:
166
+ """Return the required project name from a manifest."""
167
+ name = cls._optional_project_name(manifest)
168
+ if not isinstance(name, str) or not name:
169
+ raise PrepareCommitError(f"No project.name is defined in {manifest}.")
170
+ return name
171
+
172
+ @classmethod
173
+ def _optional_project_name(cls, manifest: Path) -> str | None:
174
+ """Return a project name when the manifest owns a Python project."""
175
+ name = cls._load_toml(manifest).get("project", {}).get("name")
176
+ return name if isinstance(name, str) and name else None
177
+
178
+ @classmethod
179
+ def _read_project_version(cls, manifest: Path) -> str | None:
180
+ """Return a static project version when one is declared."""
181
+ version = cls._load_toml(manifest).get("project", {}).get("version")
182
+ return version if isinstance(version, str) else None
183
+
184
+ def _run(self, command: Sequence[str], cwd: Path) -> None:
185
+ """Run one preparation command in the target repository."""
186
+ self._logger.info("$ %s", " ".join(command))
187
+ subprocess.run(list(command), cwd=cwd, check=True)
188
+
189
+
190
+ def main() -> int:
191
+ """Run the prepare-commit command and return its exit status."""
192
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
193
+ runner = PrepareCommitRunner()
194
+ try:
195
+ return runner.run(sys.argv[1:])
196
+ except (
197
+ PrepareCommitError,
198
+ FileNotFoundError,
199
+ subprocess.CalledProcessError,
200
+ ) as error:
201
+ runner._logger.error("Preparation failed: %s", error)
202
+ if isinstance(error, subprocess.CalledProcessError):
203
+ return error.returncode
204
+ return 1
205
+
206
+
207
+ if __name__ == "__main__":
208
+ raise SystemExit(main())
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.5
2
+ Name: pycraftbox-tools
3
+ Version: 4.0.0
4
+ Summary: Reusable development commands for uv-based Python repositories
5
+ Project-URL: Homepage, https://gitlab.com/erch/pycraftbox
6
+ Project-URL: Repository, https://gitlab.com/erch/pycraftbox
7
+ Project-URL: Issues, https://gitlab.com/erch/pycraftbox/-/issues
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: black[jupyter]>=26.5.1
10
+ Requires-Dist: pytest>=9.1.1
11
+ Requires-Dist: uv>=0.9.0
@@ -0,0 +1,6 @@
1
+ pycraftbox/tools/__init__.py,sha256=0LNq9Pp9b2mZFLfzi5gTHeS1v_l_tETo4r_A6QxVYyI,173
2
+ pycraftbox/tools/prepare_commit.py,sha256=mSeWiCd033fDmMpAIRivI-dE2C7RmwbdPjhzmC3ROlo,7800
3
+ pycraftbox_tools-4.0.0.dist-info/METADATA,sha256=iL8l2BU85fI0qnYxaca_lfNdSCG7kRSN_7X7Zxfv9VU,431
4
+ pycraftbox_tools-4.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ pycraftbox_tools-4.0.0.dist-info/entry_points.txt,sha256=HHHg4-Lo3NT_fosBpdNS7wOSXGo8H2VQOQBGrZKgXDQ,72
6
+ pycraftbox_tools-4.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ prepare-commit = pycraftbox.tools.prepare_commit:main