Compare commits

..

5 Commits

Author SHA1 Message Date
cclecle
df74016945 improve quality 2023-03-18 01:39:25 +00:00
cclecle
bce35f0a60 fix quality 2023-03-18 01:32:44 +00:00
cclecle
39e7d8236c update: update: quality column length check 120 -> 140 2023-03-18 01:23:33 +00:00
cclecle
6a1331d1bf improve quality 2023-03-18 01:22:32 +00:00
cclecle
96250682ec fix missing user/mail for git 2023-03-18 00:59:35 +00:00
3 changed files with 135 additions and 85 deletions

View File

@@ -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:

View File

@@ -23,12 +23,13 @@ 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
@@ -36,53 +37,69 @@ def _exec(cmd: str, root: str | os.PathLike | None = None) -> list[str]:
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
check if the repository is in dirty state
Return:
True if it is dirty
"""
return True if _exec("git status --short") else False
return bool(_exec("git status --short"))
class tag:
"""
@@ -90,14 +107,22 @@ 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]:
"""
@@ -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
@@ -147,7 +172,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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,23 +215,23 @@ 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:
"""
@@ -212,13 +242,13 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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:
"""
@@ -229,14 +259,14 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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:
@@ -248,7 +278,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
BumpType = self._getBumpType(**kwargs)
BumpDevStrategy=self._getBumpDevStrategy(**kwargs)
_v=copy(self)
if BumpType == "dev":
if BumpDevStrategy == "post":
if _v.pre_count > 0:
@@ -279,13 +309,18 @@ 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
Return:
formated version string
"""
return gitversionhelper.version.doFormatVersion(self,**kwargs)
@classmethod
def _getVersionStd(cls,**kwargs):
"""
@@ -302,29 +337,39 @@ 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]:
"""
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:
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.")
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:
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]:
def getLastVersion(cls,**kwargs) -> Union[str,MetaVersion]: # pylint: disable=R0914, R0912, R0915
"""
bump the last version from tags
get the last version from tags
Kwargs:
version_std(str): the given version_std (can be None)
same_branch(bool): force searching only in the same branch
@@ -333,11 +378,11 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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 +390,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 +402,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 +418,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,16 +436,16 @@ 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):
"""
@@ -411,21 +455,21 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
Return:
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 +488,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)

View File

@@ -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: