Repository navigation
build: embed source git commit in built package #1935
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
smflorentino
wants to merge
4
commits into
main
Choose a base branch
from
evals-py-version
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6085678
build: embed source git commit in built package
smflorentino 6e65aaa
build: type-check hatch_build.py against real hatchling
smflorentino c81692e
build: drop hatchling version bounds
smflorentino f51f9c3
chore: bump version so the next release carries the commit id
smflorentino File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| """Hatch build hook that stamps the source git commit into the built package. | ||
|
|
||
| Writes the file named by ``version-file`` in ``[tool.hatch.build.hooks.custom]`` | ||
| using the setuptools-scm / hatch-vcs convention (``__version__`` and | ||
| ``__commit_id__``), so an installed package can report the exact commit it was | ||
| built from:: | ||
|
|
||
| from <package>._version import __commit_id__ | ||
|
|
||
| The file is generated at build time and git-ignored. The commit comes from | ||
| ``git rev-parse HEAD`` when building from a checkout of this repo. When there is | ||
| no checkout (e.g. building a wheel from an sdist), the commit already recorded | ||
| in the file is kept. If neither is available, ``__commit_id__`` is ``None``. | ||
| """ | ||
|
|
||
| import ast | ||
| import subprocess | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from hatchling.builders.config import BuilderConfig | ||
| from hatchling.builders.hooks.plugin.interface import BuildHookInterface | ||
|
|
||
| TEMPLATE = '''\ | ||
| """Version and source commit of this build. Generated by hatch_build.py.""" | ||
|
|
||
| __all__ = ["__version__", "__commit_id__", "version", "commit_id"] | ||
|
|
||
| __version__ = version = {version!r} | ||
| __commit_id__ = commit_id = {commit_id!r} | ||
| ''' | ||
|
|
||
|
|
||
| class CommitIdBuildHook(BuildHookInterface[BuilderConfig]): | ||
| """Generate the version file before each build.""" | ||
|
|
||
| PLUGIN_NAME = "custom" | ||
|
|
||
| def initialize(self, version: str, build_data: dict[str, Any]) -> None: | ||
| """Write the version file and ship it despite it being git-ignored.""" | ||
| relative_path = self.config["version-file"] | ||
| version_file = Path(self.root) / relative_path | ||
| commit_id = _git_commit(Path(self.root)) or _recorded_commit(version_file) | ||
| version_file.write_text( | ||
| TEMPLATE.format(version=self.metadata.version, commit_id=commit_id), | ||
| encoding="utf-8", | ||
| ) | ||
| build_data["artifacts"].append(f"/{relative_path}") | ||
|
|
||
|
|
||
| def _git_commit(root: Path) -> str | None: | ||
| """Return HEAD's full SHA if ``root`` is tracked in a git checkout.""" | ||
| try: | ||
| # Confirms root belongs to this repo, not to an unrelated parent checkout. | ||
| subprocess.run( | ||
| ["git", "ls-files", "--error-unmatch", "pyproject.toml"], | ||
| cwd=root, | ||
| check=True, | ||
| capture_output=True, | ||
| ) | ||
| result = subprocess.run( | ||
| ["git", "rev-parse", "HEAD"], | ||
| cwd=root, | ||
| check=True, | ||
| capture_output=True, | ||
| text=True, | ||
| ) | ||
| except (OSError, subprocess.CalledProcessError): | ||
| return None | ||
| return result.stdout.strip() or None | ||
|
|
||
|
|
||
| def _recorded_commit(version_file: Path) -> str | None: | ||
| """Return the commit already in ``version_file`` (e.g. one shipped in an sdist).""" | ||
| try: | ||
| tree = ast.parse(version_file.read_text(encoding="utf-8")) | ||
| except (OSError, SyntaxError): | ||
| return None | ||
| for node in tree.body: | ||
| if ( | ||
| isinstance(node, ast.Assign) | ||
| and any( | ||
| isinstance(t, ast.Name) and t.id == "__commit_id__" | ||
| for t in node.targets | ||
| ) | ||
| and isinstance(node.value, ast.Constant) | ||
| and isinstance(node.value.value, str) | ||
| ): | ||
| return node.value.value | ||
| return None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| """Hatch build hook that stamps the source git commit into the built package. | ||
|
|
||
| Writes the file named by ``version-file`` in ``[tool.hatch.build.hooks.custom]`` | ||
| using the setuptools-scm / hatch-vcs convention (``__version__`` and | ||
| ``__commit_id__``), so an installed package can report the exact commit it was | ||
| built from:: | ||
|
|
||
| from <package>._version import __commit_id__ | ||
|
|
||
| The file is generated at build time and git-ignored. The commit comes from | ||
| ``git rev-parse HEAD`` when building from a checkout of this repo. When there is | ||
| no checkout (e.g. building a wheel from an sdist), the commit already recorded | ||
| in the file is kept. If neither is available, ``__commit_id__`` is ``None``. | ||
| """ | ||
|
|
||
| import ast | ||
| import subprocess | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from hatchling.builders.config import BuilderConfig | ||
| from hatchling.builders.hooks.plugin.interface import BuildHookInterface | ||
|
|
||
| TEMPLATE = '''\ | ||
| """Version and source commit of this build. Generated by hatch_build.py.""" | ||
|
|
||
| __all__ = ["__version__", "__commit_id__", "version", "commit_id"] | ||
|
|
||
| __version__ = version = {version!r} | ||
| __commit_id__ = commit_id = {commit_id!r} | ||
| ''' | ||
|
|
||
|
|
||
| class CommitIdBuildHook(BuildHookInterface[BuilderConfig]): | ||
| """Generate the version file before each build.""" | ||
|
|
||
| PLUGIN_NAME = "custom" | ||
|
|
||
| def initialize(self, version: str, build_data: dict[str, Any]) -> None: | ||
| """Write the version file and ship it despite it being git-ignored.""" | ||
| relative_path = self.config["version-file"] | ||
| version_file = Path(self.root) / relative_path | ||
| commit_id = _git_commit(Path(self.root)) or _recorded_commit(version_file) | ||
| version_file.write_text( | ||
| TEMPLATE.format(version=self.metadata.version, commit_id=commit_id), | ||
| encoding="utf-8", | ||
| ) | ||
| build_data["artifacts"].append(f"/{relative_path}") | ||
|
|
||
|
|
||
| def _git_commit(root: Path) -> str | None: | ||
| """Return HEAD's full SHA if ``root`` is tracked in a git checkout.""" | ||
| try: | ||
| # Confirms root belongs to this repo, not to an unrelated parent checkout. | ||
| subprocess.run( | ||
| ["git", "ls-files", "--error-unmatch", "pyproject.toml"], | ||
| cwd=root, | ||
| check=True, | ||
| capture_output=True, | ||
| ) | ||
| result = subprocess.run( | ||
| ["git", "rev-parse", "HEAD"], | ||
| cwd=root, | ||
| check=True, | ||
| capture_output=True, | ||
| text=True, | ||
| ) | ||
| except (OSError, subprocess.CalledProcessError): | ||
| return None | ||
| return result.stdout.strip() or None | ||
|
|
||
|
|
||
| def _recorded_commit(version_file: Path) -> str | None: | ||
| """Return the commit already in ``version_file`` (e.g. one shipped in an sdist).""" | ||
| try: | ||
| tree = ast.parse(version_file.read_text(encoding="utf-8")) | ||
| except (OSError, SyntaxError): | ||
| return None | ||
| for node in tree.body: | ||
| if ( | ||
| isinstance(node, ast.Assign) | ||
| and any( | ||
| isinstance(t, ast.Name) and t.id == "__commit_id__" | ||
| for t in node.targets | ||
| ) | ||
| and isinstance(node.value, ast.Constant) | ||
| and isinstance(node.value.value, str) | ||
| ): | ||
| return node.value.value | ||
| return None | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.