From a9052f1d7156c8dcff8ae9efa4ab06d05a0cf3d6 Mon Sep 17 00:00:00 2001 From: cclecle Date: Sun, 26 Mar 2023 20:25:57 +0100 Subject: [PATCH 1/4] back port from pychangelogfactory --- .gitignore | 2 ++ Jenkinsfile | 32 ++++++++++++++++++-------------- helpers/helper_base.py | 7 ++++--- helpers/quality_check.py | 3 ++- helpers/types_check.py | 19 +++++++++---------- 5 files changed, 35 insertions(+), 28 deletions(-) diff --git a/.gitignore b/.gitignore index 58782a1..221ee37 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,5 @@ docs helpers-results .coverage /.mypy_cache/ +.coverage +.mypy_cache \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile index 5a0144c..a097e14 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -397,14 +397,23 @@ pipeline { } post { always { - dir("gitrepo") { - publishHTML([ - reportDir: "helpers-results/quality_check", - reportFiles: "report.html", - reportName: "quality-report", - allowMissing: false, - alwaysLinkToLastBuild: true, - keepAll: true]) + dir("gitrepo") { + publishCoverage adapters: [cobertura(mergeToOneReport: true, path: "helpers-results/types_check/cobertura.xml")] + junit 'helpers-results/types_check/junit.xml' + publishHTML([ + reportDir: "helpers-results/quality_check", + reportFiles: "report.html", + reportName: "quality-report", + allowMissing: false, + alwaysLinkToLastBuild: true, + keepAll: true]) + publishHTML([ + reportDir: "helpers-results/types_check", + reportFiles: "index.html", + reportName: "types_check", + allowMissing: false, + alwaysLinkToLastBuild: true, + keepAll: true]) } } } @@ -481,12 +490,7 @@ pipeline { sz_full_rate = full_rate.setScale(2, RoundingMode.HALF_EVEN).toString() badge_coverage.setStatus(sz_full_rate) badge_coverage.setColor(getColorScale(full_rate)) - - //complexity = new BigDecimal( 10*GetCoverageValue_complexity(coverage_report_path)) - //sz_complexity = complexity.setScale(2, RoundingMode.HALF_EVEN).toString() - //badge_complexity.setStatus(sz_complexity) - //badge_quality.setColor(getColorScale_reversed(complexity)) - + //badge_maintainability records = readCSV file: 'helpers-results/complexity_check/MI.csv' maintainability = records[1][1] diff --git a/helpers/helper_base.py b/helpers/helper_base.py index 294ca80..ab88e6a 100644 --- a/helpers/helper_base.py +++ b/helpers/helper_base.py @@ -57,10 +57,11 @@ class helper_base(ABC): return process.stdout @classmethod - def run_cmd(cls, cmdarray): + def run_cmd(cls, cmdarray, silent: bool = False): p = subprocess.run(cmdarray, capture_output=True) - print(p.stdout) - print(p.stderr) + if not silent: + print(p.stdout.decode()) + print(p.stderr.decode()) return p.stdout diff --git a/helpers/quality_check.py b/helpers/quality_check.py index d57c523..4028148 100644 --- a/helpers/quality_check.py +++ b/helpers/quality_check.py @@ -37,7 +37,7 @@ class quality_check(helper_withresults_base): def GetPylintMessageList(cls): Messagelist = dict() regex = r"^:([a-zA-Z-]+) \(([^\)]+)\)" - for line in cls.run_cmd([sys.executable, "-m", "pylint", "--list-msgs"]).splitlines(): + for line in cls.run_cmd([sys.executable, "-m", "pylint", "--list-msgs"], True).splitlines(): if res := re.search(regex, line.decode()): Messagelist[res.group(1)] = res.group(2) cls.PylintMessageList = Messagelist @@ -52,6 +52,7 @@ class quality_check(helper_withresults_base): @classmethod def do_job(cls): print("checking code quality ...") + cls.GetPylintMessageList() RES_all = dict() diff --git a/helpers/types_check.py b/helpers/types_check.py index 6179581..62d17f0 100644 --- a/helpers/types_check.py +++ b/helpers/types_check.py @@ -24,22 +24,18 @@ class types_check(helper_withresults_base): print("checking code typing ...") result = api.run( [ # project path - "-m", - "src." + str(cls.pyproject["project"]["name"]), + "-p", + "src.pychangelogfactory", # analysis configuration - "--ignore-missing-imports", - "--strict-equality", + # "--show-traceback", + "--explicit-package-bases", + # "--strict-equality", + # "--check-untyped-defs", # reports generation "--cobertura-xml-report", str(cls.get_result_dir()), "--html-report", str(cls.get_result_dir()), - "--linecount-report", - str(cls.get_result_dir()), - "--linecoverage-report", - str(cls.get_result_dir()), - "--lineprecision-report", - str(cls.get_result_dir()), "--txt-report", str(cls.get_result_dir()), "--xml-report", @@ -52,6 +48,9 @@ class types_check(helper_withresults_base): if result[0]: print("\nType checking report:\n") print(result[0]) # stdout + # converting the report using pylint_json2html (/!\ internal API, but as their is no leading '_' ...) + with open(cls.get_result_dir() / "raw_eport.txt", "w+", encoding="utf-8") as Outfile: + Outfile.write(result[0]) if result[1]: print("\nError report:\n") -- 2.47.3 From dc322e52da147a585e979c5d2abd5e5c17147c00 Mon Sep 17 00:00:00 2001 From: cclecle Date: Sun, 26 Mar 2023 20:38:00 +0100 Subject: [PATCH 2/4] fix quality cmd line --- helpers/types_check.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helpers/types_check.py b/helpers/types_check.py index 62d17f0..26b7942 100644 --- a/helpers/types_check.py +++ b/helpers/types_check.py @@ -25,7 +25,7 @@ class types_check(helper_withresults_base): result = api.run( [ # project path "-p", - "src.pychangelogfactory", + "src." + cls.pyproject["project"]["name"], # analysis configuration # "--show-traceback", "--explicit-package-bases", -- 2.47.3 From 5087cf96145e69571f892c1d38ea7a8de790a35b Mon Sep 17 00:00:00 2001 From: cclecle Date: Mon, 27 Mar 2023 01:03:21 +0100 Subject: [PATCH 3/4] improve typing checks and fix warnings / errors --- RUN_complexity.launch | 2 +- RUN_mkdocs.launch | 2 +- RUN_quality.launch | 2 +- RUN_unittest.launch | 2 +- helpers/types_check.py | 1 + src/pygitversionhelper/data/__init__.py | 7 + src/pygitversionhelper/gitversionhelper.py | 253 ++++++++++++--------- test/test_gitversionhelper.py | 4 +- 8 files changed, 161 insertions(+), 112 deletions(-) create mode 100644 src/pygitversionhelper/data/__init__.py diff --git a/RUN_complexity.launch b/RUN_complexity.launch index f29538b..5422619 100644 --- a/RUN_complexity.launch +++ b/RUN_complexity.launch @@ -7,7 +7,7 @@ - + diff --git a/RUN_mkdocs.launch b/RUN_mkdocs.launch index bb142ed..31fdb36 100644 --- a/RUN_mkdocs.launch +++ b/RUN_mkdocs.launch @@ -10,7 +10,7 @@ - + diff --git a/RUN_quality.launch b/RUN_quality.launch index 43ae6da..7c59c30 100644 --- a/RUN_quality.launch +++ b/RUN_quality.launch @@ -7,7 +7,7 @@ - + diff --git a/RUN_unittest.launch b/RUN_unittest.launch index 78228a9..af0da74 100644 --- a/RUN_unittest.launch +++ b/RUN_unittest.launch @@ -7,7 +7,7 @@ - + diff --git a/helpers/types_check.py b/helpers/types_check.py index 26b7942..e909464 100644 --- a/helpers/types_check.py +++ b/helpers/types_check.py @@ -31,6 +31,7 @@ class types_check(helper_withresults_base): "--explicit-package-bases", # "--strict-equality", # "--check-untyped-defs", + "--enable-incomplete-feature=Unpack", # reports generation "--cobertura-xml-report", str(cls.get_result_dir()), diff --git a/src/pygitversionhelper/data/__init__.py b/src/pygitversionhelper/data/__init__.py new file mode 100644 index 0000000..5858865 --- /dev/null +++ b/src/pygitversionhelper/data/__init__.py @@ -0,0 +1,7 @@ +# pygitversionhelper (c) by chacha +# +# pygitversionhelper is licensed under a +# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License. +# +# You should have received a copy of the license along with this +# work. If not, see . diff --git a/src/pygitversionhelper/gitversionhelper.py b/src/pygitversionhelper/gitversionhelper.py index 910ba73..904f842 100644 --- a/src/pygitversionhelper/gitversionhelper.py +++ b/src/pygitversionhelper/gitversionhelper.py @@ -5,6 +5,7 @@ # # You should have received a copy of the license along with this # work. If not, see . + """ This project try to help doing handy operations with git when dealing with project versioning and tags on python project - @@ -28,16 +29,38 @@ Note: _Other Parameters_ are **kwargs from __future__ import annotations +from typing import TYPE_CHECKING, cast, TypedDict, Literal import os import subprocess import re from copy import copy import logging +from pathlib import Path from packaging.version import VERSION_PATTERN as packaging_VERSION_PATTERN +from typing_extensions import reveal_type + +if TYPE_CHECKING: + from typing import List, Optional, Any, Dict + from typing_extensions import Unpack + + TKwargs = TypedDict( + "TKwargs", + { + "version_std": Optional[str], + "same_branch": Optional[bool], + "formated_output": Optional[bool], + "bump_type": Optional[str], + "bump_dev_strategy": Optional[str], + "merged_output": Optional[bool], + "ignore_unknown_tags": Optional[bool], + "output_format": Optional[str], + }, + total=False, + ) -def _exec(cmd: str, root: str | os.PathLike | None = None, raw: bool = False) -> list[str]: +def _exec(cmd: str, root: Optional[str | os.PathLike[str]] = None, raw: bool = False) -> str | List[str]: """ helper function to handle system cmd execution Args: @@ -47,10 +70,18 @@ def _exec(cmd: str, root: str | os.PathLike | None = None, raw: bool = False) -> a list of command's return lines """ + _root: Path + if isinstance(root, str): + _root = Path(root) + elif isinstance(root, os.PathLike): + _root = Path(root) + else: + _root = Path(os.getcwd()) + p = subprocess.run( cmd, text=True, - cwd=root, + cwd=_root, capture_output=True, check=False, timeout=2, @@ -63,7 +94,7 @@ def _exec(cmd: str, root: str | os.PathLike | None = None, raw: bool = False) -> if int(p.returncode) < 0: raise gitversionhelper.unknownGITError(p.stderr) - if raw: + if raw is True: return p.stdout lines = p.stdout.splitlines() return [line.rstrip() for line in lines if line.rstrip()] @@ -129,8 +160,6 @@ class gitversionhelper: # pylint: disable=too-few-public-methods class containing methods focusing on commits """ - __OptDict = {"same_branch": "same_branch", "merged_output": "merged_output"} - class commitException(gitversionhelperException): """ generic commit exception @@ -142,7 +171,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods """ @classmethod - def getMessagesSinceTag(cls, tag: str, **kwargs) -> str: + def getMessagesSinceTag(cls, tag: str, **kwargs: Unpack[TKwargs]) -> str | List[str]: """ retrieve a commits message history from repository from Latest commit to the given tag @@ -155,7 +184,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods current_commit_id = cls.getLast(**kwargs) tag_commit_id = cls.getFromTag(tag) - if (cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True): + if ("same_branch" in kwargs) and (kwargs["same_branch"] is True): commits = _exec(f"git rev-list --first-parent --ancestry-path {tag_commit_id}..{current_commit_id}") else: commits = _exec(f"git rev-list --ancestry-path {tag_commit_id}..{current_commit_id}") @@ -163,8 +192,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods for commit in commits: result.append(cls.getMessage(commit)) - if (cls.__OptDict["merged_output"] in kwargs) and (kwargs[cls.__OptDict["merged_output"]] is True): - print("JOIN") + if ("merged_output" in kwargs) and (kwargs["merged_output"] is True): return os.linesep.join(result) return result @@ -182,7 +210,8 @@ class gitversionhelper: # pylint: disable=too-few-public-methods f'git log -z --pretty="tformat:%B%-C()" -n 1 {commit_hash}', None, True, - ).rstrip("\x00") + ) + res = cast(str, res).rstrip("\x00") except gitversionhelper.unknownGITFatalError as _e: raise cls.commitNotFound("no commit found in commit history") from _e @@ -206,7 +235,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return res[0] @classmethod - def getLast(cls, **kwargs) -> str: + def getLast(cls, **kwargs: Unpack[TKwargs]) -> str: """ retrieve last commit from repository Keyword Arguments: @@ -214,7 +243,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods Returns: the commit Id """ - if (cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True): + if ("same_branch" in kwargs) and (kwargs["same_branch"] is True): try: res = _exec("git rev-parse HEAD") except gitversionhelper.unknownGITFatalError as _e: @@ -231,7 +260,6 @@ class gitversionhelper: # pylint: disable=too-few-public-methods class containing methods focusing on tags """ - __OptDict = {"same_branch": "same_branch"} __validGitTagSort = [ "", "v:refname", @@ -258,25 +286,25 @@ class gitversionhelper: # pylint: disable=too-few-public-methods """ @classmethod - def getTags(cls, sort: str = "taggerdate", **kwargs) -> list[str | None]: + def getTags(cls, Sort: str = "taggerdate", **kwargs: Unpack[TKwargs]) -> List[str]: """ retrieve all tags from a repository Args: - sort: sorting constraints (git format) + Sort: sorting constraints (git format) Returns: the tags list """ - if sort not in cls.__validGitTagSort: - raise gitversionhelper.wrongArguments("sort option not in allowed list") + if Sort not in cls.__validGitTagSort: + raise gitversionhelper.wrongArguments("Sort option not in allowed list") - if (cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True): + if ("same_branch" in kwargs) and (kwargs["same_branch"] is True): currentBranch = _exec("git rev-parse --abbrev-ref HEAD") - return list(reversed(_exec(f"git tag --merged {currentBranch[0]} --sort={sort}"))) - return list(reversed(_exec(f"git tag -l --sort={sort}"))) + return list(reversed(_exec(f"git tag --merged {currentBranch[0]} --sort={Sort}"))) + return list(reversed(_exec(f"git tag -l --sort={Sort}"))) @classmethod - def getLastTag(cls, **kwargs) -> str | None: + def getLastTag(cls, **kwargs: Unpack[TKwargs]) -> str | None: """ retrieve the Latest tag from a repository Keyword Arguments: @@ -284,7 +312,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods Returns: the tag """ - if (cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True): + if ("same_branch" in kwargs) and (kwargs["same_branch"] is True): res = _exec("git describe --tags --first-parent --abbrev=0") else: res = _exec("git rev-list --tags --date-order --max-count=1") @@ -298,7 +326,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return res[0] @classmethod - def getDistanceFromTag(cls, tag: str = None, **kwargs) -> int: + def getDistanceFromTag(cls, tag: Optional[str] = None, **kwargs: Unpack[TKwargs]) -> int: """ retrieve the distance between Latest commit and tag in the repository Arguments: @@ -317,14 +345,11 @@ class gitversionhelper: # pylint: disable=too-few-public-methods class containing methods focusing on versions """ - __OptDict = { - "version_std": "version_std", - "formated_output": "formated_output", - "output_format": "output_format", - "ignore_unknown_tags": "ignore_unknown_tags", - } DefaultInputFormat = "Auto" - VersionStds = { + + TVersionStds = TypedDict("TVersionStds", {"regex": str, "regex_preversion_num": str, "regex_build_num": str}, total=False) + + VersionStds: dict[str, TVersionStds] = { "SemVer": { "regex": r"^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)" r"(?:-(?P(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)" @@ -333,7 +358,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods "regex_preversion_num": r"(?:\.)(?P(?:\d+(?!\w))+)", "regex_build_num": r"(?:\.)(?P(?:\d+(?!\w))+)", }, - "PEP440": {"regex": packaging_VERSION_PATTERN, "Auto": None}, + "PEP440": {"regex": packaging_VERSION_PATTERN}, } __versionReseted = False @@ -357,17 +382,16 @@ class gitversionhelper: # pylint: disable=too-few-public-methods generic version object """ - __OptDict = { - "bump_type": "bump_type", - "bump_dev_strategy": "bump_dev_strategy", - "formated_output": "formated_output", - } - DefaultBumpType = "patch" - BumpTypes = ["major", "minor", "patch", "dev"] - DefaultBumpDevStrategy = "post" - BumpDevStrategys = ["post", "pre-patch", "pre-minor", "pre-major"] + TBumpTypes = Literal["major", "minor", "patch", "dev"] + DefaultBumpType: TBumpTypes = "patch" + BumpTypes: set[TBumpTypes] = {"major", "minor", "patch", "dev"} - version_std: str = "None" + TBumpDevStrategies = Literal["post", "pre-patch", "pre-minor", "pre-major"] + DefaultBumpDevStrategy: TBumpDevStrategies = "post" + BumpDevStrategies: set[TBumpDevStrategies] = {"post", "pre-patch", "pre-minor", "pre-major"} + + TVersionStd = Literal["Auto", "PEP440", "SemVer"] + version_std: TVersionStd = "Auto" major: int = 0 minor: int = 1 patch: int = 0 @@ -377,13 +401,13 @@ class gitversionhelper: # pylint: disable=too-few-public-methods def __init__( self, - version_std, - major=0, - minor=1, - patch=0, - pre_count=0, - post_count=0, - raw="0.1.0", + version_std: TVersionStd = "Auto", + major: int = 0, + minor: int = 1, + patch: int = 0, + pre_count: int = 0, + post_count: int = 0, + raw: str = "0.1.0", ): # pylint: disable=R0913 self.version_std = version_std self.major = major @@ -394,7 +418,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods self.raw = raw @classmethod - def _getBumpDevStrategy(cls, **kwargs) -> str: + def _getBumpDevStrategy(cls, **kwargs: Unpack[TKwargs]) -> str: """ get selected bump_dev_strategy Keyword Arguments: @@ -402,16 +426,17 @@ class gitversionhelper: # pylint: disable=too-few-public-methods Returns: Kwargs given bump_dev_strategy or the default one. """ - BumpDevStrategy = cls.DefaultBumpDevStrategy - if cls.__OptDict["bump_dev_strategy"] in kwargs: - if kwargs[cls.__OptDict["bump_dev_strategy"]] in cls.BumpDevStrategys: - BumpDevStrategy = kwargs[cls.__OptDict["bump_dev_strategy"]] + BumpDevStrategy: str = cls.DefaultBumpDevStrategy + + if kwargs and ("bump_dev_strategy" in kwargs): + if kwargs["bump_dev_strategy"] in cls.BumpDevStrategies: + BumpDevStrategy = kwargs["bump_dev_strategy"] else: - raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['bump_type']} requested") + raise gitversionhelper.wrongArguments(f"invalid {'bump_type'} requested") return BumpDevStrategy @classmethod - def _getBumpType(cls, **kwargs) -> str: + def _getBumpType(cls, **kwargs: Unpack[TKwargs]) -> str: """ get selected bump_type Keyword Arguments: @@ -419,15 +444,17 @@ class gitversionhelper: # pylint: disable=too-few-public-methods Returns: Kwargs given bump_type or the default one. """ - BumpType = cls.DefaultBumpType - if cls.__OptDict["bump_type"] in kwargs: - if kwargs[cls.__OptDict["bump_type"]] in cls.BumpTypes: - BumpType = kwargs[cls.__OptDict["bump_type"]] + BumpType: str = cls.DefaultBumpType + if "bump_type" in kwargs: + if kwargs["bump_type"] in cls.BumpTypes: + BumpType = kwargs["bump_type"] else: - raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['bump_type']} requested") + raise gitversionhelper.wrongArguments(f"invalid {'bump_type'} requested") return BumpType - def bump(self, amount: int = 1, **kwargs) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R0912 + def bump( + self, amount: int = 1, **kwargs: Unpack[TKwargs] + ) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R0912 """ bump the version to the next one Keyword Arguments: @@ -436,8 +463,11 @@ class gitversionhelper: # pylint: disable=too-few-public-methods Returns: the bumped version """ - BumpType = self._getBumpType(**kwargs) + + BumpType: str = self._getBumpType(**kwargs) + BumpDevStrategy = self._getBumpDevStrategy(**kwargs) + _v = copy(self) if BumpType == "dev": @@ -473,13 +503,14 @@ class gitversionhelper: # pylint: disable=too-few-public-methods _v.patch = _v.patch + amount _v.pre_count = 0 _v.post_count = 0 + _v.raw = _v.doFormatVersion(**kwargs) - if (self.__OptDict["formated_output"] in kwargs) and (kwargs[self.__OptDict["formated_output"]] is True): + if ("formated_output" in kwargs) and (kwargs["formated_output"] is True): return _v.doFormatVersion(**kwargs) return _v - def doFormatVersion(self, **kwargs) -> str: + def doFormatVersion(self, **kwargs: Unpack[TKwargs]) -> str: """ output a formated version string Keyword Arguments: @@ -490,7 +521,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return gitversionhelper.version.doFormatVersion(self, **kwargs) @classmethod - def _getVersionStd(cls, **kwargs) -> str: + def _getVersionStd(cls, **kwargs: Unpack[TKwargs]) -> gitversionhelper.version.MetaVersion.TVersionStd: """ get selected version_std Keyword Arguments: @@ -498,16 +529,16 @@ class gitversionhelper: # pylint: disable=too-few-public-methods Returns: Kwargs given version_std or the default one. """ - VersionStd = cls.DefaultInputFormat - if cls.__OptDict["version_std"] in kwargs: - if kwargs[cls.__OptDict["version_std"]] in cls.VersionStds: - VersionStd = kwargs[cls.__OptDict["version_std"]] + VersionStd: str = cls.DefaultInputFormat + if "version_std" in kwargs: + if kwargs["version_std"] in cls.VersionStds: + VersionStd = kwargs["version_std"] else: - raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['version_std']} requested") - return VersionStd + raise gitversionhelper.wrongArguments(f"invalid {'version_std'} requested") + return cast(gitversionhelper.version.MetaVersion.TVersionStd, VersionStd) @classmethod - def getCurrentVersion(cls, **kwargs) -> MetaVersion | str: + def getCurrentVersion(cls, **kwargs: Unpack[TKwargs]) -> gitversionhelper.version.MetaVersion | str: """ get the current version or bump depending of repository state Keyword Arguments: @@ -521,30 +552,33 @@ class gitversionhelper: # pylint: disable=too-few-public-methods """ if gitversionhelper.repository.isDirty() is not False: raise gitversionhelper.repository.repositoryDirty("The repository is dirty and a current version can not be generated.") + saved_kwargs = copy(kwargs) if "formated_output" in kwargs: del saved_kwargs["formated_output"] - _v = cls.getLastVersion(**saved_kwargs) + _v = cast(gitversionhelper.version.MetaVersion, cls.getLastVersion(**saved_kwargs)) if not cls.__versionReseted: amount = gitversionhelper.tag.getDistanceFromTag(_v.raw, **kwargs) - _v = _v.bump(amount, **saved_kwargs) + _v = cast(gitversionhelper.version.MetaVersion, _v.bump(amount, **saved_kwargs)) - if (cls.__OptDict["formated_output"] in kwargs) and (kwargs[cls.__OptDict["formated_output"]] is True): + if ("formated_output" in kwargs) and (kwargs["formated_output"] is True): return _v.doFormatVersion(**kwargs) return _v @classmethod - def getCurrentFormatedVersion(cls, **kwargs) -> str: + def getCurrentFormatedVersion(cls, **kwargs: Unpack[TKwargs]) -> str: """ Same as getCurrentVersion() with formated_output kwarg activated """ kwargs["formated_output"] = True - return cls.getCurrentVersion(**kwargs) + return cast(str, cls.getCurrentVersion(**kwargs)) @classmethod - def _parseTag(cls, tag, **kwargs): # pylint: disable=R0914, R0912, R0915 + def _parseTag( + cls, tag: str, **kwargs: Unpack[TKwargs] + ) -> gitversionhelper.version.MetaVersion: # pylint: disable=R0914, R0912, R0915 """get the last version from tags Arguments: tag: the tag to be parsed @@ -554,7 +588,8 @@ class gitversionhelper: # pylint: disable=too-few-public-methods Returns: the last version """ - VersionStd = cls._getVersionStd(**kwargs) + _m: Optional[re.Match[str]] + VersionStd: gitversionhelper.version.MetaVersion.TVersionStd = cls._getVersionStd(**kwargs) bAutoVersionStd = False if VersionStd == "Auto": bAutoVersionStd = True @@ -565,14 +600,12 @@ class gitversionhelper: # pylint: disable=too-few-public-methods re.VERBOSE | re.IGNORECASE, ) _m = re.match(_r, tag) - if not _m: + if _m is None: pass else: - major, minor, patch = ( - int(_m.group("major")), - int(_m.group("minor")), - int(_m.group("patch")), - ) + major = int(_m.group("major")) + minor = int(_m.group("minor")) + patch = int(_m.group("patch")) pre_count = 0 if _pre := _m.group("prerelease"): @@ -596,19 +629,25 @@ class gitversionhelper: # pylint: disable=too-few-public-methods re.VERBOSE | re.IGNORECASE, ) _m = re.match(_r, tag) - if not _m: + if _m is None: pass else: - ver = _m.group("release").split(".") - ver += ["0"] * (3 - len(ver)) - ver[0] = int(ver[0]) - ver[1] = int(ver[1]) - ver[2] = int(ver[2]) - major, minor, patch = tuple(ver) - pre_count = int(_m.group("pre_n")) if _m.group("pre_n") else 0 - post_count = int(_m.group("post_n2")) if _m.group("post_n2") else 0 - bFound = True - VersionStd = "PEP440" + res: str = _m.group("release") + if isinstance(res, str): + + ver = res.split(".") + ver += ["0"] * (3 - len(ver)) + + ver_int: List[int] = [0, 0, 0] + ver_int[0] = int(ver[0]) + ver_int[1] = int(ver[1]) + ver_int[2] = int(ver[2]) + major, minor, patch = tuple(ver_int) + + pre_count = int(_m.group("pre_n")) if _m.group("pre_n") else 0 + post_count = int(_m.group("post_n2")) if _m.group("post_n2") else 0 + bFound = True + VersionStd = "PEP440" if not bFound: raise gitversionhelper.version.noValidVersion("no valid version found in tags") @@ -618,7 +657,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return cls.MetaVersion(VersionStd, major, minor, patch, pre_count, post_count, tag) @classmethod - def getLastVersion(cls, **kwargs) -> MetaVersion | str: # pylint: disable=R0914, R0912, R0915 + def getLastVersion( + cls, **kwargs: Unpack[TKwargs] + ) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R0914, R0912, R0915 """get the last version from tags Keyword Arguments: version_std(str): the given version_std (can be None) @@ -628,20 +669,20 @@ class gitversionhelper: # pylint: disable=too-few-public-methods Returns: the last version """ - lastTag = cls.MetaVersion.raw + lastTag: str = cls.MetaVersion.raw cls.__versionReseted = False try: - lastTag = gitversionhelper.tag.getLastTag(**kwargs) + lastTag = cast(str, gitversionhelper.tag.getLastTag(**kwargs)) except gitversionhelper.tag.tagNotFound: logging.warning("tag not found, reseting versionning") cls.__versionReseted = True - _v = None + _v: Optional[gitversionhelper.version.MetaVersion] = None try: _v = cls._parseTag(lastTag, **kwargs) except gitversionhelper.version.noValidVersion as _ex: - if (cls.__OptDict["ignore_unknown_tags"] in kwargs) and (kwargs[cls.__OptDict["ignore_unknown_tags"]] is True): - tags = gitversionhelper.tag.getTags(sort="taggerdate", **kwargs) + if ("ignore_unknown_tags" in kwargs) and (kwargs["ignore_unknown_tags"] is True): + tags = gitversionhelper.tag.getTags(Sort="taggerdate", **kwargs) _v = None for _tag in tags: try: @@ -652,12 +693,12 @@ class gitversionhelper: # pylint: disable=too-few-public-methods if _v is None: raise gitversionhelper.version.noValidVersion() from _ex - if (cls.__OptDict["formated_output"] in kwargs) and (kwargs[cls.__OptDict["formated_output"]] is True): + if ("formated_output" in kwargs) and (kwargs["formated_output"] is True): return _v.doFormatVersion(**kwargs) return _v @classmethod - def doFormatVersion(cls, inputversion: MetaVersion, **kwargs) -> str: + def doFormatVersion(cls, inputversion: MetaVersion, **kwargs: Unpack[TKwargs]) -> str: """ output a formated version string Keyword Arguments: @@ -679,8 +720,8 @@ class gitversionhelper: # pylint: disable=too-few-public-methods pre_count = inputversion.pre_count patch = inputversion.patch - if cls.__OptDict["output_format"] in kwargs: - OutputFormat = kwargs[cls.__OptDict["output_format"]] + if "output_format" in kwargs: + OutputFormat = kwargs["output_format"] if OutputFormat is None: OutputFormat = "{major}.{minor}.{patch}{revpattern}{revcount}" diff --git a/test/test_gitversionhelper.py b/test/test_gitversionhelper.py index 137ed34..17f8dfd 100644 --- a/test/test_gitversionhelper.py +++ b/test/test_gitversionhelper.py @@ -730,9 +730,9 @@ class Test_gitversionhelper(unittest.TestCase): with self.assertRaises(pygitversionhelper.gitversionhelper.version.PreAndPostVersionUnsupported): pygitversionhelper.gitversionhelper.version._parseTag("0.0.1.pre1.post1") - def test_defect__git__wrongargument_sortargs(self): + def test_defect__git__wrongargument_Sortargs(self): with self.assertRaises(pygitversionhelper.gitversionhelper.wrongArguments): - pygitversionhelper.gitversionhelper.tag.getTags(sort="toto") + pygitversionhelper.gitversionhelper.tag.getTags(Sort="toto") def test_defect__git__notagfound(self): with open("demofile.txt", "w+t") as tmpFile: -- 2.47.3 From 5f9d513c59d7c33fd93ae0fd23bff54529a70742 Mon Sep 17 00:00:00 2001 From: cclecle Date: Mon, 27 Mar 2023 01:59:15 +0100 Subject: [PATCH 4/4] finish fixing typing updating and fixing doc --- docs-static/usage.md | 153 +++++++------ src/pygitversionhelper/gitversionhelper.py | 241 +++++++++------------ 2 files changed, 179 insertions(+), 215 deletions(-) diff --git a/docs-static/usage.md b/docs-static/usage.md index bbccb24..8169bd2 100644 --- a/docs-static/usage.md +++ b/docs-static/usage.md @@ -3,30 +3,32 @@ ## Installation From pypi repository (prefered): - - python -m pip install pygitversionhelper - +```console +/> python -m pip install pygitversionhelper +``` + From downloaded .whl file: +```console +/> python -m pip install pygitversionhelper--py3-none-any.whl +``` - python -m pip install pygitversionhelper--py3-none-any.whl - From master git repository: - - python -m pip install git+https://chacha.ddns.net/gitea/chacha/pygitversionhelper.git@master - +```console +/> python -m pip install git+https://chacha.ddns.net/gitea/chacha/pygitversionhelper.git@master +``` ## Import in your project Add this line on the top of your python script: - - #from pygitversionhelper import gitversionhelper - +```py +from pygitversionhelper import gitversionhelper +``` [optionnal] If you need to catch exception from this module: - - #from pygitversionhelper import gitversionhelperException - +```py +from pygitversionhelper import gitversionhelperException +``` ## Basic API All the API commands are static so it is not needed to create instantiate any object. @@ -34,93 +36,100 @@ All the API commands are static so it is not needed to create instantiate any ob They are all executed in the current active directory. One easy way to change directory: - - import os - os.chdir("") - -### sublib: repository +```py +import os +os.chdir("") +``` +### sub-lib: repository To check if a repository is dirty: - - if gitversionhelper.repository.isDirty(): - print("repository is dirty") - -### sublib: tag +```py +if gitversionhelper.repository.isDirty(): + print("repository is dirty") +``` +### sub-lib: tag List all tags [default to taggerdate order]: - - for tag in gitversionhelper.tag.getTags(): - print(f"found tag: {tag}") - +```py +for tag in gitversionhelper.tag.getTags(): + print(f"found tag: {tag}") +``` List all tags [using git refname order]: - - for tag in gitversionhelper.tag.getTags("v:refname"): - print(f"found tag: {tag}") - +```py +for tag in gitversionhelper.tag.getTags("v:refname"): + print(f"found tag: {tag}") +``` Get the last tag: - - print(f"most recent repository tag: {gitversionhelper.tag.getLastTag()}") - +```py +print(f"most recent repository tag: {gitversionhelper.tag.getLastTag()}") +``` Get the last tag [only on same branch]: - - print(f"most recent repository tag: {gitversionhelper.tag.getLastTag(same_branch=True)}") - +```py +print(f"most recent repository tag: {gitversionhelper.tag.getLastTag(same_branch=True)}") +``` Get the distance from HEAD to last tag: - - print(f"number of commit since last tag: {gitversionhelper.tag.getDistanceFromTag()}") - +```py +print(f"number of commit since last tag: {gitversionhelper.tag.getDistanceFromTag()}") +``` Get the distance from HEAD to last tag [only on same branch]: - - print(f"number of commit since last tag: {gitversionhelper.tag.getDistanceFromTag(same_branch=True)}") - -### sublib: version +```py +print(f"number of commit since last tag: {gitversionhelper.tag.getDistanceFromTag(same_branch=True)}") +``` +### sub-lib: version Get the last found version in the repository [return MetaVersion object]: - - print(f"most recent repository version: {gitversionhelper.version.getLastVersion()}") - +```py +print(f"most recent repository version: {gitversionhelper.version.getLastVersion()}") +``` Get the last found version in the repository [return formated string]: - - print(f"most recent repository version: {gitversionhelper.version.getLastVersion(formated_output=True)}") - +```py +print(f"most recent repository version: {gitversionhelper.version.getLastVersion(formated_output=True)}") +``` Others kwargs available to this function: * version_std: string to force a version standard for rendering ["PEP440" or "SemVer"] * same_branch: boolean to force searching on same branch * ignore\_unknown\_tags: boolean to allow unknown tag to be ignored -Get the current version of the repository, automatically bump it if the last one is not tagged [returns MetaVersion object]: - - print(f"current repository version: {gitversionhelper.version.getCurrentVersion()}") - +Get the current version of the repository, automatically bump it if the last commit is not tagged [returns MetaVersion object]: +```py +print(f"current repository version: {gitversionhelper.version.getCurrentVersion()}") +``` Or with formated output: - - print(f"current repository version: {gitversionhelper.version.getCurrentVersion(formated_output=True)}") - +```py +print(f"current repository version: {gitversionhelper.version.getCurrentVersion(formated_output=True)}") +``` Typical usage in CI/CD env: - - bumped_version = gitversionhelper.version.getCurrentVersion( formated_output=True, \ - version_std="PEP440", \ - bump_type="dev", \ - bump_dev_strategy="post") - print(f"current repository version: {bumped_version}") - +```py +bumped_version = gitversionhelper.version.getCurrentVersion( formated_output=True, \ + version_std="PEP440", \ + bump_type="dev", \ + bump_dev_strategy="post") +print(f"current repository version: {bumped_version}") +``` kwargs available to this function: * All same args as getLastVersion() * bump_type: if version need to be pump, allow to configure next release update type: __major, minor, patch, dev__ * bump\_dev\_strategy: if bump\_type is dev, allow to choose dev update strategy: __post, pre-patch, pre-minor, pre-major__ + A version object can also be manually formated: +```py +_version = gitversionhelper.tag.getCurrentVersion() +``` +Then; +```py +_version.doFormatVersion() +``` +or; +```py +gitversionhelper.version.doFormatVersion(_version) +``` +kwargs available to this function: - _version = gitversionhelper.tag.getCurrentVersion() - _version.doFormatVersion() - #or - gitversionhelper.version.doFormatVersion(_version) - -kwargs available to those function: - - output_format: string to choose a rendering format ["Auto","PEP440" or "SemVer"] +- output_format: string to choose a rendering format ["Auto","PEP440" or "SemVer"] ## Limitations diff --git a/src/pygitversionhelper/gitversionhelper.py b/src/pygitversionhelper/gitversionhelper.py index 904f842..4765769 100644 --- a/src/pygitversionhelper/gitversionhelper.py +++ b/src/pygitversionhelper/gitversionhelper.py @@ -7,16 +7,14 @@ # work. If not, see . """ -This project try to help doing handy operations with git when +This project try to help doing handy operations with git when dealing with project versioning and tags on python project - at leat for project using PEP440 or SemVer standards. One requirement is to keep it compact and to not cover too much fancy features. This is the reason why it is one single file with nested classes. -=> Design is on-purpose poorly expandable to keep the scope light. - -This library is maid for repository using tag as version. +This library is made for repository that uses tags as version. Support for non-version tags is optional and not well tested. This module is the main project file, containing all the code. @@ -24,7 +22,12 @@ This module is the main project file, containing all the code. Read the read me for more information. Check the unittest s for usage samples. -Note: _Other Parameters_ are **kwargs +///Note +_Other Parameters_ are **kwargs +/// + +Attributes: + TKwargs: Kwargs type definition for type hints """ from __future__ import annotations @@ -38,7 +41,6 @@ import logging from pathlib import Path from packaging.version import VERSION_PATTERN as packaging_VERSION_PATTERN -from typing_extensions import reveal_type if TYPE_CHECKING: from typing import List, Optional, Any, Dict @@ -61,13 +63,13 @@ if TYPE_CHECKING: def _exec(cmd: str, root: Optional[str | os.PathLike[str]] = None, raw: bool = False) -> str | List[str]: - """ - helper function to handle system cmd execution + """helper function to handle system cmd execution Args: cmd: command line to be executed root: root directory where the command need to be executed + raw: return bytes if True, str if False or None Returns: - a list of command's return lines + a list of command's return lines or the raw output """ _root: Path @@ -101,83 +103,60 @@ def _exec(cmd: str, root: Optional[str | os.PathLike[str]] = None, raw: bool = F class gitversionhelperException(Exception): - """ - general Module Exception - """ + """general Module Exception""" class gitversionhelper: # pylint: disable=too-few-public-methods - """ - main gitversionhelper class - """ + """main gitversionhelper class""" class wrongArguments(gitversionhelperException): - """ - wrong argument generic exception - """ + """wrong argument generic exception""" class unknownGITError(gitversionhelperException): - """ - unknown git error generic exception - """ + """unknown git error generic exception""" class unknownGITFatalError(unknownGITError): - """ - unknown fatal git error generic exception - """ + """unknown fatal git error generic exception""" class repository: - """ - class containing methods focusing on repository - """ + """class containing methods focusing on repository""" class repositoryException(gitversionhelperException): - """ - generic repository exeption - """ + """generic repository exeption""" class notAGitRepository(repositoryException): - """ - not a git repository exception - """ + """not-a-git-repository repository exception""" class repositoryDirty(repositoryException): - """ - dirty repository exception - """ + """dirty-repository repository exception""" @classmethod def isDirty(cls) -> bool: - """ - check if the repository is in dirty state + """check if the repository is in dirty state Returns: True if it is dirty """ return bool(_exec("git status --short")) class commit: - """ - class containing methods focusing on commits - """ + """class containing methods focusing on commits""" class commitException(gitversionhelperException): - """ - generic commit exception - """ + """generic commit exception""" class commitNotFound(commitException): - """ - tag not found exception - """ + """tag not found exception""" @classmethod def getMessagesSinceTag(cls, tag: str, **kwargs: Unpack[TKwargs]) -> str | List[str]: - """ - retrieve a commits message history from repository - from Latest commit to the given tag + """Retrieve a commits message history from repository. + + Start from Latest found commit until the given tag. + Args: + tag: tag of the commit where search will stop Keyword Arguments: - merged_output: output one single merged string - same_branch(bool): force searching only in the same branch + kwargs/merged_output (bool): Output one single merged string + kwargs/same_branch (bool): Force searching only in the same branch Returns: the commit message """ @@ -198,8 +177,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def getMessage(cls, commit_hash: str) -> str: - """ - retrieve a commit message from repository + """retrieve a commit message from repository Args: commit_hash: id of the commit Returns: @@ -219,8 +197,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def getFromTag(cls, tag: str) -> str: - """ - retrieve a commit from repository associated to a tag + """retrieve a commit from repository associated to a tag Args: tag: tag of the commit Returns: @@ -236,10 +213,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def getLast(cls, **kwargs: Unpack[TKwargs]) -> str: - """ - retrieve last commit from repository + """retrieve last commit from repository Keyword Arguments: - same_branch(bool): force searching only in the same branch + kwargs/same_branch (bool): force searching only in the same branch Returns: the commit Id """ @@ -256,9 +232,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return res[0] class tag: - """ - class containing methods focusing on tags - """ + """class containing methods focusing on tags""" __validGitTagSort = [ "", @@ -271,26 +245,21 @@ class gitversionhelper: # pylint: disable=too-few-public-methods ] class tagException(gitversionhelperException): - """ - generic tag exception - """ + """generic tag exception""" class tagNotFound(tagException): - """ - tag not found exception - """ + """tag-not-found tag exception""" class moreThanOneTag(tagException): - """ - more than one tag exception - """ + """more-than-one-tag tag exception""" @classmethod def getTags(cls, Sort: str = "taggerdate", **kwargs: Unpack[TKwargs]) -> List[str]: - """ - retrieve all tags from a repository + """retrieve all tags from a repository Args: Sort: sorting constraints (git format) + Keyword Arguments: + kwargs/same_branch (bool): force searching only in the same branch Returns: the tags list """ @@ -304,11 +273,10 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return list(reversed(_exec(f"git tag -l --sort={Sort}"))) @classmethod - def getLastTag(cls, **kwargs: Unpack[TKwargs]) -> str | None: - """ - retrieve the Latest tag from a repository + def getLastTag(cls, **kwargs: Unpack[TKwargs]) -> str: + """retrieve the Latest tag from a repository Keyword Arguments: - same_branch(bool): force searching only in the same branch + kwargs/same_branch (bool): force searching only in the same branch Returns: the tag """ @@ -327,12 +295,11 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def getDistanceFromTag(cls, tag: Optional[str] = None, **kwargs: Unpack[TKwargs]) -> int: - """ - retrieve the distance between Latest commit and tag in the repository + """retrieve the distance between Latest commit and tag in the repository Arguments: tag: reference tag, if None the most recent one will be used Keyword Arguments: - same_branch(bool): force searching only in the same branch + kwargs/same_branch (bool): force searching only in the same branch Returns: the tag """ @@ -341,9 +308,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return int(_exec(f"git rev-list {tag}..HEAD --count")[0]) class version: - """ - class containing methods focusing on versions - """ + """class containing methods focusing on versions""" DefaultInputFormat = "Auto" @@ -363,24 +328,16 @@ class gitversionhelper: # pylint: disable=too-few-public-methods __versionReseted = False class versionException(gitversionhelperException): - """ - generic version exception - """ + """generic version exception""" class noValidVersion(versionException): - """ - no valid version found exception - """ + """no valid version found exception""" class PreAndPostVersionUnsupported(versionException): - """ - pre and post release can not be present at the same time - """ + """pre and post release can not be present at the same time""" class MetaVersion: - """ - generic version object - """ + """generic version object""" TBumpTypes = Literal["major", "minor", "patch", "dev"] DefaultBumpType: TBumpTypes = "patch" @@ -419,10 +376,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def _getBumpDevStrategy(cls, **kwargs: Unpack[TKwargs]) -> str: - """ - get selected bump_dev_strategy + """get selected bump_dev_strategy Keyword Arguments: - bump_dev_strategy(str): the given bump_dev_strategy (can be None) + kwargs/bump_dev_strategy (str): the given bump_dev_strategy (can be None) Returns: Kwargs given bump_dev_strategy or the default one. """ @@ -437,10 +393,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def _getBumpType(cls, **kwargs: Unpack[TKwargs]) -> str: - """ - get selected bump_type + """get selected bump_type Keyword Arguments: - bump_type(str): the given bump_type (can be None) + kwargs/bump_type (str): the given bump_type (can be None) Returns: Kwargs given bump_type or the default one. """ @@ -452,14 +407,15 @@ class gitversionhelper: # pylint: disable=too-few-public-methods raise gitversionhelper.wrongArguments(f"invalid {'bump_type'} requested") return BumpType - def bump( + def bump( # pylint: disable=R1260,R0912 self, amount: int = 1, **kwargs: Unpack[TKwargs] - ) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R0912 - """ - bump the version to the next one + ) -> gitversionhelper.version.MetaVersion | str: + """bump the version to the next one + Args: + amount: number of revision to bump Keyword Arguments: - bump_type(str): the given bump_type (can be None) - bump_dev_strategy(str): the given bump_dev_strategy (can be None) + kwargs/bump_type (str): the given bump_type (can be None) + kwargs/bump_dev_strategy (str): the given bump_dev_strategy (can be None) Returns: the bumped version """ @@ -511,10 +467,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return _v def doFormatVersion(self, **kwargs: Unpack[TKwargs]) -> str: - """ - output a formated version string + """output a formated version string Keyword Arguments: - output_format: output format to render ("Auto" or "PEP440" or "SemVer") + kwargs/output_format: output format to render ("Auto" or "PEP440" or "SemVer") Returns: formated version string """ @@ -522,10 +477,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def _getVersionStd(cls, **kwargs: Unpack[TKwargs]) -> gitversionhelper.version.MetaVersion.TVersionStd: - """ - get selected version_std + """get selected version_std Keyword Arguments: - version_std(str): the given version_std (can be None) + kwargs/version_std (str): the given version_std (can be None) Returns: Kwargs given version_std or the default one. """ @@ -539,14 +493,14 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def getCurrentVersion(cls, **kwargs: Unpack[TKwargs]) -> gitversionhelper.version.MetaVersion | str: - """ - get the current version or bump depending of repository state + """get the current version or bump depending of repository state. Keyword Arguments: - version_std(str): the given version_std (can be None) - same_branch(bool): force searching only in the same branch - formated_output(bool) : output a formated version string - bump_type(str): the given bump_type (can be None) - bump_dev_strategy(str): the given bump_dev_strategy (can be None) + kwargs/version_std (str): the given version_std (can be None) + kwargs/same_branch (bool): force searching only in the same branch + kwargs/formated_output (bool): output a formated version string + kwargs/bump_type (str): the given bump_type (can be None) + kwargs/bump_dev_strategy (str): the given bump_dev_strategy (can be None) + kwargs/output_format (str): output format to render ("Auto" or "PEP440" or "SemVer") Returns: the last version """ @@ -560,7 +514,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods _v = cast(gitversionhelper.version.MetaVersion, cls.getLastVersion(**saved_kwargs)) if not cls.__versionReseted: - amount = gitversionhelper.tag.getDistanceFromTag(_v.raw, **kwargs) + amount = gitversionhelper.tag.getDistanceFromTag(_v.raw, **saved_kwargs) _v = cast(gitversionhelper.version.MetaVersion, _v.bump(amount, **saved_kwargs)) if ("formated_output" in kwargs) and (kwargs["formated_output"] is True): @@ -569,24 +523,30 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def getCurrentFormatedVersion(cls, **kwargs: Unpack[TKwargs]) -> str: - """ - Same as getCurrentVersion() with formated_output kwarg activated + """same as getCurrentVersion() with formated_output kwarg forced activated. + Keyword Arguments: + kwargs/version_std (str): the given version_std (can be None) + kwargs/same_branch (bool): force searching only in the same branch + kwargs/bump_type (str): the given bump_type (can be None) + kwargs/bump_dev_strategy (str): the given bump_dev_strategy (can be None) + kwargs/output_format (str): output format to render ("Auto" or "PEP440" or "SemVer") + Returns: + the last version """ kwargs["formated_output"] = True return cast(str, cls.getCurrentVersion(**kwargs)) @classmethod - def _parseTag( + def _parseTag( # pylint: disable=R1260,R0914,R0912,R0915 cls, tag: str, **kwargs: Unpack[TKwargs] - ) -> gitversionhelper.version.MetaVersion: # pylint: disable=R0914, R0912, R0915 - """get the last version from tags + ) -> gitversionhelper.version.MetaVersion: + """get version from tags. Arguments: tag: the tag to be parsed Keyword Arguments: - version_std(str): the given version_std (can be None) - ignore_unknown_tags(bool): skip tags with not decoded versions (default to False) + kwargs/version_std (str): the given version_std (can be None) Returns: - the last version + MetaVersion object """ _m: Optional[re.Match[str]] VersionStd: gitversionhelper.version.MetaVersion.TVersionStd = cls._getVersionStd(**kwargs) @@ -657,17 +617,15 @@ class gitversionhelper: # pylint: disable=too-few-public-methods return cls.MetaVersion(VersionStd, major, minor, patch, pre_count, post_count, tag) @classmethod - def getLastVersion( - cls, **kwargs: Unpack[TKwargs] - ) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R0914, R0912, R0915 + def getLastVersion(cls, **kwargs: Unpack[TKwargs]) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R1260 """get the last version from tags Keyword Arguments: - version_std(str): the given version_std (can be None) - same_branch(bool): force searching only in the same branch - formated_output(bool) : output a formated version string - ignore_unknown_tags(bool): skip tags with not decoded versions (default to False) + kwargs/version_std (str): the given version_std (can be None) + kwargs/same_branch (bool): force searching only in the same branch + kwargs/formated_output (bool): output a formated version string + kwargs/ignore_unknown_tags (bool): skip tags with not decoded versions (default to False) Returns: - the last version + the last version in MetaVersion object or string """ lastTag: str = cls.MetaVersion.raw cls.__versionReseted = False @@ -699,10 +657,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods @classmethod def doFormatVersion(cls, inputversion: MetaVersion, **kwargs: Unpack[TKwargs]) -> str: - """ - output a formated version string + """output a formated version string from a MetaVersion object Keyword Arguments: - output_format: output format to render ("Auto" or "PEP440" or "SemVer") + kwargs/output_format (str): output format to render ("Auto" or "PEP440" or "SemVer") Args: inputversion: version to be rendered Returns: @@ -713,15 +670,13 @@ class gitversionhelper: # pylint: disable=too-few-public-methods if VersionStd == "Auto": VersionStd = inputversion.version_std - OutputFormat = None revpattern = "" revcount = "" post_count = inputversion.post_count pre_count = inputversion.pre_count patch = inputversion.patch - if "output_format" in kwargs: - OutputFormat = kwargs["output_format"] + OutputFormat = kwargs.get("output_format") if OutputFormat is None: OutputFormat = "{major}.{minor}.{patch}{revpattern}{revcount}" -- 2.47.3