Compare commits
7 Commits
0.0.1.post
...
0.0.1.post
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05093566d6 | ||
|
|
f3f3459ccf | ||
|
|
df74016945 | ||
|
|
bce35f0a60 | ||
|
|
39e7d8236c | ||
|
|
6a1331d1bf | ||
|
|
96250682ec |
@@ -61,7 +61,7 @@ class quality_check(helper_withresults_base):
|
||||
'--ignore=_version.py',
|
||||
'--reports=y',
|
||||
'--score=yes',
|
||||
'--max-line-length=120',
|
||||
'--max-line-length=140',
|
||||
'src.' + cls.pyproject['project']['name']], exit=False)
|
||||
|
||||
with open(cls.get_result_dir()/"report.json","w+", encoding='utf-8') as Outfile:
|
||||
|
||||
@@ -23,66 +23,83 @@ import logging
|
||||
|
||||
from packaging.version import VERSION_PATTERN as packaging_VERSION_PATTERN
|
||||
|
||||
if TYPE_CHECKING: # Only imports the below statements during type checking
|
||||
# Only imports the below statements during type checking
|
||||
if TYPE_CHECKING:
|
||||
from typing import Union
|
||||
|
||||
|
||||
def _exec(cmd: str, root: str | os.PathLike | None = None) -> 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
|
||||
Return:
|
||||
Returns:
|
||||
a list of command's return lines
|
||||
|
||||
"""
|
||||
try:
|
||||
#stdout = subprocess.check_output(cmd, shell=True, text=True, cwd=root)
|
||||
p = subprocess.run(cmd.split(), text=True, cwd=root, capture_output=True)
|
||||
if re.search("not a git repository",p.stderr):
|
||||
raise gitversionhelper.repository.notAGitRepository()
|
||||
if re.search("fatal:",p.stderr):
|
||||
raise gitversionhelper.unknownGITFatalError()
|
||||
if int(p.returncode) < 0:
|
||||
raise gitversionhelper.unknownGITError
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError(e.output)
|
||||
|
||||
p = subprocess.run(cmd.split(), text=True, cwd=root, capture_output=True, check=False)
|
||||
if re.search("not a git repository",p.stderr):
|
||||
raise gitversionhelper.repository.notAGitRepository()
|
||||
if re.search("fatal:",p.stderr):
|
||||
raise gitversionhelper.unknownGITFatalError()
|
||||
if int(p.returncode) < 0:
|
||||
raise gitversionhelper.unknownGITError
|
||||
|
||||
lines = p.stdout.splitlines()
|
||||
return [line.rstrip() for line in lines if line.rstrip()]
|
||||
|
||||
class gitversionhelperException(Exception):
|
||||
pass
|
||||
"""
|
||||
general Module Exception
|
||||
"""
|
||||
|
||||
class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
"""
|
||||
Main gitversionhelper class
|
||||
main gitversionhelper class
|
||||
"""
|
||||
class wrongArguments(gitversionhelperException):
|
||||
pass
|
||||
"""
|
||||
wrong argument generic exception
|
||||
"""
|
||||
|
||||
class unknownGITError(gitversionhelperException):
|
||||
pass
|
||||
"""
|
||||
unknown git error generic exception
|
||||
"""
|
||||
|
||||
class unknownGITFatalError(unknownGITError):
|
||||
pass
|
||||
"""
|
||||
unknown fatal git error generic exception
|
||||
"""
|
||||
|
||||
class repository:
|
||||
"""
|
||||
class containing methods focusing on repository
|
||||
"""
|
||||
class repositoryException(gitversionhelperException):
|
||||
pass
|
||||
"""
|
||||
generic repository exeption
|
||||
"""
|
||||
|
||||
class notAGitRepository(repositoryException):
|
||||
pass
|
||||
"""
|
||||
not a git repository exception
|
||||
"""
|
||||
|
||||
class repositoryDirty(repositoryException):
|
||||
pass
|
||||
"""
|
||||
dirty repository exception
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def isDirty(cls) -> bool:
|
||||
"""
|
||||
Check if the repository is in dirty state
|
||||
Return:
|
||||
check if the repository is in dirty state
|
||||
Returns:
|
||||
True if it is dirty
|
||||
"""
|
||||
return True if _exec("git status --short") else False
|
||||
return bool(_exec("git status --short"))
|
||||
|
||||
class tag:
|
||||
"""
|
||||
@@ -90,21 +107,29 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
"""
|
||||
__OptDict = {"same_branch": "same_branch"}
|
||||
__validGitTagSort=["","v:refname","-v:refname","taggerdate","committerdate","-taggerdate","-committerdate"]
|
||||
|
||||
|
||||
class tagException(gitversionhelperException):
|
||||
pass
|
||||
"""
|
||||
generic tag exception
|
||||
"""
|
||||
|
||||
class tagNotFound(tagException):
|
||||
pass
|
||||
"""
|
||||
tag not found exception
|
||||
"""
|
||||
|
||||
class moreThanOneTag(tagException):
|
||||
pass
|
||||
|
||||
"""
|
||||
more than one tag exception
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def getTags(cls,sort:str = "version:refname") -> list[str]:
|
||||
"""
|
||||
retrieve all tags from a repository
|
||||
Args:
|
||||
sort: sorting constraints (git format)
|
||||
Return:
|
||||
Returns:
|
||||
the tags list
|
||||
"""
|
||||
if sort not in cls.__validGitTagSort:
|
||||
@@ -117,7 +142,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
retrieve the last tag from a repository
|
||||
Kwargs:
|
||||
same_branch(bool): force searching only in the same branch
|
||||
Return:
|
||||
Returns:
|
||||
the tag
|
||||
"""
|
||||
if ((cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True)):
|
||||
@@ -126,11 +151,11 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
res = _exec("git rev-list --tags --max-count=1")
|
||||
if len(res)==1:
|
||||
res = _exec(f"git describe --tags {res[0]}")
|
||||
|
||||
if len(res)==0:
|
||||
|
||||
if len(res)==0:
|
||||
raise cls.tagNotFound("no tag found in commit history")
|
||||
elif len(res)!=1:
|
||||
raise cls.moreThanOneTag("multiple tags on same commit is unsupported")
|
||||
if len(res)!=1:
|
||||
raise cls.moreThanOneTag("multiple tags on same commit is unsupported")
|
||||
return res[0]
|
||||
|
||||
@classmethod
|
||||
@@ -141,13 +166,13 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
tag: reference tag, if None the most recent one will be used
|
||||
Kwargs:
|
||||
same_branch(bool): force searching only in the same branch
|
||||
Return:
|
||||
Returns:
|
||||
the tag
|
||||
"""
|
||||
if tag is None:
|
||||
tag = cls.getLastTag(**kwargs)
|
||||
return int(_exec(f"git rev-list {tag}..HEAD --count")[0])
|
||||
|
||||
|
||||
class version:
|
||||
"""
|
||||
class containing methods focusing on versions
|
||||
@@ -162,7 +187,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
r"(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
|
||||
"regex_preversion_num": r"(?:\.)(?P<num>(?:\d+(?!\w))+)",
|
||||
"regex_build_num" : r"(?:\.)(?P<num>(?:\d+(?!\w))+)"
|
||||
|
||||
|
||||
},
|
||||
"PEP440" : { "regex" : packaging_VERSION_PATTERN,
|
||||
"Auto" : None
|
||||
@@ -170,10 +195,15 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
}
|
||||
__versionReseted = False
|
||||
class versionException(gitversionhelperException):
|
||||
pass
|
||||
"""
|
||||
generic version exception
|
||||
"""
|
||||
|
||||
class noValidVersion(versionException):
|
||||
pass
|
||||
|
||||
"""
|
||||
no valid version found exception
|
||||
"""
|
||||
|
||||
class MetaVersion:
|
||||
"""
|
||||
generic version object
|
||||
@@ -185,70 +215,70 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
DefaultBumpDevStrategy = "post"
|
||||
BumpDevStrategys = ["post","pre-patch","pre-minor","pre-major"]
|
||||
version_std = "None"
|
||||
|
||||
|
||||
major: int = 0
|
||||
minor: int = 1
|
||||
patch: int = 0
|
||||
pre_count:int = 0
|
||||
post_count:int = 0
|
||||
raw:str = "0.1.0"
|
||||
|
||||
def __init__(self,version_std,major=0,minor=1,patch=0,pre_count=0,post_count=0,raw="0.1.0"):
|
||||
self.version_std = version_std
|
||||
|
||||
def __init__(self,version_std,major=0,minor=1,patch=0,pre_count=0,post_count=0,raw="0.1.0"): #pylint: disable=R0913
|
||||
self.version_std = version_std
|
||||
self.major = major
|
||||
self.minor = minor
|
||||
self.patch = patch
|
||||
self.pre_count = pre_count
|
||||
self.post_count = post_count
|
||||
self.raw = raw
|
||||
|
||||
|
||||
@classmethod
|
||||
def _getBumpDevStrategy(cls,**kwargs) -> str:
|
||||
"""
|
||||
get selected bump_dev_strategy
|
||||
Kwargs:
|
||||
bump_dev_strategy(str): the given bump_dev_strategy (can be None)
|
||||
Return:
|
||||
Returns:
|
||||
Kwargs given bump_dev_strategy or the default one.
|
||||
"""
|
||||
BumpDevStrategy = cls.DefaultBumpDevStrategy
|
||||
if (cls.__OptDict["bump_dev_strategy"] in kwargs):
|
||||
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"]]
|
||||
else:
|
||||
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['bump_type']} requested")
|
||||
return BumpDevStrategy
|
||||
|
||||
|
||||
@classmethod
|
||||
def _getBumpType(cls,**kwargs) -> str:
|
||||
"""
|
||||
get selected bump_type
|
||||
Kwargs:
|
||||
bump_type(str): the given bump_type (can be None)
|
||||
Return:
|
||||
Returns:
|
||||
Kwargs given bump_type or the default one.
|
||||
"""
|
||||
BumpType = cls.DefaultBumpType
|
||||
if (cls.__OptDict["bump_type"] in kwargs):
|
||||
if cls.__OptDict["bump_type"] in kwargs:
|
||||
if kwargs[cls.__OptDict["bump_type"]] in cls.BumpTypes:
|
||||
BumpType = kwargs[cls.__OptDict["bump_type"]]
|
||||
else:
|
||||
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['bump_type']} requested")
|
||||
return BumpType
|
||||
|
||||
def bump(self,amount:int=1,**kwargs):
|
||||
|
||||
def bump(self,amount:int=1,**kwargs): # pylint: disable=R0912
|
||||
"""
|
||||
bump the version to the next one
|
||||
Kwargs:
|
||||
bump_type(str): the given bump_type (can be None)
|
||||
bump_dev_strategy(str): the given bump_dev_strategy (can be None)
|
||||
Return:
|
||||
Returns:
|
||||
the bumped version
|
||||
"""
|
||||
BumpType = self._getBumpType(**kwargs)
|
||||
BumpDevStrategy=self._getBumpDevStrategy(**kwargs)
|
||||
_v=copy(self)
|
||||
|
||||
|
||||
if BumpType == "dev":
|
||||
if BumpDevStrategy == "post":
|
||||
if _v.pre_count > 0:
|
||||
@@ -279,20 +309,25 @@ 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)
|
||||
return _v
|
||||
|
||||
|
||||
def doFormatVersion(self,**kwargs):
|
||||
"""
|
||||
output a formated version string
|
||||
Returns:
|
||||
formated version string
|
||||
"""
|
||||
return gitversionhelper.version.doFormatVersion(self,**kwargs)
|
||||
|
||||
|
||||
@classmethod
|
||||
def _getVersionStd(cls,**kwargs):
|
||||
"""
|
||||
get selected version_std
|
||||
Kwargs:
|
||||
version_std(str): the given version_std (can be None)
|
||||
Return:
|
||||
Returns:
|
||||
Kwargs given version_std or the default one.
|
||||
"""
|
||||
VersionStd = cls.DefaultInputFormat
|
||||
@@ -302,42 +337,53 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
else:
|
||||
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['version_std']} requested")
|
||||
return VersionStd
|
||||
|
||||
|
||||
@classmethod
|
||||
def getCurrentVersion(cls,**kwargs) -> Union[str,MetaVersion]:
|
||||
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)
|
||||
|
||||
if cls.__versionReseted == False:
|
||||
amount = gitversionhelper.tag.getDistanceFromTag(_v.raw,**kwargs)
|
||||
_v = _v.bump(amount,**kwargs)
|
||||
|
||||
if ((cls.__OptDict["formated_output"] in kwargs) and (kwargs[cls.__OptDict["formated_output"]] is True)):
|
||||
return _v.doFormatVersion(**kwargs)
|
||||
return _v
|
||||
|
||||
@classmethod
|
||||
def getLastVersion(cls,**kwargs) -> Union[str,MetaVersion]:
|
||||
"""
|
||||
bump the last version from tags
|
||||
get the current version or bump depending of repository state
|
||||
Kwargs:
|
||||
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
|
||||
Return:
|
||||
Returns:
|
||||
the last version
|
||||
"""
|
||||
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)
|
||||
|
||||
if not cls.__versionReseted:
|
||||
amount = gitversionhelper.tag.getDistanceFromTag(_v.raw,**kwargs)
|
||||
_v = _v.bump(amount,**kwargs)
|
||||
|
||||
if ((cls.__OptDict["formated_output"] in kwargs) and (kwargs[cls.__OptDict["formated_output"]] is True)):
|
||||
return _v.doFormatVersion(**kwargs)
|
||||
return _v
|
||||
|
||||
@classmethod
|
||||
def getLastVersion(cls,**kwargs) -> Union[str,MetaVersion]: # pylint: disable=R0914, R0912, R0915
|
||||
"""
|
||||
get the last version from tags
|
||||
Parameters:
|
||||
**kwargs:
|
||||
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
|
||||
Returns:
|
||||
the last version
|
||||
"""
|
||||
VersionStd = cls._getVersionStd(**kwargs)
|
||||
|
||||
bAutoVersionStd = False
|
||||
|
||||
bAutoVersionStd = False
|
||||
if VersionStd == "Auto":
|
||||
bAutoVersionStd = True
|
||||
|
||||
bAutoVersionStd = True
|
||||
|
||||
lastTag=cls.MetaVersion.raw
|
||||
cls.__versionReseted = False
|
||||
try:
|
||||
@@ -345,9 +391,8 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
except gitversionhelper.tag.tagNotFound:
|
||||
logging.warning('tag not found, reseting versionning')
|
||||
cls.__versionReseted = True
|
||||
|
||||
|
||||
bFound = False
|
||||
|
||||
bFound = False
|
||||
if VersionStd == "SemVer" or (bAutoVersionStd is True) :
|
||||
_r=re.compile(r"^\s*" + cls.VersionStds["SemVer"]["regex"] + r"\s*$", re.VERBOSE | \
|
||||
re.IGNORECASE)
|
||||
@@ -358,14 +403,14 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
major, minor, patch = int(_m.group("major")),\
|
||||
int(_m.group("minor")),\
|
||||
int(_m.group("patch"))
|
||||
|
||||
|
||||
pre_count = 0
|
||||
if _pre := _m.group("prerelease"):
|
||||
if (_match := re.search (cls.VersionStds["SemVer"]["regex_preversion_num"],_pre)) is not None:
|
||||
pre_count = int(_match.group("num"))
|
||||
else:
|
||||
pre_count = 1
|
||||
|
||||
|
||||
post_count = 0
|
||||
if _post := _m.group("buildmetadata"):
|
||||
if (_match := re.search (cls.VersionStds["SemVer"]["regex_build_num"],_post)) is not None:
|
||||
@@ -374,7 +419,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
post_count = 1
|
||||
bFound = True
|
||||
VersionStd = "SemVer"
|
||||
|
||||
|
||||
if VersionStd == "PEP440" or ( (bAutoVersionStd is True) and (bFound is not True)):
|
||||
_r=re.compile(r"^\s*" + cls.VersionStds["PEP440"]["regex"] + r"\s*$", re.VERBOSE | \
|
||||
re.IGNORECASE)
|
||||
@@ -392,40 +437,40 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
post_count = int(_m.group("post_n2")) if _m.group("post_n2") else 0
|
||||
bFound = True
|
||||
VersionStd = "PEP440"
|
||||
|
||||
if bFound is not True:
|
||||
|
||||
if not bFound :
|
||||
raise gitversionhelper.version.noValidVersion("no valid version found in tags")
|
||||
|
||||
_v = cls.MetaVersion(VersionStd,major, minor, patch, pre_count, post_count, lastTag)
|
||||
|
||||
|
||||
_v = cls.MetaVersion(VersionStd, major, minor, patch, pre_count, post_count, lastTag)
|
||||
|
||||
if ((cls.__OptDict["formated_output"] in kwargs) and (kwargs[cls.__OptDict["formated_output"]] is True)):
|
||||
return _v.doFormatVersion(**kwargs)
|
||||
return _v
|
||||
|
||||
|
||||
@classmethod
|
||||
def doFormatVersion(cls,inputversion:MetaVersion,**kwargs):
|
||||
"""
|
||||
output a formated version string
|
||||
Args:
|
||||
inputversion: version to be rendered
|
||||
Return:
|
||||
Returns:
|
||||
formated version string
|
||||
"""
|
||||
|
||||
|
||||
VersionStd = cls._getVersionStd(**kwargs)
|
||||
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 (cls.__OptDict["output_format"] in kwargs):
|
||||
|
||||
if cls.__OptDict["output_format"] in kwargs:
|
||||
OutputFormat=kwargs[cls.__OptDict["output_format"]]
|
||||
|
||||
|
||||
if OutputFormat is None:
|
||||
OutputFormat = "{major}.{minor}.{patch}{revpattern}{revcount}"
|
||||
if post_count > 0 and pre_count > 0:
|
||||
@@ -444,4 +489,8 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||
elif pre_count > 0:
|
||||
revpattern="-pre"
|
||||
revcount=f".{pre_count}"
|
||||
return OutputFormat.format(major=inputversion.major,minor=inputversion.minor,patch=patch,revpattern=revpattern,revcount=revcount)
|
||||
return OutputFormat.format( major=inputversion.major, \
|
||||
minor=inputversion.minor, \
|
||||
patch=patch, \
|
||||
revpattern=revpattern, \
|
||||
revcount=revcount)
|
||||
|
||||
@@ -28,6 +28,8 @@ class Test_gitversionhelper(unittest.TestCase):
|
||||
self.TmpWorkingDirPath=pathlib.Path(self.TmpWorkingDir.name)
|
||||
os.chdir(self.TmpWorkingDirPath)
|
||||
os.system("git init")
|
||||
os.system('git config --local user.name "john doe"')
|
||||
os.system('git config --local user.email "john@doe.org"')
|
||||
|
||||
def _test_version_readback(self,tag:str,**kwargs):
|
||||
with open("demofile.txt", "w+t") as tmpFile:
|
||||
|
||||
Reference in New Issue
Block a user