pax_global_header00006660000000000000000000000064143110771200014506gustar00rootroot0000000000000052 comment=2d5aadc70b7812fc80f57af7ca82e4b351c30eaf frankie567-hatch-regex-commit-c2167dc/000077500000000000000000000000001431107712000174655ustar00rootroot00000000000000frankie567-hatch-regex-commit-c2167dc/.editorconfig000066400000000000000000000003451431107712000221440ustar00rootroot00000000000000# http://editorconfig.org root = true [*] indent_style = space indent_size = 2 trim_trailing_whitespace = true insert_final_newline = true charset = utf-8 end_of_line = lf [*.py] indent_size = 4 [Makefile] indent_style = tab frankie567-hatch-regex-commit-c2167dc/.github/000077500000000000000000000000001431107712000210255ustar00rootroot00000000000000frankie567-hatch-regex-commit-c2167dc/.github/workflows/000077500000000000000000000000001431107712000230625ustar00rootroot00000000000000frankie567-hatch-regex-commit-c2167dc/.github/workflows/build.yml000066400000000000000000000026101431107712000247030ustar00rootroot00000000000000name: Build on: [push, pull_request] jobs: test: runs-on: ubuntu-latest strategy: matrix: python_version: [3.7, 3.8, 3.9, '3.10'] steps: - uses: actions/checkout@v1 - name: Set up Python uses: actions/setup-python@v1 with: python-version: ${{ matrix.python_version }} - name: Install dependencies shell: bash run: | python -m pip install --upgrade pip pip install hatch hatch env create - name: Lint and typecheck run: | hatch run lint-check # - name: Test with pytest # run: | # pytest --cov-report xml --cov=fief_client/ # - uses: codecov/codecov-action@v2 # with: # token: ${{ secrets.CODECOV_TOKEN }} # fail_ci_if_error: true # verbose: true release: runs-on: ubuntu-latest needs: test if: startsWith(github.ref, 'refs/tags/') steps: - uses: actions/checkout@v1 - name: Set up Python uses: actions/setup-python@v1 with: python-version: 3.7 - name: Install dependencies shell: bash run: | python -m pip install --upgrade pip pip install hatch - name: Build and publish on PyPI env: HATCH_INDEX_USER: ${{ secrets.HATCH_INDEX_USER }} HATCH_INDEX_AUTH: ${{ secrets.HATCH_INDEX_AUTH }} run: | hatch build hatch publish frankie567-hatch-regex-commit-c2167dc/.gitignore000066400000000000000000000024171431107712000214610ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ junit/ junit.xml test.db # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # .vscode .vscode/ # OS files .DS_Store # Terraform .terraform # SQLite databases *.db s3cfg frankie567-hatch-regex-commit-c2167dc/LICENSE000066400000000000000000000020601431107712000204700ustar00rootroot00000000000000MIT License Copyright (c) 2022 François Voron Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. frankie567-hatch-regex-commit-c2167dc/README.md000066400000000000000000000101231431107712000207410ustar00rootroot00000000000000# hatch-regex-commit [![PyPI - Version](https://img.shields.io/pypi/v/hatch-regex-commit.svg)](https://pypi.org/project/hatch-regex-commit) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hatch-regex-commit.svg)](https://pypi.org/project/hatch-regex-commit) ----- This provides a plugin for [Hatch](https://github.com/pypa/hatch) that automatically creates a Git **commit** and **tag** after version bumping. ## Global dependency Ensure `hatch-regex-commit` is defined within the `build-system.requires` field in your `pyproject.toml` file. ```toml [build-system] requires = ["hatchling", "hatch-regex-commit"] build-backend = "hatchling.build" ``` ## Version source The [version source plugin](https://hatch.pypa.io/latest/plugins/version-source/) name is `regex_commit`. - ***pyproject.toml*** ```toml [tool.hatch.version] source = "regex_commit" path = "my_library/___about___.py" ``` - ***hatch.toml*** ```toml [version] source = "regex_commit" path = "my_library/___about___.py" ``` ### Version source options This plugin inherits from the Hatch builtin [Regex version source](https://hatch.pypa.io/latest/plugins/version-source/regex/). It inherits from all its [options](https://hatch.pypa.io/latest/plugins/version-source/regex/#options) and add the following ones: | Option | Type | Default | Description | | ------------------- | ----------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | | `check_dirty` | `bool` | true | Check if the Git repository is dirty, e.g., you have uncommited changes. If you have, the version bumping will abort. | | `commit` | `bool` | true | Whether to create a Git commit. | | `commit_message` | `str` | `Bump version {current_version} → {new_version}` | Template of the Git commit message. | | `commit_extra_args` | `list[str]` | [] | List of [extra arguments](https://git-scm.com/docs/git-commit#_options) for Git commit command. | | `tag` | `bool` | true | Whether to create a Git tag. | | `tag_name` | `str` | `v{new_version}` | Template for the Git tag name. | | `tag_message` | `str` | `Bump version {current_version} → {new_version}` | Template of the Git tag message. | | `tag_sign` | `bool` | true | Whether to sign the Git tag. | ## Examples ### Basic ```toml [tool.hatch.version] source = "regex_commit" path = "my_library/___about___.py" ``` ### Custom commit message ```toml [tool.hatch.version] source = "regex_commit" path = "my_library/___about___.py" commit_message = "🚀 Version {new_version}" ``` ### Edit commit message in the editor before proceeding ```toml [tool.hatch.version] source = "regex_commit" path = "my_library/___about___.py" commit_extra_args = ["-e"] ``` ### Disable Git tag ```toml [tool.hatch.version] source = "regex_commit" path = "my_library/___about___.py" tag = false ``` ## License `hatch-regex-commit` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license. frankie567-hatch-regex-commit-c2167dc/hatch_regex_commit/000077500000000000000000000000001431107712000233165ustar00rootroot00000000000000frankie567-hatch-regex-commit-c2167dc/hatch_regex_commit/__about__.py000066400000000000000000000000261431107712000255740ustar00rootroot00000000000000__version__ = "0.0.3" frankie567-hatch-regex-commit-c2167dc/hatch_regex_commit/__init__.py000066400000000000000000000000001431107712000254150ustar00rootroot00000000000000frankie567-hatch-regex-commit-c2167dc/hatch_regex_commit/exceptions.py000066400000000000000000000005241431107712000260520ustar00rootroot00000000000000class HatchRegexCommitException(Exception): pass class GitNotAvailableException(HatchRegexCommitException): def __init__(self) -> None: self.message = "Git is not available on this system" class WorkingDirectoryIsDirtyException(HatchRegexCommitException): def __init__(self, message): self.message = message frankie567-hatch-regex-commit-c2167dc/hatch_regex_commit/git.py000066400000000000000000000072031431107712000244550ustar00rootroot00000000000000import errno import logging import os import subprocess from tempfile import NamedTemporaryFile from typing import List, Optional from hatch_regex_commit.exceptions import WorkingDirectoryIsDirtyException logger = logging.getLogger(__name__) class Git: _TEST_USABLE_COMMAND = ["git", "rev-parse", "--git-dir"] _COMMIT_COMMAND = ["git", "commit", "-F"] @classmethod def is_usable(cls): try: return ( subprocess.call( cls._TEST_USABLE_COMMAND, stderr=subprocess.PIPE, stdout=subprocess.PIPE, ) == 0 ) except OSError as e: if e.errno in (errno.ENOENT, errno.EACCES, errno.ENOTDIR): return False raise @classmethod def assert_nondirty(cls): lines = [ line.strip() for line in subprocess.check_output( ["git", "status", "--porcelain"] ).splitlines() if not line.strip().startswith(b"??") ] if lines: raise WorkingDirectoryIsDirtyException( "Git working directory is not clean:\n{}".format( b"\n".join(lines).decode() ) ) @classmethod def commit(cls, message: str, extra_args: Optional[List[str]] = None): extra_args = extra_args or [] with NamedTemporaryFile("wb", delete=False) as f: f.write(message.encode("utf-8")) try: subprocess.check_output(cls._COMMIT_COMMAND + [f.name] + extra_args) except subprocess.CalledProcessError as exc: err_msg = "Failed to run {}: return code {}, output: {}".format( exc.cmd, exc.returncode, exc.output ) logger.exception(err_msg) raise exc finally: os.unlink(f.name) @classmethod def latest_tag_info(cls): try: # git-describe doesn't update the git-index, so we do that subprocess.check_output(["git", "update-index", "--refresh"]) # get info about the latest tag in git describe_out = ( subprocess.check_output( [ "git", "describe", "--dirty", "--tags", "--long", "--abbrev=40", "--match=v*", ], stderr=subprocess.STDOUT, ) .decode() .split("-") ) except subprocess.CalledProcessError: logger.debug("Error when running git describe") return {} info = {} if describe_out[-1].strip() == "dirty": info["dirty"] = True describe_out.pop() info["commit_sha"] = describe_out.pop().lstrip("g") info["distance_to_latest_tag"] = int(describe_out.pop()) info["current_version"] = "-".join(describe_out).lstrip("v") return info @classmethod def add_path(cls, path): subprocess.check_output(["git", "add", "--update", path]) @classmethod def tag(cls, sign, name, message): """ Create a tag of the new_version in VCS. If only name is given, bumpversion uses a lightweight tag. Otherwise, it utilizes an annotated tag. """ command = ["git", "tag", name] if sign: command += ["--sign"] if message: command += ["--message", message] subprocess.check_output(command) frankie567-hatch-regex-commit-c2167dc/hatch_regex_commit/hooks.py000066400000000000000000000002651431107712000250160ustar00rootroot00000000000000from hatchling.plugin import hookimpl from hatch_regex_commit.version_source import RegexCommitSource @hookimpl def hatch_register_version_source(): return RegexCommitSource frankie567-hatch-regex-commit-c2167dc/hatch_regex_commit/version_source.py000066400000000000000000000054161431107712000267430ustar00rootroot00000000000000from typing import List, Type from hatchling.version.source.regex import RegexSource from hatch_regex_commit.exceptions import GitNotAvailableException from hatch_regex_commit.git import Git class RegexCommitSource(RegexSource): PLUGIN_NAME = "regex_commit" @property def git(self) -> Type[Git]: if not Git.is_usable(): raise GitNotAvailableException() return Git @property def config_check_dirty(self) -> bool: return self._get_bool_config("check_dirty", True) @property def config_commit(self) -> bool: return self._get_bool_config("commit", True) @property def config_commit_message(self) -> str: return self._get_str_config( "commit_message", "Bump version {current_version} → {new_version}" ) @property def config_commit_extra_args(self) -> List[str]: extra_args = self.config.get("commit_extra_args", []) if not isinstance(extra_args, list): raise TypeError(f"option `{extra_args}` must be a list") return extra_args @property def config_tag(self) -> bool: return self._get_bool_config("tag", True) @property def config_tag_name(self) -> str: return self._get_str_config("tag_name", "v{new_version}") @property def config_tag_message(self) -> str: return self._get_str_config( "tag_message", "Bump version {current_version} → {new_version}" ) @property def config_tag_sign(self) -> bool: return self._get_bool_config("tag_sign", True) def set_version(self, version, version_data): if self.config_check_dirty: self.git.assert_nondirty() super().set_version(version, version_data) context = {"current_version": version_data["version"], "new_version": version} if self.config_commit: file = self.config.get("path", "") self.git.add_path(file) commit_message = self.config_commit_message.format(**context) self.git.commit(commit_message, self.config_commit_extra_args) if self.config_tag: tag_name = self.config_tag_name.format(**context) tag_message = self.config_tag_message.format(**context) self.git.tag(self.config_tag_sign, tag_name, tag_message) def _get_bool_config(self, name: str, default: bool) -> bool: value = self.config.get(name, default) if not isinstance(value, bool): raise TypeError(f"option `{name}` must be a boolean") return value def _get_str_config(self, name: str, default: str) -> str: value = self.config.get(name, default) if not isinstance(value, str): raise TypeError(f"option `{name}` must be a string") return value frankie567-hatch-regex-commit-c2167dc/pyproject.toml000066400000000000000000000040551431107712000224050ustar00rootroot00000000000000[build-system] requires = ["hatchling", "hatch-regex-commit"] build-backend = "hatchling.build" [project] name = "hatch-regex-commit" description = "Hatch plugin to create a commit and tag when bumping version" readme = "README.md" requires-python = ">=3.7" license = "MIT" keywords = [] authors = [ { name = "François Voron", email = "fvoron@gmail.com" }, ] classifiers = [ "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Framework :: Hatch", ] dependencies = [ "hatchling" ] dynamic = ["version"] [project.urls] Documentation = "https://github.com/frankie567/hatch-regex-commit#readme" Issues = "https://github.com/frankie567/hatch-regex-commit/issues" Source = "https://github.com/frankie567/hatch-regex-commit" [project.entry-points.hatch] regex-commit = "hatch_regex_commit.hooks" [tool.hatch.version] source = "regex_commit" path = "hatch_regex_commit/__about__.py" commit_extra_args = ["-e"] [tool.hatch.envs.default] dependencies = [ "black", "isort", "mypy", "pytest", "pytest-cov", ] [tool.hatch.envs.default.scripts] cov = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=hatch_regex_commit --cov=tests" no-cov = "cov --no-cov" lint = [ "isort ./hatch_regex_commit", "isort ./tests", "black .", "mypy hatch_regex_commit/", ] lint-check = [ "isort --check-only ./hatch_regex_commit ./tests", "black --check .", "mypy hatch_regex_commit/", ] [[tool.hatch.envs.test.matrix]] python = ["37", "38", "39", "310", "311"] [tool.coverage.run] branch = true parallel = true omit = [ "hatch_regex_commit/__about__.py", ] [tool.coverage.report] exclude_lines = [ "no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:", ] [tool.isort] profile = "black" frankie567-hatch-regex-commit-c2167dc/tests/000077500000000000000000000000001431107712000206275ustar00rootroot00000000000000frankie567-hatch-regex-commit-c2167dc/tests/__init__.py000066400000000000000000000000001431107712000227260ustar00rootroot00000000000000