-
-
Notifications
You must be signed in to change notification settings - Fork 267
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
Feature: version providers #646
Merged
Lee-W
merged 6 commits into
commitizen-tools:v3
from
noirbizarre:feature/version-provider
Feb 12, 2023
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2de2ea4
feat(providers): add a `commitizen.provider` endpoint for alternative…
noirbizarre 3bf2021
feat(providers): add support for some TOML-based versions (PEP621, Po…
noirbizarre 4a5fda3
feat(providers): add support for some JSON-based version providers (N…
noirbizarre ec5caf0
docs(deps): upgrade mkdocs-material and tidy some snippets
noirbizarre 2db5c75
feat(providers): add a `scm` version provider
noirbizarre 5672eaf
test(providers): factorize some version providers tests
noirbizarre 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 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 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 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 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 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,240 @@ | ||
from __future__ import annotations | ||
|
||
import json | ||
import re | ||
from abc import ABC, abstractmethod | ||
from pathlib import Path | ||
from typing import Any, Callable, ClassVar, Optional, cast | ||
|
||
import importlib_metadata as metadata | ||
import tomlkit | ||
from packaging.version import VERSION_PATTERN, Version | ||
|
||
from commitizen.config.base_config import BaseConfig | ||
from commitizen.exceptions import VersionProviderUnknown | ||
from commitizen.git import get_tags | ||
|
||
PROVIDER_ENTRYPOINT = "commitizen.provider" | ||
DEFAULT_PROVIDER = "commitizen" | ||
|
||
|
||
class VersionProvider(ABC): | ||
""" | ||
Abstract base class for version providers. | ||
|
||
Each version provider should inherit and implement this class. | ||
""" | ||
|
||
config: BaseConfig | ||
|
||
def __init__(self, config: BaseConfig): | ||
self.config = config | ||
|
||
@abstractmethod | ||
def get_version(self) -> str: | ||
""" | ||
Get the current version | ||
""" | ||
... | ||
|
||
@abstractmethod | ||
def set_version(self, version: str): | ||
""" | ||
Set the new current version | ||
""" | ||
... | ||
|
||
|
||
class CommitizenProvider(VersionProvider): | ||
""" | ||
Default version provider: Fetch and set version in commitizen config. | ||
""" | ||
|
||
def get_version(self) -> str: | ||
return self.config.settings["version"] # type: ignore | ||
|
||
def set_version(self, version: str): | ||
self.config.set_key("version", version) | ||
|
||
|
||
class FileProvider(VersionProvider): | ||
""" | ||
Base class for file-based version providers | ||
""" | ||
|
||
filename: ClassVar[str] | ||
|
||
@property | ||
def file(self) -> Path: | ||
return Path() / self.filename | ||
|
||
|
||
class TomlProvider(FileProvider): | ||
""" | ||
Base class for TOML-based version providers | ||
""" | ||
|
||
def get_version(self) -> str: | ||
document = tomlkit.parse(self.file.read_text()) | ||
return self.get(document) | ||
|
||
def set_version(self, version: str): | ||
document = tomlkit.parse(self.file.read_text()) | ||
self.set(document, version) | ||
self.file.write_text(tomlkit.dumps(document)) | ||
|
||
def get(self, document: tomlkit.TOMLDocument) -> str: | ||
return document["project"]["version"] # type: ignore | ||
|
||
def set(self, document: tomlkit.TOMLDocument, version: str): | ||
document["project"]["version"] = version # type: ignore | ||
|
||
|
||
class Pep621Provider(TomlProvider): | ||
""" | ||
PEP-621 version management | ||
""" | ||
|
||
filename = "pyproject.toml" | ||
|
||
|
||
class PoetryProvider(TomlProvider): | ||
""" | ||
Poetry version management | ||
""" | ||
|
||
filename = "pyproject.toml" | ||
|
||
def get(self, pyproject: tomlkit.TOMLDocument) -> str: | ||
return pyproject["tool"]["poetry"]["version"] # type: ignore | ||
|
||
def set(self, pyproject: tomlkit.TOMLDocument, version: str): | ||
pyproject["tool"]["poetry"]["version"] = version # type: ignore | ||
|
||
|
||
class CargoProvider(TomlProvider): | ||
""" | ||
Cargo version management | ||
""" | ||
|
||
filename = "Cargo.toml" | ||
|
||
def get(self, document: tomlkit.TOMLDocument) -> str: | ||
return document["package"]["version"] # type: ignore | ||
|
||
def set(self, document: tomlkit.TOMLDocument, version: str): | ||
document["package"]["version"] = version # type: ignore | ||
|
||
|
||
class JsonProvider(FileProvider): | ||
""" | ||
Base class for JSON-based version providers | ||
""" | ||
|
||
indent: ClassVar[int] = 2 | ||
|
||
def get_version(self) -> str: | ||
document = json.loads(self.file.read_text()) | ||
return self.get(document) | ||
|
||
def set_version(self, version: str): | ||
document = json.loads(self.file.read_text()) | ||
self.set(document, version) | ||
self.file.write_text(json.dumps(document, indent=self.indent) + "\n") | ||
|
||
def get(self, document: dict[str, Any]) -> str: | ||
return document["version"] # type: ignore | ||
|
||
def set(self, document: dict[str, Any], version: str): | ||
document["version"] = version | ||
|
||
|
||
class NpmProvider(JsonProvider): | ||
""" | ||
npm package.json version management | ||
""" | ||
|
||
filename = "package.json" | ||
|
||
|
||
class ComposerProvider(JsonProvider): | ||
""" | ||
Composer version management | ||
""" | ||
|
||
filename = "composer.json" | ||
indent = 4 | ||
|
||
|
||
class ScmProvider(VersionProvider): | ||
""" | ||
A provider fetching the current/last version from the repository history | ||
|
||
The version is fetched using `git describe` and is never set. | ||
|
||
It is meant for `setuptools-scm` or any package manager `*-scm` provider. | ||
""" | ||
|
||
TAG_FORMAT_REGEXS = { | ||
"$version": r"(?P<version>.+)", | ||
"$major": r"(?P<major>\d+)", | ||
"$minor": r"(?P<minor>\d+)", | ||
"$patch": r"(?P<patch>\d+)", | ||
"$prerelease": r"(?P<prerelease>\w+\d+)?", | ||
"$devrelease": r"(?P<devrelease>\.dev\d+)?", | ||
} | ||
|
||
def _tag_format_matcher(self) -> Callable[[str], Optional[str]]: | ||
pattern = self.config.settings.get("tag_format") or VERSION_PATTERN | ||
for var, tag_pattern in self.TAG_FORMAT_REGEXS.items(): | ||
pattern = pattern.replace(var, tag_pattern) | ||
|
||
regex = re.compile(f"^{pattern}$", re.VERBOSE) | ||
|
||
def matcher(tag: str) -> Optional[str]: | ||
match = regex.match(tag) | ||
if not match: | ||
return None | ||
groups = match.groupdict() | ||
if "version" in groups: | ||
return groups["version"] | ||
elif "major" in groups: | ||
return "".join( | ||
( | ||
groups["major"], | ||
f".{groups['minor']}" if groups.get("minor") else "", | ||
f".{groups['patch']}" if groups.get("patch") else "", | ||
groups["prerelease"] if groups.get("prerelease") else "", | ||
groups["devrelease"] if groups.get("devrelease") else "", | ||
) | ||
) | ||
elif pattern == VERSION_PATTERN: | ||
return str(Version(tag)) | ||
return None | ||
|
||
return matcher | ||
|
||
def get_version(self) -> str: | ||
matcher = self._tag_format_matcher() | ||
return next( | ||
(cast(str, matcher(t.name)) for t in get_tags() if matcher(t.name)), "0.0.0" | ||
) | ||
|
||
def set_version(self, version: str): | ||
# Not necessary | ||
pass | ||
|
||
|
||
def get_provider(config: BaseConfig) -> VersionProvider: | ||
""" | ||
Get the version provider as defined in the configuration | ||
|
||
:raises VersionProviderUnknown: if the provider named by `version_provider` is not found. | ||
""" | ||
provider_name = config.settings["version_provider"] or DEFAULT_PROVIDER | ||
try: | ||
(ep,) = metadata.entry_points(name=provider_name, group=PROVIDER_ENTRYPOINT) | ||
except ValueError: | ||
raise VersionProviderUnknown(f'Version Provider "{provider_name}" unknown.') | ||
provider_cls = ep.load() | ||
return cast(VersionProvider, provider_cls(config)) |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think of using protocols?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In this precise case, I prefer
ABC
overProtocol
because:config
in the method signatures, but this makes more verbose code without benefits in my opinion)ABC
force to implement methods and raise an explicit error if not, which I think is easier to understand (so more discoverable for them, less support for you)But if you prefer
Protocol
overABC
I can switch 👍🏼There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@woile What do you think?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I prefer
Protocol
🤣 but usingABC
is fine as well. Point 2 is the key, withProtocols
people would have to usemypy
to catch the problems, I like the explicit error.