pycraftbox-tools 4.0.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.
@@ -0,0 +1,131 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ .vscode/*
6
+ !.vscode/extensions.json
7
+ !.vscode/tasks.json
8
+ # C extensions
9
+ *.so
10
+
11
+ # Distribution / packaging
12
+ .Python
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ pip-wheel-metadata/
26
+ share/python-wheels/
27
+ *.egg-info/
28
+ .installed.cfg
29
+ *.egg
30
+ MANIFEST
31
+
32
+ # PyInstaller
33
+ # Usually these files are written by a python script from a template
34
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
+ *.manifest
36
+ *.spec
37
+
38
+ # Installer logs
39
+ pip-log.txt
40
+ pip-delete-this-directory.txt
41
+
42
+ # Unit test / coverage reports
43
+ htmlcov/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py,cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+
56
+ # Translations
57
+ *.mo
58
+ *.pot
59
+
60
+ # Django stuff:
61
+ *.log
62
+ local_settings.py
63
+ db.sqlite3
64
+ db.sqlite3-journal
65
+
66
+ # Flask stuff:
67
+ instance/
68
+ .webassets-cache
69
+
70
+ # Scrapy stuff:
71
+ .scrapy
72
+
73
+ # Sphinx documentation
74
+ docs/_build/
75
+
76
+ # PyBuilder
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ .python-version
88
+
89
+ # pipenv
90
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
91
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
92
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
93
+ # install all needed dependencies.
94
+ #Pipfile.lock
95
+
96
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
97
+ __pypackages__/
98
+
99
+ # Celery stuff
100
+ celerybeat-schedule
101
+ celerybeat.pid
102
+
103
+ # SageMath parsed files
104
+ *.sage.py
105
+
106
+ # Environments
107
+ .env
108
+ .venv
109
+ env/
110
+ venv/
111
+ ENV/
112
+ env.bak/
113
+ venv.bak/
114
+
115
+ # Spyder project settings
116
+ .spyderproject
117
+ .spyproject
118
+
119
+ # Rope project settings
120
+ .ropeproject
121
+
122
+ # mkdocs documentation
123
+ /site
124
+
125
+ # mypy
126
+ .mypy_cache/
127
+ .dmypy.json
128
+ dmypy.json
129
+
130
+ # Pyre type checker
131
+ .pyre/
@@ -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,28 @@
1
+ [project]
2
+ name = "pycraftbox-tools"
3
+ version = "4.0.0"
4
+ description = "Reusable development commands for uv-based Python repositories"
5
+ requires-python = ">=3.12"
6
+ dependencies = [
7
+ "black[jupyter]>=26.5.1",
8
+ "pytest>=9.1.1",
9
+ "uv>=0.9.0",
10
+ ]
11
+
12
+ [project.urls]
13
+ Homepage = "https://gitlab.com/erch/pycraftbox"
14
+ Repository = "https://gitlab.com/erch/pycraftbox"
15
+ Issues = "https://gitlab.com/erch/pycraftbox/-/issues"
16
+
17
+ [project.scripts]
18
+ prepare-commit = "pycraftbox.tools.prepare_commit:main"
19
+
20
+ [build-system]
21
+ requires = ["hatchling"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.build]
25
+ dev-mode-dirs = ["src"]
26
+
27
+ [tool.hatch.build.targets.wheel]
28
+ packages = ["src/pycraftbox"]
@@ -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())