improve quality

This commit is contained in:
cclecle
2023-03-18 01:22:32 +00:00
parent 96250682ec
commit 6a1331d1bf

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,54 +37,71 @@ 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):
"""
general Module Exception
"""
pass
class gitversionhelper: # pylint: disable=too-few-public-methods
"""
Main gitversionhelper class
main gitversionhelper class
"""
class wrongArguments(gitversionhelperException):
"""
wrong argument generic exception
"""
pass
class unknownGITError(gitversionhelperException):
"""
unknown git error generic exception
"""
pass
class unknownGITFatalError(unknownGITError):
"""
unknown fatal git error generic exception
"""
pass
class repository:
"""
class containing methods focusing on repository
"""
class repositoryException(gitversionhelperException):
"""
generic repository exeption
"""
pass
class notAGitRepository(repositoryException):
"""
not a git repository exception
"""
pass
class repositoryDirty(repositoryException):
"""
dirty repository exception
"""
pass
@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:
"""
class containing methods focusing on tags
@@ -92,10 +110,19 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
__validGitTagSort=["","v:refname","-v:refname","taggerdate","committerdate","-taggerdate","-committerdate"]
class tagException(gitversionhelperException):
"""
generic tag exception
"""
pass
class tagNotFound(tagException):
"""
tag not found exception
"""
pass
class moreThanOneTag(tagException):
"""
more than one tag exception
"""
pass
@classmethod
@@ -110,7 +137,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
if sort not in cls.__validGitTagSort:
raise gitversionhelper.wrongArguments("sort option not in allowed list")
return _exec(f"git tag -l --sort={sort}")
@classmethod
def getLastTag(cls,**kwargs) -> Union[str,None]:
"""
@@ -129,7 +156,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
if len(res)==0:
raise cls.tagNotFound("no tag found in commit history")
elif len(res)!=1:
if len(res)!=1:
raise cls.moreThanOneTag("multiple tags on same commit is unsupported")
return res[0]
@@ -147,7 +174,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
@@ -170,8 +197,14 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
}
__versionReseted = False
class versionException(gitversionhelperException):
"""
generic version exception
"""
pass
class noValidVersion(versionException):
"""
no valid version found exception
"""
pass
class MetaVersion:
@@ -193,7 +226,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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"):
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
@@ -201,7 +234,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
self.pre_count = pre_count
self.post_count = post_count
self.raw = raw
@classmethod
def _getBumpDevStrategy(cls,**kwargs) -> str:
"""
@@ -236,7 +269,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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:
@@ -285,7 +318,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
def doFormatVersion(self,**kwargs):
return gitversionhelper.version.doFormatVersion(self,**kwargs)
@classmethod
def _getVersionStd(cls,**kwargs):
"""
@@ -302,18 +335,19 @@ 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.")
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)
@@ -322,7 +356,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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
Kwargs:
@@ -345,7 +379,6 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
except gitversionhelper.tag.tagNotFound:
logging.warning('tag not found, reseting versionning')
cls.__versionReseted = True
bFound = False
if VersionStd == "SemVer" or (bAutoVersionStd is True) :
@@ -358,14 +391,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 +407,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)
@@ -393,10 +426,10 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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)
@@ -415,7 +448,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
VersionStd = cls._getVersionStd(**kwargs)
if VersionStd=="Auto" :
VersionStd = inputversion.version_std
OutputFormat = None
revpattern=""
revcount=""
@@ -425,7 +458,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
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 +477,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)