|
| 1 | +import os |
| 2 | +from pathlib import Path |
| 3 | +from tempfile import NamedTemporaryFile |
| 4 | + |
| 5 | +import tomli |
| 6 | +import tomli_w |
| 7 | +from hatchling.builders.hooks.plugin.interface import BuildHookInterface |
| 8 | +from hatchling.plugin import hookimpl |
| 9 | +from packaging.requirements import Requirement |
| 10 | +from packaging.specifiers import SpecifierSet |
| 11 | + |
| 12 | + |
| 13 | +class PinJumpstarter(BuildHookInterface): |
| 14 | + PLUGIN_NAME = "pin_jumpstarter" |
| 15 | + |
| 16 | + def initialize(self, version, build_data): |
| 17 | + if self.target_name != "sdist": |
| 18 | + return |
| 19 | + |
| 20 | + pyproject = Path(self.root) / "pyproject.toml" |
| 21 | + |
| 22 | + with pyproject.open("rb") as f: |
| 23 | + metadata = tomli.load(f) |
| 24 | + |
| 25 | + if "project" in metadata and "dependencies" in metadata["project"]: |
| 26 | + for i, dep in enumerate(metadata["project"]["dependencies"]): |
| 27 | + req = Requirement(dep) |
| 28 | + if req.name.startswith("jumpstarter"): |
| 29 | + req.specifier &= SpecifierSet(f"=={self.metadata.version}") |
| 30 | + metadata["project"]["dependencies"][i] = str(req) |
| 31 | + |
| 32 | + f = NamedTemporaryFile(delete=False) |
| 33 | + tomli_w.dump(metadata, f) |
| 34 | + f.close() |
| 35 | + |
| 36 | + build_data["__hatch_pin_jumpstarter_tempfile"] = f |
| 37 | + build_data["force_include"][f.name] = "pyproject.toml" |
| 38 | + |
| 39 | + def finalize(self, version, build_data, artifact_path): |
| 40 | + if self.target_name != "sdist": |
| 41 | + return |
| 42 | + |
| 43 | + f = build_data["__hatch_pin_jumpstarter_tempfile"] |
| 44 | + os.unlink(f.name) |
| 45 | + |
| 46 | + |
| 47 | +@hookimpl |
| 48 | +def hatch_register_build_hook(): |
| 49 | + return PinJumpstarter |
0 commit comments