Compare commits
12 Commits
1.0.3.post
...
1.0.6.post
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fc9032cd0 | ||
|
|
72e43e7c1c | ||
|
|
6d7411693e | ||
|
|
1338ef5f8e | ||
|
|
da411f51e3 | ||
|
|
e9559e97fb | ||
|
|
158b85e29c | ||
|
|
d4545f999b | ||
|
|
21fc9e7c52 | ||
|
|
13a584c7d9 | ||
|
|
6dfe0682d7 | ||
|
|
d15b495f0a |
48
Jenkinsfile
vendored
48
Jenkinsfile
vendored
@@ -21,10 +21,12 @@ def _bDraft = false
|
|||||||
// release content / changelog management
|
// release content / changelog management
|
||||||
def _bAutoChangelog = true //Not supported yet
|
def _bAutoChangelog = true //Not supported yet
|
||||||
def _ReleaseContent_Title = "_CI/CD Automatic Release_"
|
def _ReleaseContent_Title = "_CI/CD Automatic Release_"
|
||||||
|
def bPushMasterOnPypi = true
|
||||||
// full rebuild toogle
|
// full rebuild toogle
|
||||||
def _bFullRebuilt = true
|
def _bFullRebuilt = true
|
||||||
def _MkDocsWebURL = "dabauto--mkdocs-web.dmz.chacha.home/mkdocs-web/"
|
def _MkDocsWebURL = "dabauto--mkdocs-web.dmz.chacha.home/mkdocs-web/"
|
||||||
def _MkDocsWebCredentials = "2c5b684e-3787-4b37-8aca-b3dd4a383fe2"
|
def _MkDocsWebCredentials = "2c5b684e-3787-4b37-8aca-b3dd4a383fe2"
|
||||||
|
def _PypiCredentials = "Pypi"
|
||||||
|
|
||||||
// commands Helper: /!\ Made for GITEA /!\
|
// commands Helper: /!\ Made for GITEA /!\
|
||||||
String determineRepoUserName() {
|
String determineRepoUserName() {
|
||||||
@@ -131,11 +133,21 @@ pipeline {
|
|||||||
|
|
||||||
sh(". ~/BUILD_ENV/bin/activate && pip install --upgrade setuptools build pip copier jinja2-slug toml")
|
sh(". ~/BUILD_ENV/bin/activate && pip install --upgrade setuptools build pip copier jinja2-slug toml")
|
||||||
|
|
||||||
sh(". ~/TOOLS_ENV/bin/activate && pip install simple_rest_client requests")
|
sh(". ~/TOOLS_ENV/bin/activate && pip install simple_rest_client requests twine")
|
||||||
sh(". ~/TOOLS_ENV/bin/activate && pip install git+https://chacha.ddns.net/gitea/chacha/pygitversionhelper.git@master")
|
|
||||||
|
|
||||||
|
script {
|
||||||
|
if(_PROJECT_NAME!="pygitversionhelper") {
|
||||||
|
sh(". ~/TOOLS_ENV/bin/activate && pip install git+https://chacha.ddns.net/gitea/chacha/pygitversionhelper.git@master")
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
//TODO: need to install pygitversionhelper deps from a better way...
|
||||||
|
sh(". ~/TOOLS_ENV/bin/activate && pip install packaging")
|
||||||
|
}
|
||||||
|
}
|
||||||
sh("git config --global user.email $_MaintainerEmail")
|
sh("git config --global user.email $_MaintainerEmail")
|
||||||
sh("git config --global user.name $_MaintainerName")
|
sh("git config --global user.name $_MaintainerName")
|
||||||
|
sh("git config --global init.defaultBranch master")
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -157,13 +169,18 @@ pipeline {
|
|||||||
|
|
||||||
if(_GIT_BRANCH=="master") {
|
if(_GIT_BRANCH=="master") {
|
||||||
if(sh(returnStdout: true, script: "git tag --points-at HEAD").trim().isEmpty()) {
|
if(sh(returnStdout: true, script: "git tag --points-at HEAD").trim().isEmpty()) {
|
||||||
|
|
||||||
BUMPED_VERSION = sh(script: """#!/bin/sh -
|
BUMPED_VERSION = sh(script: """#!/bin/sh -
|
||||||
|. ~/TOOLS_ENV/bin/activate
|
|. ~/TOOLS_ENV/bin/activate
|
||||||
|exec python - << '__EOWRAPPER__'
|
|exec python - << '__EOWRAPPER__'
|
||||||
|
|
|
|
||||||
|from pygitversionhelper import gitversionhelper
|
|
||||||
|import re
|
|import re
|
||||||
|
|
|
|
||||||
|
|try:
|
||||||
|
| from pygitversionhelper import gitversionhelper
|
||||||
|
|except ImportError:
|
||||||
|
| from src.pygitversionhelper import gitversionhelper
|
||||||
|
|
|
||||||
|lastcommit=gitversionhelper.commit.getLast(same_branch=True)
|
|lastcommit=gitversionhelper.commit.getLast(same_branch=True)
|
||||||
|msg=gitversionhelper.commit.getMessage(lastcommit)
|
|msg=gitversionhelper.commit.getMessage(lastcommit)
|
||||||
|
|
|
|
||||||
@@ -173,6 +190,7 @@ pipeline {
|
|||||||
|__EOWRAPPER__
|
|__EOWRAPPER__
|
||||||
""".stripMargin(),
|
""".stripMargin(),
|
||||||
returnStdout: true).trim()
|
returnStdout: true).trim()
|
||||||
|
|
||||||
if(BUMPED_VERSION.isEmpty()) {
|
if(BUMPED_VERSION.isEmpty()) {
|
||||||
echo "master push/merge must have an explicit tag release number, stopping pipeline"
|
echo "master push/merge must have an explicit tag release number, stopping pipeline"
|
||||||
currentBuild.getRawBuild().getExecutor().doStop()
|
currentBuild.getRawBuild().getExecutor().doStop()
|
||||||
@@ -190,7 +208,10 @@ pipeline {
|
|||||||
|. ~/TOOLS_ENV/bin/activate
|
|. ~/TOOLS_ENV/bin/activate
|
||||||
|exec python - << '__EOWRAPPER__'
|
|exec python - << '__EOWRAPPER__'
|
||||||
|
|
|
|
||||||
|from pygitversionhelper import gitversionhelper
|
|try:
|
||||||
|
| from pygitversionhelper import gitversionhelper
|
||||||
|
|except ImportError:
|
||||||
|
| from src.pygitversionhelper import gitversionhelper
|
||||||
|
|
|
|
||||||
|print(gitversionhelper.tag.getLastTag(same_branch=True),end ="")
|
|print(gitversionhelper.tag.getLastTag(same_branch=True),end ="")
|
||||||
|
|
|
|
||||||
@@ -204,7 +225,10 @@ pipeline {
|
|||||||
|. ~/TOOLS_ENV/bin/activate
|
|. ~/TOOLS_ENV/bin/activate
|
||||||
|exec python - << '__EOWRAPPER__'
|
|exec python - << '__EOWRAPPER__'
|
||||||
|
|
|
|
||||||
|from pygitversionhelper import gitversionhelper
|
|try:
|
||||||
|
| from pygitversionhelper import gitversionhelper
|
||||||
|
|except ImportError:
|
||||||
|
| from src.pygitversionhelper import gitversionhelper
|
||||||
|
|
|
|
||||||
|print(gitversionhelper.version.getCurrentVersion(formated_output=True,version_std="PEP440",bump_type="dev",bump_dev_strategy="post"),end ="")
|
|print(gitversionhelper.version.getCurrentVersion(formated_output=True,version_std="PEP440",bump_type="dev",bump_dev_strategy="post"),end ="")
|
||||||
|
|
|
|
||||||
@@ -447,7 +471,11 @@ pipeline {
|
|||||||
|
|
|
|
||||||
|from simple_rest_client.api import API
|
|from simple_rest_client.api import API
|
||||||
|from simple_rest_client.resource import Resource
|
|from simple_rest_client.resource import Resource
|
||||||
|from pygitversionhelper import gitversionhelper
|
|
|
||||||
|
|try:
|
||||||
|
| from pygitversionhelper import gitversionhelper
|
||||||
|
|except ImportError:
|
||||||
|
| from src.pygitversionhelper import gitversionhelper
|
||||||
|
|
|
|
||||||
|from urllib.parse import urljoin
|
|from urllib.parse import urljoin
|
||||||
|
|
|
|
||||||
@@ -529,6 +557,14 @@ pipeline {
|
|||||||
|__EOWRAPPER__
|
|__EOWRAPPER__
|
||||||
""".stripMargin())
|
""".stripMargin())
|
||||||
}
|
}
|
||||||
|
if((_GIT_BRANCH=="master") && (bPushMasterOnPypi)) {
|
||||||
|
withCredentials([usernamePassword( credentialsId: _PypiCredentials, passwordVariable: 'PYPI_PASSWORD', usernameVariable: 'PYPI_USERNAME')]) {
|
||||||
|
sh(script: """#!/bin/sh -
|
||||||
|
|. ~/TOOLS_ENV/bin/activate
|
||||||
|
|exec twine upload -r ${PY_PROJECT_NAME} dist/* -u ${PYPI_USERNAME} -p ${PYPI_PASSWORD} --non-interactive --disable-progress-bar
|
||||||
|
""".stripMargin())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,20 @@
|
|||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
From master repository:
|
From pypi repository (prefered):
|
||||||
|
|
||||||
|
python -m pip install pygitversionhelper
|
||||||
|
|
||||||
|
From downloaded .whl file:
|
||||||
|
|
||||||
|
python -m pip install pygitversionhelper-<VERSION>-py3-none-any.whl
|
||||||
|
|
||||||
|
From master git repository:
|
||||||
|
|
||||||
python -m pip install git+https://chacha.ddns.net/gitea/chacha/pygitversionhelper.git@master
|
python -m pip install git+https://chacha.ddns.net/gitea/chacha/pygitversionhelper.git@master
|
||||||
|
|
||||||
From local .whl file:
|
|
||||||
|
|
||||||
python -m pip install pygitversionhelper-<VERSION>-py3-none-any.whl
|
|
||||||
|
|
||||||
From public repository:
|
|
||||||
|
|
||||||
TBD
|
|
||||||
|
|
||||||
## Import in your project
|
## Import in your project
|
||||||
|
|
||||||
|
|||||||
@@ -4,4 +4,4 @@
|
|||||||
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
|
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
|
||||||
#
|
#
|
||||||
# You should have received a copy of the license along with this
|
# You should have received a copy of the license along with this
|
||||||
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
|
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
|
||||||
|
|||||||
@@ -16,89 +16,132 @@ import os
|
|||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
if __package__=="helpers":
|
if __package__ == "helpers":
|
||||||
# when calling the module from: > python -m helpers
|
# when calling the module from: > python -m helpers
|
||||||
from .types_check import types_check
|
from .types_check import types_check
|
||||||
from .quality_check import quality_check
|
from .quality_check import quality_check
|
||||||
from .unit_test import unit_test
|
from .unit_test import unit_test
|
||||||
from .doc_gen import doc_gen
|
from .doc_gen import doc_gen
|
||||||
from .changelog_gen import changelog_gen
|
from .changelog_gen import changelog_gen
|
||||||
else:
|
else:
|
||||||
# when calling the __main__.py file (from IDE)
|
# when calling the __main__.py file (from IDE)
|
||||||
from helpers.types_check import types_check
|
from helpers.types_check import types_check
|
||||||
from helpers.quality_check import quality_check
|
from helpers.quality_check import quality_check
|
||||||
from helpers.unit_test import unit_test
|
from helpers.unit_test import unit_test
|
||||||
from helpers.doc_gen import doc_gen
|
from helpers.doc_gen import doc_gen
|
||||||
from helpers.changelog_gen import changelog_gen
|
from helpers.changelog_gen import changelog_gen
|
||||||
|
|
||||||
logging.getLogger().setLevel(logging.INFO)
|
logging.getLogger().setLevel(logging.INFO)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
project_rootdir_path=Path(__file__).parent.parent.absolute()
|
project_rootdir_path = Path(__file__).parent.parent.absolute()
|
||||||
|
|
||||||
with open(project_rootdir_path / "pyproject.toml", mode="rb") as fp:
|
with open(project_rootdir_path / "pyproject.toml", mode="rb") as fp:
|
||||||
pyproject = tomli.load(fp)
|
pyproject = tomli.load(fp)
|
||||||
|
|
||||||
parser = argparse.ArgumentParser( prog = 'continuous-integration-helper',
|
|
||||||
description = 'A tiny set of scripts to help continous integration on python')
|
|
||||||
|
|
||||||
parser.add_argument('-tc', '--type-check', dest='typecheck', action='store_true', help='enable static typing check')
|
|
||||||
|
|
||||||
parser.add_argument('-ut', '--unit-test', dest='unittest', action='store_true', help='enable unit-test')
|
|
||||||
parser.add_argument('-cc', '--coverage-check', dest='coveragecheck', action='store_true', help='enable unit-test coverage check (requires unit-test)')
|
|
||||||
|
|
||||||
parser.add_argument('-qc', '--quality-check', dest='qualitycheck', action='store_true', help='enable code quality check')
|
parser = argparse.ArgumentParser(
|
||||||
|
prog="continuous-integration-helper",
|
||||||
parser.add_argument('-dg', '--doc-gen', dest='docgen', action='store_true', help='enable documentation generation using MkDoc')
|
description="A tiny set of scripts to help continous integration on python",
|
||||||
parser.add_argument('-pdf', '--doc-gen-pdf', dest='docgenpdf', action='store_true', help='enable pdf documentation export (requires doc-gen)')
|
)
|
||||||
|
|
||||||
parser.add_argument('-clg', '--changelog-gen', dest='changeloggen', action='store_true', help='enable changelog generation')
|
parser.add_argument(
|
||||||
|
"-tc",
|
||||||
|
"--type-check",
|
||||||
|
dest="typecheck",
|
||||||
|
action="store_true",
|
||||||
|
help="enable static typing check",
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-ut",
|
||||||
|
"--unit-test",
|
||||||
|
dest="unittest",
|
||||||
|
action="store_true",
|
||||||
|
help="enable unit-test",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-cc",
|
||||||
|
"--coverage-check",
|
||||||
|
dest="coveragecheck",
|
||||||
|
action="store_true",
|
||||||
|
help="enable unit-test coverage check (requires unit-test)",
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-qc",
|
||||||
|
"--quality-check",
|
||||||
|
dest="qualitycheck",
|
||||||
|
action="store_true",
|
||||||
|
help="enable code quality check",
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-dg",
|
||||||
|
"--doc-gen",
|
||||||
|
dest="docgen",
|
||||||
|
action="store_true",
|
||||||
|
help="enable documentation generation using MkDoc",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-pdf",
|
||||||
|
"--doc-gen-pdf",
|
||||||
|
dest="docgenpdf",
|
||||||
|
action="store_true",
|
||||||
|
help="enable pdf documentation export (requires doc-gen)",
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-clg",
|
||||||
|
"--changelog-gen",
|
||||||
|
dest="changeloggen",
|
||||||
|
action="store_true",
|
||||||
|
help="enable changelog generation",
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
##################################
|
##################################
|
||||||
# Dev / Debug forced toogles
|
# Dev / Debug forced toogles
|
||||||
#
|
#
|
||||||
#--------------------------------
|
# --------------------------------
|
||||||
#
|
#
|
||||||
#args.typecheck = True
|
# args.typecheck = True
|
||||||
#args.qualitycheck = True
|
# args.qualitycheck = True
|
||||||
#args.unittest = True
|
# args.unittest = True
|
||||||
#args.coveragecheck = True
|
# args.coveragecheck = True
|
||||||
#args.docgen = True
|
# args.docgen = True
|
||||||
#args.docgenpdf = True
|
# args.docgenpdf = True
|
||||||
#args.changeloggen = True
|
# args.changeloggen = True
|
||||||
|
|
||||||
helpers = []
|
helpers = []
|
||||||
if args.typecheck == True:
|
if args.typecheck == True:
|
||||||
helpers.append(types_check)
|
helpers.append(types_check)
|
||||||
|
|
||||||
if args.unittest == True:
|
if args.unittest == True:
|
||||||
helpers.append(unit_test)
|
helpers.append(unit_test)
|
||||||
|
|
||||||
if args.coveragecheck == True:
|
if args.coveragecheck == True:
|
||||||
if args.unittest == True:
|
if args.unittest == True:
|
||||||
unit_test.enable_coverage_check = True
|
unit_test.enable_coverage_check = True
|
||||||
else:
|
else:
|
||||||
raise RuntimeError("unit-test is required to enable coverage-check")
|
raise RuntimeError("unit-test is required to enable coverage-check")
|
||||||
|
|
||||||
if args.qualitycheck == True:
|
if args.qualitycheck == True:
|
||||||
helpers.append(quality_check)
|
helpers.append(quality_check)
|
||||||
|
|
||||||
if args.docgen == True:
|
if args.docgen == True:
|
||||||
helpers.append(doc_gen)
|
helpers.append(doc_gen)
|
||||||
|
|
||||||
if args.docgenpdf==True:
|
if args.docgenpdf == True:
|
||||||
if args.docgen == True:
|
if args.docgen == True:
|
||||||
doc_gen.enable_gen_pdf = True
|
doc_gen.enable_gen_pdf = True
|
||||||
else:
|
else:
|
||||||
raise RuntimeError("doc-gen is required to enable doc-gen-pdf")
|
raise RuntimeError("doc-gen is required to enable doc-gen-pdf")
|
||||||
|
|
||||||
if args.changeloggen == True:
|
if args.changeloggen == True:
|
||||||
helpers.append(changelog_gen)
|
helpers.append(changelog_gen)
|
||||||
|
|
||||||
for helper in helpers:
|
for helper in helpers:
|
||||||
helper.set_context(project_rootdir_path,pyproject)
|
helper.set_context(project_rootdir_path, pyproject)
|
||||||
helper.reset_result_dir()
|
helper.reset_result_dir()
|
||||||
helper.do_job()
|
helper.do_job()
|
||||||
|
|
||||||
|
|||||||
@@ -9,16 +9,15 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
#from pathlib import Path
|
# from pathlib import Path
|
||||||
#import os
|
# import os
|
||||||
#import datetime
|
# import datetime
|
||||||
|
|
||||||
|
|
||||||
from .helper_base import helper_base
|
from .helper_base import helper_base
|
||||||
|
|
||||||
|
|
||||||
class changelog_gen(helper_base):
|
class changelog_gen(helper_base):
|
||||||
|
@classmethod
|
||||||
@classmethod
|
def do_job(cls):
|
||||||
def do_job(cls):
|
pass
|
||||||
pass
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ from pathlib import Path
|
|||||||
from distutils.dir_util import copy_tree
|
from distutils.dir_util import copy_tree
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from yaml import CLoader as Loader, CDumper as Dumper
|
from yaml import CLoader as Loader, CDumper as Dumper
|
||||||
except ImportError:
|
except ImportError:
|
||||||
@@ -24,35 +25,44 @@ except ImportError:
|
|||||||
|
|
||||||
from .helper_base import helper_withresults_base
|
from .helper_base import helper_withresults_base
|
||||||
|
|
||||||
class doc_gen(helper_withresults_base):
|
|
||||||
|
class doc_gen(helper_withresults_base):
|
||||||
enable_gen_pdf: bool = False
|
enable_gen_pdf: bool = False
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def do_job(cls):
|
def do_job(cls):
|
||||||
print(cls.project_rootdir_path)
|
print(cls.project_rootdir_path)
|
||||||
print()
|
print()
|
||||||
|
|
||||||
# create doc root dir
|
# create doc root dir
|
||||||
doc_path = cls.project_rootdir_path/"docs"
|
doc_path = cls.project_rootdir_path / "docs"
|
||||||
cls._reset_dir(doc_path)
|
cls._reset_dir(doc_path)
|
||||||
|
|
||||||
site_path = cls.get_result_dir()/"site"
|
site_path = cls.get_result_dir() / "site"
|
||||||
cls._reset_dir(site_path)
|
cls._reset_dir(site_path)
|
||||||
|
|
||||||
# copy files from main project dir
|
# copy files from main project dir
|
||||||
shutil.copyfile(str(cls.project_rootdir_path/"README.md"),str(doc_path/"README.md"))
|
shutil.copyfile(
|
||||||
shutil.copyfile(str(cls.project_rootdir_path/"LICENSE.md"),str(doc_path/"LICENSE.md"))
|
str(cls.project_rootdir_path / "README.md"), str(doc_path / "README.md")
|
||||||
|
)
|
||||||
|
shutil.copyfile(
|
||||||
|
str(cls.project_rootdir_path / "LICENSE.md"), str(doc_path / "LICENSE.md")
|
||||||
|
)
|
||||||
|
|
||||||
# copy files from static-doc dir
|
# copy files from static-doc dir
|
||||||
copy_tree(str(cls.project_rootdir_path/"docs-static"),str(doc_path))
|
copy_tree(str(cls.project_rootdir_path / "docs-static"), str(doc_path))
|
||||||
|
|
||||||
# generating API doc + nav from python docstrings
|
# generating API doc + nav from python docstrings
|
||||||
reference_path = doc_path / "reference"
|
reference_path = doc_path / "reference"
|
||||||
cls._reset_dir(reference_path)
|
cls._reset_dir(reference_path)
|
||||||
|
|
||||||
for path in sorted((cls.project_rootdir_path / "src").rglob("*.py")):
|
for path in sorted((cls.project_rootdir_path / "src").rglob("*.py")):
|
||||||
module_path = path.relative_to(cls.project_rootdir_path/ "src").with_suffix("")
|
module_path = path.relative_to(
|
||||||
doc_path = path.relative_to(cls.project_rootdir_path/ "src").with_suffix(".md")
|
cls.project_rootdir_path / "src"
|
||||||
|
).with_suffix("")
|
||||||
|
doc_path = path.relative_to(cls.project_rootdir_path / "src").with_suffix(
|
||||||
|
".md"
|
||||||
|
)
|
||||||
full_doc_path = Path(reference_path, doc_path)
|
full_doc_path = Path(reference_path, doc_path)
|
||||||
|
|
||||||
parts = list(module_path.parts)
|
parts = list(module_path.parts)
|
||||||
@@ -61,43 +71,60 @@ class doc_gen(helper_withresults_base):
|
|||||||
parts = parts[:-1]
|
parts = parts[:-1]
|
||||||
elif parts[-1] == "__main__":
|
elif parts[-1] == "__main__":
|
||||||
continue
|
continue
|
||||||
|
|
||||||
cls._reset_dir(os.path.dirname(full_doc_path))
|
cls._reset_dir(os.path.dirname(full_doc_path))
|
||||||
with open(full_doc_path, "w+") as fd:
|
with open(full_doc_path, "w+") as fd:
|
||||||
identifier = "src."+".".join(parts)
|
identifier = "src." + ".".join(parts)
|
||||||
print("::: " + identifier, file=fd)
|
print("::: " + identifier, file=fd)
|
||||||
|
|
||||||
|
cmdopts = [
|
||||||
cmdopts = [f"{sys.executable}","-m","mkdocs","-v","build","--site-dir",str(site_path),"--clean"]
|
f"{sys.executable}",
|
||||||
|
"-m",
|
||||||
|
"mkdocs",
|
||||||
|
"-v",
|
||||||
|
"build",
|
||||||
|
"--site-dir",
|
||||||
|
str(site_path),
|
||||||
|
"--clean",
|
||||||
|
]
|
||||||
|
|
||||||
# little hack here, to enable / disable pdf generation using own class config
|
# little hack here, to enable / disable pdf generation using own class config
|
||||||
# => reason is mkdocs seems to try loading the plugin even if we disable it, so we need to
|
# => reason is mkdocs seems to try loading the plugin even if we disable it, so we need to
|
||||||
# manually process the configuration file.
|
# manually process the configuration file.
|
||||||
mkdocsCfg=None
|
mkdocsCfg = None
|
||||||
with open(cls.project_rootdir_path / "mkdocs.yml",'r') as mkdocsCfgFile:
|
with open(cls.project_rootdir_path / "mkdocs.yml", "r") as mkdocsCfgFile:
|
||||||
mkdocsCfg = yaml.load(mkdocsCfgFile, Loader=yaml.SafeLoader)
|
mkdocsCfg = yaml.load(mkdocsCfgFile, Loader=yaml.SafeLoader)
|
||||||
|
|
||||||
if cls.enable_gen_pdf==True:
|
if cls.enable_gen_pdf == True:
|
||||||
mkdocsCfg['plugins'].append({ 'with-pdf':{
|
mkdocsCfg["plugins"].append(
|
||||||
'cover_subtitle': 'User Manual',
|
{
|
||||||
'cover_logo': str(cls.project_rootdir_path / 'docs-static' / 'Library.jpg'),
|
"with-pdf": {
|
||||||
'verbose': False,
|
"cover_subtitle": "User Manual",
|
||||||
'media_type': 'print',
|
"cover_logo": str(
|
||||||
'exclude_pages': ['LICENSE'],
|
cls.project_rootdir_path / "docs-static" / "Library.jpg"
|
||||||
'output_path': str(site_path / 'pdf' / 'manual.pdf')
|
),
|
||||||
}})
|
"verbose": False,
|
||||||
|
"media_type": "print",
|
||||||
|
"headless_chrome_path": "chromium",
|
||||||
|
"exclude_pages": ["LICENSE"],
|
||||||
|
"output_path": str(site_path / "pdf" / "manual.pdf"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
for subelem in mkdocsCfg['plugins']:
|
for subelem in mkdocsCfg["plugins"]:
|
||||||
if isinstance(subelem,dict) :
|
if isinstance(subelem, dict):
|
||||||
if 'with-pdf' in subelem.keys():
|
if "with-pdf" in subelem.keys():
|
||||||
mkdocsCfg['plugins'].remove(subelem)
|
mkdocsCfg["plugins"].remove(subelem)
|
||||||
break
|
break
|
||||||
|
|
||||||
with open(cls.project_rootdir_path / "mkdocs.yml",'w') as mkdocsCfgFile:
|
with open(cls.project_rootdir_path / "mkdocs.yml", "w") as mkdocsCfgFile:
|
||||||
mkdocsCfgFile.write(yaml.dump(mkdocsCfg, Dumper=Dumper,default_flow_style=False, sort_keys=False))
|
mkdocsCfgFile.write(
|
||||||
|
yaml.dump(
|
||||||
|
mkdocsCfg, Dumper=Dumper, default_flow_style=False, sort_keys=False
|
||||||
res=cls.run_cmd(cmdopts)
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
res = cls.run_cmd(cmdopts)
|
||||||
print(res.decode())
|
print(res.decode())
|
||||||
print(' !! done')
|
print(" !! done")
|
||||||
|
|
||||||
|
|||||||
@@ -9,64 +9,76 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from abc import ABC,abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
if TYPE_CHECKING: # Only imports the below statements during type checking
|
if TYPE_CHECKING: # Only imports the below statements during type checking
|
||||||
from typing import Union
|
from typing import Union
|
||||||
|
|
||||||
|
|
||||||
class helper_base(ABC):
|
class helper_base(ABC):
|
||||||
project_rootdir_path: Union[Path,None] = None
|
project_rootdir_path: Union[Path, None] = None
|
||||||
pyproject: Union[dict,None] = None
|
pyproject: Union[dict, None] = None
|
||||||
current_dir: Union[Path,None] = None
|
current_dir: Union[Path, None] = None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def set_context(cls,project_rootdir_path:Path, pyproject:dict):
|
def set_context(cls, project_rootdir_path: Path, pyproject: dict):
|
||||||
cls.project_rootdir_path = project_rootdir_path
|
cls.project_rootdir_path = project_rootdir_path
|
||||||
cls.pyproject = pyproject
|
cls.pyproject = pyproject
|
||||||
cls.current_dir = Path(__file__).parent.absolute()
|
cls.current_dir = Path(__file__).parent.absolute()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_result_dir(cls):
|
def get_result_dir(cls):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _reset_dir(dirpath:Path):
|
def _reset_dir(dirpath: Path):
|
||||||
dirpath = Path(dirpath)
|
dirpath = Path(dirpath)
|
||||||
if not os.path.exists(dirpath):
|
if not os.path.exists(dirpath):
|
||||||
os.makedirs(dirpath)
|
os.makedirs(dirpath)
|
||||||
[f.unlink() for f in Path(dirpath).glob("*") if f.is_file()]
|
[f.unlink() for f in Path(dirpath).glob("*") if f.is_file()]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def reset_result_dir(cls):
|
def reset_result_dir(cls):
|
||||||
result_dir = cls.get_result_dir()
|
result_dir = cls.get_result_dir()
|
||||||
if result_dir != None:
|
if result_dir != None:
|
||||||
cls._reset_dir(result_dir)
|
cls._reset_dir(result_dir)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def do_job(cls):
|
def do_job(cls):
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def run_cmd_(cls, cmdarray):
|
def run_cmd_(cls, cmdarray):
|
||||||
process = subprocess.run(cmdarray, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True)
|
process = subprocess.run(
|
||||||
|
cmdarray,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
shell=True,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
return process.stdout
|
return process.stdout
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def run_cmd(cls, cmdarray):
|
def run_cmd(cls, cmdarray):
|
||||||
p = subprocess.run(cmdarray, capture_output=True)
|
p = subprocess.run(cmdarray, capture_output=True)
|
||||||
print(p.stdout)
|
print(p.stdout)
|
||||||
print(p.stderr)
|
print(p.stderr)
|
||||||
return p.stdout
|
return p.stdout
|
||||||
|
|
||||||
|
|
||||||
class helper_withresults_base(helper_base):
|
class helper_withresults_base(helper_base):
|
||||||
helper_results_dir: Union[Path,None] = None
|
helper_results_dir: Union[Path, None] = None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_result_dir(cls):
|
def get_result_dir(cls):
|
||||||
if cls.helper_results_dir==None:
|
if cls.helper_results_dir == None:
|
||||||
cls.helper_results_dir=cls.__name__
|
cls.helper_results_dir = cls.__name__
|
||||||
return Path(__file__).parent.parent.absolute() / "helpers-results" / cls.helper_results_dir
|
return (
|
||||||
|
Path(__file__).parent.parent.absolute()
|
||||||
|
/ "helpers-results"
|
||||||
|
/ cls.helper_results_dir
|
||||||
|
)
|
||||||
|
|||||||
@@ -25,197 +25,289 @@ import pylint_json2html
|
|||||||
|
|
||||||
from .helper_base import helper_withresults_base
|
from .helper_base import helper_withresults_base
|
||||||
|
|
||||||
|
|
||||||
class PyLintMetricNotFound(Warning):
|
class PyLintMetricNotFound(Warning):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
class quality_check(helper_withresults_base):
|
|
||||||
PylintMessageList=dict()
|
class quality_check(helper_withresults_base):
|
||||||
|
PylintMessageList = dict()
|
||||||
@classmethod
|
|
||||||
|
@classmethod
|
||||||
def GetPylintMessageList(cls):
|
def GetPylintMessageList(cls):
|
||||||
Messagelist=dict()
|
Messagelist = dict()
|
||||||
regex = r"^:([a-zA-Z-]+) \(([^\)]+)\)"
|
regex = r"^:([a-zA-Z-]+) \(([^\)]+)\)"
|
||||||
for line in cls.run_cmd([sys.executable,"-m","pylint","--list-msgs"]).splitlines():
|
for line in cls.run_cmd(
|
||||||
if res:=re.search(regex,line.decode()):
|
[sys.executable, "-m", "pylint", "--list-msgs"]
|
||||||
Messagelist[res.group(1)]=res.group(2)
|
).splitlines():
|
||||||
|
if res := re.search(regex, line.decode()):
|
||||||
|
Messagelist[res.group(1)] = res.group(2)
|
||||||
cls.PylintMessageList = Messagelist
|
cls.PylintMessageList = Messagelist
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def TryExtractPYReportMetric(line: str,tag: str):
|
def TryExtractPYReportMetric(line: str, tag: str):
|
||||||
regex=f"^(?:\|{tag}\s*\|)(\d+)(?=\s*|)"
|
regex = f"^(?:\|{tag}\s*\|)(\d+)(?=\s*|)"
|
||||||
if res:=re.search(regex,line):
|
if res := re.search(regex, line):
|
||||||
return float(res.group(1))
|
return float(res.group(1))
|
||||||
raise PyLintMetricNotFound()
|
raise PyLintMetricNotFound()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def do_job(cls):
|
def do_job(cls):
|
||||||
print("checking code quality ...")
|
print("checking code quality ...")
|
||||||
cls.GetPylintMessageList()
|
cls.GetPylintMessageList()
|
||||||
|
|
||||||
RES_all=dict()
|
RES_all = dict()
|
||||||
with StringIO() as StdOutput:
|
with StringIO() as StdOutput:
|
||||||
JsonContent=""
|
JsonContent = ""
|
||||||
with redirect_stdout(StdOutput):
|
with redirect_stdout(StdOutput):
|
||||||
pylint_Run(['--output-format=json,parseable',
|
pylint_Run(
|
||||||
'--disable=invalid-name',
|
[
|
||||||
'--ignore=_version.py',
|
"--output-format=json,parseable",
|
||||||
'--reports=y',
|
"--disable=invalid-name",
|
||||||
'--score=yes',
|
"--ignore=_version.py",
|
||||||
'--max-line-length=140',
|
"--reports=y",
|
||||||
'src.' + cls.pyproject['project']['name']], exit=False)
|
"--score=yes",
|
||||||
|
"--max-line-length=140",
|
||||||
with open(cls.get_result_dir()/"report.json","w+", encoding='utf-8') as Outfile:
|
"src." + cls.pyproject["project"]["name"],
|
||||||
|
],
|
||||||
|
exit=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(
|
||||||
|
cls.get_result_dir() / "report.json", "w+", encoding="utf-8"
|
||||||
|
) as Outfile:
|
||||||
# hacky way of exctracting json + having overall score...
|
# hacky way of exctracting json + having overall score...
|
||||||
class TScanState(Enum):
|
class TScanState(Enum):
|
||||||
TEXT_REPORT = 1
|
TEXT_REPORT = 1
|
||||||
JSON_REPORT = 2
|
JSON_REPORT = 2
|
||||||
OTHER_REPORT_START = 3
|
OTHER_REPORT_START = 3
|
||||||
OTHER_REPORT_STATISTICS = 4
|
OTHER_REPORT_STATISTICS = 4
|
||||||
OTHER_REPORT_METRICS = 5
|
OTHER_REPORT_METRICS = 5
|
||||||
OTHER_REPORT_DUPLICATION = 6
|
OTHER_REPORT_DUPLICATION = 6
|
||||||
OTHER_REPORT_MESSAGES_CAT = 7
|
OTHER_REPORT_MESSAGES_CAT = 7
|
||||||
OTHER_REPORT_MESSAGES = 8
|
OTHER_REPORT_MESSAGES = 8
|
||||||
OTHER_REPORT_END = 99
|
OTHER_REPORT_END = 99
|
||||||
|
|
||||||
RES_all['Statistics'] = dict()
|
RES_all["Statistics"] = dict()
|
||||||
RES_all['RawMetrics'] = dict()
|
RES_all["RawMetrics"] = dict()
|
||||||
RES_all['RawMetricsPercent'] = dict()
|
RES_all["RawMetricsPercent"] = dict()
|
||||||
RES_all['Duplication'] = dict()
|
RES_all["Duplication"] = dict()
|
||||||
RES_all['MessagesCat'] = dict()
|
RES_all["MessagesCat"] = dict()
|
||||||
RES_all['Messages'] = dict()
|
RES_all["Messages"] = dict()
|
||||||
RES_all['GlobalScore'] = -999
|
RES_all["GlobalScore"] = -999
|
||||||
RES_all['NbAnalysedStatments'] = -999
|
RES_all["NbAnalysedStatments"] = -999
|
||||||
RES_all['NbAnalysedLines'] = -999
|
RES_all["NbAnalysedLines"] = -999
|
||||||
|
|
||||||
ScanState = TScanState.TEXT_REPORT
|
ScanState = TScanState.TEXT_REPORT
|
||||||
for line in StdOutput.getvalue().split('\n'):
|
for line in StdOutput.getvalue().split("\n"):
|
||||||
print(line)
|
print(line)
|
||||||
if ScanState == TScanState.TEXT_REPORT:
|
if ScanState == TScanState.TEXT_REPORT:
|
||||||
# ignoring this part, we need json
|
# ignoring this part, we need json
|
||||||
if line=='[':
|
if line == "[":
|
||||||
JsonContent+=line
|
JsonContent += line
|
||||||
ScanState = TScanState.JSON_REPORT
|
ScanState = TScanState.JSON_REPORT
|
||||||
elif line=='[]':
|
elif line == "[]":
|
||||||
JsonContent+=line
|
JsonContent += line
|
||||||
ScanState = TScanState.OTHER_REPORT_START
|
ScanState = TScanState.OTHER_REPORT_START
|
||||||
|
|
||||||
elif ScanState == TScanState.JSON_REPORT:
|
elif ScanState == TScanState.JSON_REPORT:
|
||||||
JsonContent+=line
|
JsonContent += line
|
||||||
if line==']':
|
if line == "]":
|
||||||
ScanState = TScanState.OTHER_REPORT_START
|
ScanState = TScanState.OTHER_REPORT_START
|
||||||
|
|
||||||
elif ScanState == TScanState.OTHER_REPORT_START:
|
elif ScanState == TScanState.OTHER_REPORT_START:
|
||||||
if res:=re.search(r"^(\d+)(?= statements analysed.)",line):
|
if res := re.search(r"^(\d+)(?= statements analysed.)", line):
|
||||||
RES_all['NbAnalysedStatments'] = float(res.group(1))
|
RES_all["NbAnalysedStatments"] = float(res.group(1))
|
||||||
if line == "Statistics by type":
|
if line == "Statistics by type":
|
||||||
ScanState = TScanState.OTHER_REPORT_STATISTICS
|
ScanState = TScanState.OTHER_REPORT_STATISTICS
|
||||||
|
|
||||||
elif ScanState == TScanState.OTHER_REPORT_STATISTICS:
|
elif ScanState == TScanState.OTHER_REPORT_STATISTICS:
|
||||||
if res:=re.search(r"^(\d+)(?= lines have been analyzed)",line):
|
if res := re.search(
|
||||||
RES_all['NbAnalysedLines' ]= float(res.group(1))
|
r"^(\d+)(?= lines have been analyzed)", line
|
||||||
|
):
|
||||||
|
RES_all["NbAnalysedLines"] = float(res.group(1))
|
||||||
elif line == "Raw metrics":
|
elif line == "Raw metrics":
|
||||||
ScanState = TScanState.OTHER_REPORT_METRICS
|
ScanState = TScanState.OTHER_REPORT_METRICS
|
||||||
else:
|
else:
|
||||||
with suppress(PyLintMetricNotFound): RES_all['Statistics']['module'] = cls.TryExtractPYReportMetric(line,"module")
|
with suppress(PyLintMetricNotFound):
|
||||||
with suppress(PyLintMetricNotFound): RES_all['Statistics']['class'] = cls.TryExtractPYReportMetric(line,"class")
|
RES_all["Statistics"][
|
||||||
with suppress(PyLintMetricNotFound): RES_all['Statistics']['method'] = cls.TryExtractPYReportMetric(line,"method")
|
"module"
|
||||||
with suppress(PyLintMetricNotFound): RES_all['Statistics']['function'] = cls.TryExtractPYReportMetric(line,"function")
|
] = cls.TryExtractPYReportMetric(line, "module")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
elif ScanState == TScanState.OTHER_REPORT_METRICS:
|
RES_all["Statistics"][
|
||||||
|
"class"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "class")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
|
RES_all["Statistics"][
|
||||||
|
"method"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "method")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
|
RES_all["Statistics"][
|
||||||
|
"function"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "function")
|
||||||
|
|
||||||
|
elif ScanState == TScanState.OTHER_REPORT_METRICS:
|
||||||
if line == "Duplication":
|
if line == "Duplication":
|
||||||
RES_all['RawMetricsPercent']['code'] = RES_all['RawMetrics']['code'] / RES_all['NbAnalysedLines' ]
|
RES_all["RawMetricsPercent"]["code"] = (
|
||||||
RES_all['RawMetricsPercent']['docstring'] = RES_all['RawMetrics']['docstring'] / RES_all['NbAnalysedLines' ]
|
RES_all["RawMetrics"]["code"]
|
||||||
RES_all['RawMetricsPercent']['comment'] = RES_all['RawMetrics']['comment'] / RES_all['NbAnalysedLines' ]
|
/ RES_all["NbAnalysedLines"]
|
||||||
RES_all['RawMetricsPercent']['empty'] = RES_all['RawMetrics']['empty'] / RES_all['NbAnalysedLines' ]
|
)
|
||||||
|
RES_all["RawMetricsPercent"]["docstring"] = (
|
||||||
|
RES_all["RawMetrics"]["docstring"]
|
||||||
|
/ RES_all["NbAnalysedLines"]
|
||||||
|
)
|
||||||
|
RES_all["RawMetricsPercent"]["comment"] = (
|
||||||
|
RES_all["RawMetrics"]["comment"]
|
||||||
|
/ RES_all["NbAnalysedLines"]
|
||||||
|
)
|
||||||
|
RES_all["RawMetricsPercent"]["empty"] = (
|
||||||
|
RES_all["RawMetrics"]["empty"]
|
||||||
|
/ RES_all["NbAnalysedLines"]
|
||||||
|
)
|
||||||
ScanState = TScanState.OTHER_REPORT_DUPLICATION
|
ScanState = TScanState.OTHER_REPORT_DUPLICATION
|
||||||
else:
|
else:
|
||||||
with suppress(PyLintMetricNotFound): RES_all['RawMetrics']['code'] = cls.TryExtractPYReportMetric(line,"code")
|
with suppress(PyLintMetricNotFound):
|
||||||
with suppress(PyLintMetricNotFound): RES_all['RawMetrics']['docstring'] = cls.TryExtractPYReportMetric(line,"docstring")
|
RES_all["RawMetrics"][
|
||||||
with suppress(PyLintMetricNotFound): RES_all['RawMetrics']['comment'] = cls.TryExtractPYReportMetric(line,"comment")
|
"code"
|
||||||
with suppress(PyLintMetricNotFound): RES_all['RawMetrics']['empty'] = cls.TryExtractPYReportMetric(line,"empty")
|
] = cls.TryExtractPYReportMetric(line, "code")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
elif ScanState == TScanState.OTHER_REPORT_DUPLICATION:
|
RES_all["RawMetrics"][
|
||||||
|
"docstring"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "docstring")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
|
RES_all["RawMetrics"][
|
||||||
|
"comment"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "comment")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
|
RES_all["RawMetrics"][
|
||||||
|
"empty"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "empty")
|
||||||
|
|
||||||
|
elif ScanState == TScanState.OTHER_REPORT_DUPLICATION:
|
||||||
if line == "Messages by category":
|
if line == "Messages by category":
|
||||||
ScanState = TScanState.OTHER_REPORT_MESSAGES_CAT
|
ScanState = TScanState.OTHER_REPORT_MESSAGES_CAT
|
||||||
else:
|
else:
|
||||||
with suppress(PyLintMetricNotFound): RES_all['Duplication']['NbDupLines'] = cls.TryExtractPYReportMetric(line,"nb duplicated lines")
|
with suppress(PyLintMetricNotFound):
|
||||||
with suppress(PyLintMetricNotFound): RES_all['Duplication']['PersentDuplicatedLines'] = cls.TryExtractPYReportMetric(line,"percent duplicated lines")
|
RES_all["Duplication"][
|
||||||
|
"NbDupLines"
|
||||||
elif ScanState == TScanState.OTHER_REPORT_MESSAGES_CAT:
|
] = cls.TryExtractPYReportMetric(
|
||||||
|
line, "nb duplicated lines"
|
||||||
|
)
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
|
RES_all["Duplication"][
|
||||||
|
"PersentDuplicatedLines"
|
||||||
|
] = cls.TryExtractPYReportMetric(
|
||||||
|
line, "percent duplicated lines"
|
||||||
|
)
|
||||||
|
|
||||||
|
elif ScanState == TScanState.OTHER_REPORT_MESSAGES_CAT:
|
||||||
if line == "Messages":
|
if line == "Messages":
|
||||||
ScanState = TScanState.OTHER_REPORT_MESSAGES
|
ScanState = TScanState.OTHER_REPORT_MESSAGES
|
||||||
else:
|
else:
|
||||||
with suppress(PyLintMetricNotFound): RES_all['MessagesCat']['Convention'] = cls.TryExtractPYReportMetric(line,"convention")
|
with suppress(PyLintMetricNotFound):
|
||||||
with suppress(PyLintMetricNotFound): RES_all['MessagesCat']['Refactor'] = cls.TryExtractPYReportMetric(line,"refactor")
|
RES_all["MessagesCat"][
|
||||||
with suppress(PyLintMetricNotFound): RES_all['MessagesCat']['Warning'] = cls.TryExtractPYReportMetric(line,"warning")
|
"Convention"
|
||||||
with suppress(PyLintMetricNotFound): RES_all['MessagesCat']['Error'] = cls.TryExtractPYReportMetric(line,"error")
|
] = cls.TryExtractPYReportMetric(line, "convention")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
elif ScanState == TScanState.OTHER_REPORT_MESSAGES:
|
RES_all["MessagesCat"][
|
||||||
|
"Refactor"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "refactor")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
|
RES_all["MessagesCat"][
|
||||||
|
"Warning"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "warning")
|
||||||
|
with suppress(PyLintMetricNotFound):
|
||||||
|
RES_all["MessagesCat"][
|
||||||
|
"Error"
|
||||||
|
] = cls.TryExtractPYReportMetric(line, "error")
|
||||||
|
|
||||||
|
elif ScanState == TScanState.OTHER_REPORT_MESSAGES:
|
||||||
# approx match because the number of '-' depend on screen width..
|
# approx match because the number of '-' depend on screen width..
|
||||||
if line.startswith("--------"):
|
if line.startswith("--------"):
|
||||||
ScanState = TScanState.OTHER_REPORT_END
|
ScanState = TScanState.OTHER_REPORT_END
|
||||||
else:
|
else:
|
||||||
for PylintMessage in cls.PylintMessageList.keys():
|
for PylintMessage in cls.PylintMessageList.keys():
|
||||||
with suppress(PyLintMetricNotFound): RES_all['Messages'][PylintMessage] = cls.TryExtractPYReportMetric(line,PylintMessage)
|
with suppress(PyLintMetricNotFound):
|
||||||
|
RES_all["Messages"][
|
||||||
elif ScanState == TScanState.OTHER_REPORT_END:
|
PylintMessage
|
||||||
if res:=re.search(r"(?<=Your code has been rated at )(\d+(?:\.\d+)?)/10",line):
|
] = cls.TryExtractPYReportMetric(
|
||||||
RES_all['GlobalScore']=float(res.group(1))
|
line, PylintMessage
|
||||||
print(RES_all['GlobalScore'])
|
)
|
||||||
|
|
||||||
|
elif ScanState == TScanState.OTHER_REPORT_END:
|
||||||
|
if res := re.search(
|
||||||
|
r"(?<=Your code has been rated at )(\d+(?:\.\d+)?)/10", line
|
||||||
|
):
|
||||||
|
RES_all["GlobalScore"] = float(res.group(1))
|
||||||
|
print(RES_all["GlobalScore"])
|
||||||
else:
|
else:
|
||||||
raise RuntimeError("Invalid ScanState")
|
raise RuntimeError("Invalid ScanState")
|
||||||
Outfile.write(JsonContent)
|
Outfile.write(JsonContent)
|
||||||
|
|
||||||
with open(cls.get_result_dir()/"metrics.json", 'w') as json_file:
|
with open(cls.get_result_dir() / "metrics.json", "w") as json_file:
|
||||||
json.dump(RES_all, json_file)
|
json.dump(RES_all, json_file)
|
||||||
|
|
||||||
# exporting all Data in one csv, unused atm because jenkins seems not able to select columns from csv an keep displaying all...
|
# exporting all Data in one csv, unused atm because jenkins seems not able to select columns from csv an keep displaying all...
|
||||||
# => to export a working full csv we need to a 'flat' dict (no more nested dict)
|
# => to export a working full csv we need to a 'flat' dict (no more nested dict)
|
||||||
RES_all_trim = copy.deepcopy(RES_all)
|
RES_all_trim = copy.deepcopy(RES_all)
|
||||||
del RES_all_trim["Messages"]
|
del RES_all_trim["Messages"]
|
||||||
flat_RES_all=pandas.json_normalize(RES_all_trim, sep='_').to_dict(orient='records')[0]
|
flat_RES_all = pandas.json_normalize(RES_all_trim, sep="_").to_dict(
|
||||||
|
orient="records"
|
||||||
with open(cls.get_result_dir()/"metrics.csv", 'w', newline='') as csv_file:
|
)[0]
|
||||||
writer = csv.DictWriter(csv_file,fieldnames=flat_RES_all.keys())
|
|
||||||
|
with open(cls.get_result_dir() / "metrics.csv", "w", newline="") as csv_file:
|
||||||
|
writer = csv.DictWriter(csv_file, fieldnames=flat_RES_all.keys())
|
||||||
writer.writeheader()
|
writer.writeheader()
|
||||||
writer.writerow(flat_RES_all)
|
writer.writerow(flat_RES_all)
|
||||||
|
|
||||||
# splited csv exports for jenkins plots: RawMetricsPercent
|
# splited csv exports for jenkins plots: RawMetricsPercent
|
||||||
RES_all_percent = RES_all["RawMetricsPercent"]
|
RES_all_percent = RES_all["RawMetricsPercent"]
|
||||||
with open(cls.get_result_dir()/"metrics_rawpercent.csv", 'w', newline='') as csv_file:
|
with open(
|
||||||
writer = csv.DictWriter(csv_file,fieldnames=RES_all_percent.keys())
|
cls.get_result_dir() / "metrics_rawpercent.csv", "w", newline=""
|
||||||
|
) as csv_file:
|
||||||
|
writer = csv.DictWriter(csv_file, fieldnames=RES_all_percent.keys())
|
||||||
writer.writeheader()
|
writer.writeheader()
|
||||||
writer.writerow(RES_all_percent)
|
writer.writerow(RES_all_percent)
|
||||||
|
|
||||||
# splited csv exports for jenkins plots: Statistics + Duplication + NbAnalysedStatments + NbAnalysedLines
|
# splited csv exports for jenkins plots: Statistics + Duplication + NbAnalysedStatments + NbAnalysedLines
|
||||||
RES_all_stats = copy.deepcopy(RES_all["Statistics"])
|
RES_all_stats = copy.deepcopy(RES_all["Statistics"])
|
||||||
RES_all_stats["NbDupLines"] = RES_all['Duplication']['NbDupLines']
|
RES_all_stats["NbDupLines"] = RES_all["Duplication"]["NbDupLines"]
|
||||||
RES_all_stats["PersentDuplicatedLines"] = RES_all['Duplication']['PersentDuplicatedLines']
|
RES_all_stats["PersentDuplicatedLines"] = RES_all["Duplication"][
|
||||||
RES_all_stats["NbAnalysedStatments"] = RES_all['NbAnalysedStatments' ]
|
"PersentDuplicatedLines"
|
||||||
RES_all_stats["NbAnalysedLines"] = RES_all['NbAnalysedLines' ]
|
]
|
||||||
with open(cls.get_result_dir()/"metrics_Statistics.csv", 'w', newline='') as csv_file:
|
RES_all_stats["NbAnalysedStatments"] = RES_all["NbAnalysedStatments"]
|
||||||
writer = csv.DictWriter(csv_file,fieldnames=RES_all_stats.keys())
|
RES_all_stats["NbAnalysedLines"] = RES_all["NbAnalysedLines"]
|
||||||
|
with open(
|
||||||
|
cls.get_result_dir() / "metrics_Statistics.csv", "w", newline=""
|
||||||
|
) as csv_file:
|
||||||
|
writer = csv.DictWriter(csv_file, fieldnames=RES_all_stats.keys())
|
||||||
writer.writeheader()
|
writer.writeheader()
|
||||||
writer.writerow(RES_all_stats)
|
writer.writerow(RES_all_stats)
|
||||||
|
|
||||||
# splited csv exports for jenkins plots: Statistics + Duplication
|
# splited csv exports for jenkins plots: Statistics + Duplication
|
||||||
RES_all_MessagesCat = RES_all['MessagesCat']
|
RES_all_MessagesCat = RES_all["MessagesCat"]
|
||||||
with open(cls.get_result_dir()/"metrics_MessagesCat.csv", 'w', newline='') as csv_file:
|
with open(
|
||||||
writer = csv.DictWriter(csv_file,fieldnames=RES_all_MessagesCat.keys())
|
cls.get_result_dir() / "metrics_MessagesCat.csv", "w", newline=""
|
||||||
|
) as csv_file:
|
||||||
|
writer = csv.DictWriter(csv_file, fieldnames=RES_all_MessagesCat.keys())
|
||||||
writer.writeheader()
|
writer.writeheader()
|
||||||
writer.writerow(RES_all_MessagesCat)
|
writer.writerow(RES_all_MessagesCat)
|
||||||
|
|
||||||
# splited csv exports for jenkins plots: GlobalScore
|
# splited csv exports for jenkins plots: GlobalScore
|
||||||
RES_GlobalScore = {'GlobalScore': RES_all['GlobalScore']}
|
RES_GlobalScore = {"GlobalScore": RES_all["GlobalScore"]}
|
||||||
with open(cls.get_result_dir()/"metrics_GlobalScore.csv", 'w', newline='') as csv_file:
|
with open(
|
||||||
writer = csv.DictWriter(csv_file,fieldnames=RES_GlobalScore.keys())
|
cls.get_result_dir() / "metrics_GlobalScore.csv", "w", newline=""
|
||||||
|
) as csv_file:
|
||||||
|
writer = csv.DictWriter(csv_file, fieldnames=RES_GlobalScore.keys())
|
||||||
writer.writeheader()
|
writer.writeheader()
|
||||||
writer.writerow(RES_GlobalScore)
|
writer.writerow(RES_GlobalScore)
|
||||||
|
|
||||||
# converting the report using pylint_json2html (/!\ internal API, but as their is no leading '_' ...)
|
# converting the report using pylint_json2html (/!\ internal API, but as their is no leading '_' ...)
|
||||||
with open(cls.get_result_dir()/"report.html","w+", encoding='utf-8') as Outfile:
|
with open(
|
||||||
|
cls.get_result_dir() / "report.html", "w+", encoding="utf-8"
|
||||||
|
) as Outfile:
|
||||||
raw_data = json.loads(JsonContent)
|
raw_data = json.loads(JsonContent)
|
||||||
report=pylint_json2html.Report( raw_data)
|
report = pylint_json2html.Report(raw_data)
|
||||||
Outfile.write(report.render())
|
Outfile.write(report.render())
|
||||||
|
|
||||||
print("Done")
|
print("Done")
|
||||||
|
|||||||
@@ -16,36 +16,46 @@ from mypy import api
|
|||||||
from .helper_base import helper_withresults_base
|
from .helper_base import helper_withresults_base
|
||||||
|
|
||||||
|
|
||||||
class types_check(helper_withresults_base):
|
class types_check(helper_withresults_base):
|
||||||
JUnitReportName = "junit.xml"
|
JUnitReportName = "junit.xml"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def do_job(cls):
|
def do_job(cls):
|
||||||
print("checking code typing ...")
|
print("checking code typing ...")
|
||||||
result = api.run([ # project path
|
result = api.run(
|
||||||
"-m",
|
[ # project path
|
||||||
"src." + str(cls.pyproject['project']['name']),
|
"-m",
|
||||||
# analysis configuration
|
"src." + str(cls.pyproject["project"]["name"]),
|
||||||
"--ignore-missing-imports",
|
# analysis configuration
|
||||||
"--strict-equality",
|
"--ignore-missing-imports",
|
||||||
# reports generation
|
"--strict-equality",
|
||||||
"--cobertura-xml-report", str(cls.get_result_dir()),
|
# reports generation
|
||||||
"--html-report", str(cls.get_result_dir()),
|
"--cobertura-xml-report",
|
||||||
"--linecount-report", str(cls.get_result_dir()),
|
str(cls.get_result_dir()),
|
||||||
"--linecoverage-report", str(cls.get_result_dir()),
|
"--html-report",
|
||||||
"--lineprecision-report", str(cls.get_result_dir()),
|
str(cls.get_result_dir()),
|
||||||
"--txt-report", str(cls.get_result_dir()),
|
"--linecount-report",
|
||||||
"--xml-report", str(cls.get_result_dir()),
|
str(cls.get_result_dir()),
|
||||||
"--junit-xml", str(cls.get_result_dir()) + "/" + cls.JUnitReportName
|
"--linecoverage-report",
|
||||||
])
|
str(cls.get_result_dir()),
|
||||||
|
"--lineprecision-report",
|
||||||
|
str(cls.get_result_dir()),
|
||||||
|
"--txt-report",
|
||||||
|
str(cls.get_result_dir()),
|
||||||
|
"--xml-report",
|
||||||
|
str(cls.get_result_dir()),
|
||||||
|
"--junit-xml",
|
||||||
|
str(cls.get_result_dir()) + "/" + cls.JUnitReportName,
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
if result[0]:
|
if result[0]:
|
||||||
print('\nType checking report:\n')
|
print("\nType checking report:\n")
|
||||||
print(result[0]) # stdout
|
print(result[0]) # stdout
|
||||||
|
|
||||||
if result[1]:
|
if result[1]:
|
||||||
print('\nError report:\n')
|
print("\nError report:\n")
|
||||||
print(result[1]) # stderr
|
print(result[1]) # stderr
|
||||||
|
|
||||||
print('\nExit status:', result[2])
|
print("\nExit status:", result[2])
|
||||||
print("Done")
|
print("Done")
|
||||||
|
|||||||
@@ -21,34 +21,41 @@ from junit2htmlreport import parser as junit2html_parser
|
|||||||
from .helper_base import helper_withresults_base
|
from .helper_base import helper_withresults_base
|
||||||
|
|
||||||
|
|
||||||
class unit_test(helper_withresults_base):
|
class unit_test(helper_withresults_base):
|
||||||
enable_coverage_check: bool = False
|
enable_coverage_check: bool = False
|
||||||
enable_xml_export: bool = True
|
enable_xml_export: bool = True
|
||||||
enable_full_xml_export: bool = True
|
enable_full_xml_export: bool = True
|
||||||
FullReportName: str = "full_report"
|
FullReportName: str = "full_report"
|
||||||
CoverageReportName: str = "test_coverage"
|
CoverageReportName: str = "test_coverage"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def do_job(cls):
|
def do_job(cls):
|
||||||
if cls.enable_coverage_check==True:
|
if cls.enable_coverage_check == True:
|
||||||
import coverage
|
import coverage
|
||||||
|
|
||||||
# preparing unittest framework
|
# preparing unittest framework
|
||||||
test_loader = unittest.TestLoader()
|
test_loader = unittest.TestLoader()
|
||||||
|
|
||||||
if cls.enable_coverage_check == True:
|
if cls.enable_coverage_check == True:
|
||||||
#we start coverage now because module files discovery is part of the coverage measurement
|
# we start coverage now because module files discovery is part of the coverage measurement
|
||||||
CoverageReportPath = Path(str(cls.get_result_dir())+"_coverage")
|
CoverageReportPath = Path(str(cls.get_result_dir()) + "_coverage")
|
||||||
cls._reset_dir(CoverageReportPath)
|
cls._reset_dir(CoverageReportPath)
|
||||||
cov = coverage.Coverage(cover_pylib=False,branch=True,source_pkgs=["src."+cls.pyproject['project']['name']])
|
cov = coverage.Coverage(
|
||||||
|
cover_pylib=False,
|
||||||
|
branch=True,
|
||||||
|
source_pkgs=["src." + cls.pyproject["project"]["name"]],
|
||||||
|
)
|
||||||
cov.start()
|
cov.start()
|
||||||
|
|
||||||
package_tests = test_loader.discover(start_dir=str(cls.project_rootdir_path / "test"),top_level_dir=str(cls.project_rootdir_path / "test"))
|
package_tests = test_loader.discover(
|
||||||
|
start_dir=str(cls.project_rootdir_path / "test"),
|
||||||
|
top_level_dir=str(cls.project_rootdir_path / "test"),
|
||||||
|
)
|
||||||
if cls.enable_xml_export:
|
if cls.enable_xml_export:
|
||||||
testRunner = xmlrunner.XMLTestRunner(output=str(str(cls.get_result_dir())))
|
testRunner = xmlrunner.XMLTestRunner(output=str(str(cls.get_result_dir())))
|
||||||
else:
|
else:
|
||||||
testRunner = unittest.TextTestRunner()
|
testRunner = unittest.TextTestRunner()
|
||||||
|
|
||||||
# running the test
|
# running the test
|
||||||
testRunner.run(package_tests)
|
testRunner.run(package_tests)
|
||||||
|
|
||||||
@@ -57,23 +64,33 @@ class unit_test(helper_withresults_base):
|
|||||||
cov.stop()
|
cov.stop()
|
||||||
cov.save()
|
cov.save()
|
||||||
cov.html_report(directory=str(CoverageReportPath))
|
cov.html_report(directory=str(CoverageReportPath))
|
||||||
cov.xml_report(outfile=(CoverageReportPath/f"{cls.CoverageReportName}.xml"))
|
cov.xml_report(
|
||||||
|
outfile=(CoverageReportPath / f"{cls.CoverageReportName}.xml")
|
||||||
|
)
|
||||||
|
|
||||||
# computing results (Only if xml available)
|
# computing results (Only if xml available)
|
||||||
if cls.enable_full_xml_export == True:
|
if cls.enable_full_xml_export == True:
|
||||||
print("Full reports generation...")
|
print("Full reports generation...")
|
||||||
FullReportPath = Path(str(cls.get_result_dir())+"_full")
|
FullReportPath = Path(str(cls.get_result_dir()) + "_full")
|
||||||
cls._reset_dir(FullReportPath)
|
cls._reset_dir(FullReportPath)
|
||||||
|
|
||||||
FullJUnitReport = JUnitXml()
|
FullJUnitReport = JUnitXml()
|
||||||
for fname in [fname for fname in os.listdir(cls.get_result_dir()) if fname.endswith('.xml')]:
|
for fname in [
|
||||||
FullJUnitReport+=JUnitXml.fromfile(str(cls.get_result_dir() / fname))
|
fname
|
||||||
|
for fname in os.listdir(cls.get_result_dir())
|
||||||
|
if fname.endswith(".xml")
|
||||||
|
]:
|
||||||
|
FullJUnitReport += JUnitXml.fromfile(str(cls.get_result_dir() / fname))
|
||||||
|
|
||||||
current_datetime = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
|
current_datetime = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
|
||||||
full_report_base_name = f'{cls.pyproject["project"]["name"]}-{cls.FullReportName}-{current_datetime}'
|
full_report_base_name = f'{cls.pyproject["project"]["name"]}-{cls.FullReportName}-{current_datetime}'
|
||||||
FullJUnitReport.write(str(FullReportPath / f'{full_report_base_name}.xml'))
|
FullJUnitReport.write(str(FullReportPath / f"{full_report_base_name}.xml"))
|
||||||
report = junit2html_parser.Junit(FullReportPath/ f'{full_report_base_name}.xml')
|
report = junit2html_parser.Junit(
|
||||||
|
FullReportPath / f"{full_report_base_name}.xml"
|
||||||
|
)
|
||||||
html = report.html()
|
html = report.html()
|
||||||
with open(FullReportPath/ f'{full_report_base_name}.html', "wb") as outfile:
|
with open(
|
||||||
outfile.write(html.encode('utf-8'))
|
FullReportPath / f"{full_report_base_name}.html", "wb"
|
||||||
print("Done")
|
) as outfile:
|
||||||
|
outfile.write(html.encode("utf-8"))
|
||||||
|
print("Done")
|
||||||
|
|||||||
120
mkdocs.yml
120
mkdocs.yml
@@ -1,62 +1,78 @@
|
|||||||
# pyChaChaDummyProject (c) by chacha
|
|
||||||
#
|
|
||||||
# pyChaChaDummyProject 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 <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
|
|
||||||
|
|
||||||
|
|
||||||
docs_dir: docs
|
docs_dir: docs
|
||||||
site_name: pygitversionhelper
|
site_name: pygitversionhelper
|
||||||
site_url: https://chacha.ddns.net/mkdocs-web/chacha/pygitversionhelper/latest/
|
site_url: 'https://chacha.ddns.net/mkdocs-web/chacha/pygitversionhelper/latest/'
|
||||||
site_description: pygitversionhelper
|
site_description: pygitversionhelper
|
||||||
site_author: chacha
|
site_author: chacha
|
||||||
repo_url: https://chacha.ddns.net/gitea/chacha/pygitversionhelper
|
repo_url: 'https://chacha.ddns.net/gitea/chacha/pygitversionhelper'
|
||||||
use_directory_urls: false
|
use_directory_urls: false
|
||||||
|
copyright: Copyright © 2016 - 2023 chacha
|
||||||
theme:
|
theme:
|
||||||
name: material
|
name: material
|
||||||
features:
|
features:
|
||||||
- navigation.instant
|
- navigation.instant
|
||||||
- navigation.tracking
|
- navigation.tracking
|
||||||
- navigation.tabs
|
- navigation.tabs
|
||||||
- navigation.tabs.sticky
|
- navigation.tabs.sticky
|
||||||
- toc.integrate
|
- toc.integrate
|
||||||
- navigation.top
|
- navigation.top
|
||||||
palette:
|
palette:
|
||||||
- media: '(prefers-color-scheme: dark)'
|
- media: '(prefers-color-scheme: dark)'
|
||||||
scheme: slate
|
scheme: slate
|
||||||
toggle:
|
toggle:
|
||||||
icon: material/brightness-4
|
icon: material/brightness-4
|
||||||
name: Switch to system preference
|
name: Switch to system preference
|
||||||
- media: (prefers-color-scheme)
|
- media: (prefers-color-scheme)
|
||||||
toggle:
|
toggle:
|
||||||
icon: material/brightness-auto
|
icon: material/brightness-auto
|
||||||
name: Switch to light mode
|
name: Switch to light mode
|
||||||
- media: '(prefers-color-scheme: light)'
|
- media: '(prefers-color-scheme: light)'
|
||||||
scheme: default
|
scheme: default
|
||||||
toggle:
|
toggle:
|
||||||
icon: material/brightness-7
|
icon: material/brightness-7
|
||||||
name: Switch to dark mode
|
name: Switch to dark mode
|
||||||
plugins:
|
plugins:
|
||||||
- search
|
- search
|
||||||
- localsearch
|
- localsearch
|
||||||
- autorefs
|
- autorefs
|
||||||
- mkdocstrings:
|
- mkdocstrings:
|
||||||
default_handler: python
|
default_handler: python
|
||||||
handlers:
|
handlers:
|
||||||
python:
|
python:
|
||||||
selection:
|
selection:
|
||||||
filters:
|
filters:
|
||||||
- '!^_(?!_init__)'
|
- '!^_(?!_init__)'
|
||||||
inherited_members: true
|
inherited_members: true
|
||||||
rendering:
|
rendering:
|
||||||
show_root_heading: false
|
show_root_heading: false
|
||||||
show_root_toc_entry: false
|
show_root_toc_entry: false
|
||||||
show_root_full_path: false
|
show_root_full_path: false
|
||||||
show_if_no_docstring: true
|
show_if_no_docstring: true
|
||||||
show_signature_annotations: true
|
show_signature_annotations: true
|
||||||
show_source: false
|
show_source: false
|
||||||
heading_level: 2
|
heading_level: 2
|
||||||
group_by_category: true
|
group_by_category: true
|
||||||
show_category_heading: true
|
show_category_heading: true
|
||||||
|
markdown_extensions:
|
||||||
|
- def_list
|
||||||
|
- tables
|
||||||
|
- attr_list
|
||||||
|
- abbr
|
||||||
|
- pymdownx.betterem:
|
||||||
|
smart_enable: all
|
||||||
|
- pymdownx.caret
|
||||||
|
- pymdownx.critic
|
||||||
|
- pymdownx.details
|
||||||
|
- pymdownx.inlinehilite
|
||||||
|
- pymdownx.snippets
|
||||||
|
- pymdownx.highlight:
|
||||||
|
anchor_linenums: true
|
||||||
|
line_spans: __span
|
||||||
|
pygments_lang_class: true
|
||||||
|
- pymdownx.keys
|
||||||
|
- pymdownx.mark
|
||||||
|
- pymdownx.progressbar
|
||||||
|
- pymdownx.smartsymbols
|
||||||
|
- pymdownx.tasklist:
|
||||||
|
custom_checkbox: true
|
||||||
|
- pymdownx.tilde
|
||||||
|
- footnotes
|
||||||
@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[tool.setuptools_scm]
|
[tool.setuptools_scm]
|
||||||
version_scheme= "post-release"
|
version_scheme= "post-release"
|
||||||
tag_regex="^(?:v)?(?P<version>\\d+\\.\\d+\\.\\d+)([\\.\\-\\+])?(?:.*)?"
|
# tag_regex="^(?:v)?(?P<version>\\d+\\.\\d+\\.\\d+)([\\.\\-\\+])?(?:.*)?"
|
||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "pygitversionhelper"
|
name = "pygitversionhelper"
|
||||||
@@ -59,7 +59,7 @@ test = ["junitparser>=2.8","junit2html>=30.1","xmlrunner>=1.7","myp
|
|||||||
coverage-check = ["coverage>=7.0"]
|
coverage-check = ["coverage>=7.0"]
|
||||||
quality-check = ["pylint>=2.15","pylint-json2html>=0.4","pandas>=1.5"]
|
quality-check = ["pylint>=2.15","pylint-json2html>=0.4","pandas>=1.5"]
|
||||||
type-check = ["mypy[reports]>=0.99" ]
|
type-check = ["mypy[reports]>=0.99" ]
|
||||||
doc-gen = ["mkdocs>=1.4.0", "mkdocs-material>=8.5", "mkdocs-localsearch>=0.9.0", "mkdocstrings[python]>=0.19", "mkdocs-with-pdf>=0.9.3","pyyaml>=6.0"]
|
doc-gen = ["mkdocs>=1.4.0", "mkdocs-material>=8.5", "mkdocs-localsearch>=0.9.0", "mkdocstrings[python]>=0.19", "mkdocs-pdf-export-plugin","pyyaml>=6.0","pymdown-extensions>=9"]
|
||||||
|
|
||||||
#[project.scripts]
|
#[project.scripts]
|
||||||
#my-script = "my_package.module:function"
|
#my-script = "my_package.module:function"
|
||||||
|
|||||||
@@ -36,7 +36,10 @@ import logging
|
|||||||
|
|
||||||
from packaging.version import VERSION_PATTERN as packaging_VERSION_PATTERN
|
from packaging.version import VERSION_PATTERN as packaging_VERSION_PATTERN
|
||||||
|
|
||||||
def _exec(cmd: str, root: str | os.PathLike | None = None, raw:bool = False) -> list[str]:
|
|
||||||
|
def _exec(
|
||||||
|
cmd: str, root: str | os.PathLike | None = None, raw: bool = False
|
||||||
|
) -> list[str]:
|
||||||
"""
|
"""
|
||||||
helper function to handle system cmd execution
|
helper function to handle system cmd execution
|
||||||
Args:
|
Args:
|
||||||
@@ -44,14 +47,22 @@ def _exec(cmd: str, root: str | os.PathLike | None = None, raw:bool = False) ->
|
|||||||
root: root directory where the command need to be executed
|
root: root directory where the command need to be executed
|
||||||
Returns:
|
Returns:
|
||||||
a list of command's return lines
|
a list of command's return lines
|
||||||
|
|
||||||
"""
|
"""
|
||||||
p = subprocess.run(cmd, text=True, cwd=root, capture_output=True, check=False, timeout=2,shell=True)
|
p = subprocess.run(
|
||||||
if re.search("not a git repository",p.stderr):
|
cmd,
|
||||||
|
text=True,
|
||||||
|
cwd=root,
|
||||||
|
capture_output=True,
|
||||||
|
check=False,
|
||||||
|
timeout=2,
|
||||||
|
shell=True,
|
||||||
|
)
|
||||||
|
if re.search("not a git repository", p.stderr):
|
||||||
raise gitversionhelper.repository.notAGitRepository()
|
raise gitversionhelper.repository.notAGitRepository()
|
||||||
if re.search("fatal:",p.stderr): #pragma: nocover
|
if re.search("fatal:", p.stderr): # pragma: nocover
|
||||||
raise gitversionhelper.unknownGITFatalError(p.stderr)
|
raise gitversionhelper.unknownGITFatalError(p.stderr)
|
||||||
if int(p.returncode) < 0: #pragma: nocover
|
if int(p.returncode) < 0: # pragma: nocover
|
||||||
raise gitversionhelper.unknownGITError(p.stderr)
|
raise gitversionhelper.unknownGITError(p.stderr)
|
||||||
|
|
||||||
if raw:
|
if raw:
|
||||||
@@ -59,15 +70,18 @@ def _exec(cmd: str, root: str | os.PathLike | None = None, raw:bool = False) ->
|
|||||||
lines = p.stdout.splitlines()
|
lines = p.stdout.splitlines()
|
||||||
return [line.rstrip() for line in lines if line.rstrip()]
|
return [line.rstrip() for line in lines if line.rstrip()]
|
||||||
|
|
||||||
|
|
||||||
class gitversionhelperException(Exception):
|
class gitversionhelperException(Exception):
|
||||||
"""
|
"""
|
||||||
general Module Exception
|
general Module Exception
|
||||||
"""
|
"""
|
||||||
|
|
||||||
class gitversionhelper: # pylint: disable=too-few-public-methods
|
|
||||||
|
class gitversionhelper: # pylint: disable=too-few-public-methods
|
||||||
"""
|
"""
|
||||||
main gitversionhelper class
|
main gitversionhelper class
|
||||||
"""
|
"""
|
||||||
|
|
||||||
class wrongArguments(gitversionhelperException):
|
class wrongArguments(gitversionhelperException):
|
||||||
"""
|
"""
|
||||||
wrong argument generic exception
|
wrong argument generic exception
|
||||||
@@ -87,6 +101,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
"""
|
"""
|
||||||
class containing methods focusing on repository
|
class containing methods focusing on repository
|
||||||
"""
|
"""
|
||||||
|
|
||||||
class repositoryException(gitversionhelperException):
|
class repositoryException(gitversionhelperException):
|
||||||
"""
|
"""
|
||||||
generic repository exeption
|
generic repository exeption
|
||||||
@@ -110,12 +125,13 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
True if it is dirty
|
True if it is dirty
|
||||||
"""
|
"""
|
||||||
return bool(_exec("git status --short"))
|
return bool(_exec("git status --short"))
|
||||||
|
|
||||||
class commit:
|
class commit:
|
||||||
"""
|
"""
|
||||||
class containing methods focusing on commits
|
class containing methods focusing on commits
|
||||||
"""
|
"""
|
||||||
__OptDict = {"same_branch": "same_branch",
|
|
||||||
"merged_output":"merged_output"}
|
__OptDict = {"same_branch": "same_branch", "merged_output": "merged_output"}
|
||||||
|
|
||||||
class commitException(gitversionhelperException):
|
class commitException(gitversionhelperException):
|
||||||
"""
|
"""
|
||||||
@@ -128,7 +144,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getMessagesSinceTag(cls,tag:str,**kwargs) -> str:
|
def getMessagesSinceTag(cls, tag: str, **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
retrieve a commits message history from repository
|
retrieve a commits message history from repository
|
||||||
from LastCommit to the given tag
|
from LastCommit to the given tag
|
||||||
@@ -138,24 +154,32 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
Returns:
|
Returns:
|
||||||
the commit message
|
the commit message
|
||||||
"""
|
"""
|
||||||
current_commit_id=cls.getLast(**kwargs)
|
current_commit_id = cls.getLast(**kwargs)
|
||||||
tag_commit_id=cls.getFromTag(tag)
|
tag_commit_id = cls.getFromTag(tag)
|
||||||
|
|
||||||
if ((cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True)):
|
if (cls.__OptDict["same_branch"] in kwargs) and (
|
||||||
commits = _exec(f"git rev-list --first-parent --ancestry-path {tag_commit_id}..{current_commit_id}")
|
kwargs[cls.__OptDict["same_branch"]] is True
|
||||||
|
):
|
||||||
|
commits = _exec(
|
||||||
|
f"git rev-list --first-parent --ancestry-path {tag_commit_id}..{current_commit_id}"
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
commits = _exec(f"git rev-list --ancestry-path {tag_commit_id}..{current_commit_id}")
|
commits = _exec(
|
||||||
result=[]
|
f"git rev-list --ancestry-path {tag_commit_id}..{current_commit_id}"
|
||||||
|
)
|
||||||
|
result = []
|
||||||
for commit in commits:
|
for commit in commits:
|
||||||
result.append(cls.getMessage(commit))
|
result.append(cls.getMessage(commit))
|
||||||
|
|
||||||
if ((cls.__OptDict["merged_output"] in kwargs) and (kwargs[cls.__OptDict["merged_output"]] is True)):
|
if (cls.__OptDict["merged_output"] in kwargs) and (
|
||||||
|
kwargs[cls.__OptDict["merged_output"]] is True
|
||||||
|
):
|
||||||
print("JOIN")
|
print("JOIN")
|
||||||
return os.linesep.join(result)
|
return os.linesep.join(result)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getMessage(cls, commit_hash:str) -> str:
|
def getMessage(cls, commit_hash: str) -> str:
|
||||||
"""
|
"""
|
||||||
retrieve a commit message from repository
|
retrieve a commit message from repository
|
||||||
Args:
|
Args:
|
||||||
@@ -164,14 +188,18 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
the commit message
|
the commit message
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
res=_exec(f"git log -z --pretty=\"tformat:%B%-C()\" -n 1 {commit_hash}",None,True).rstrip('\x00')
|
res = _exec(
|
||||||
|
f'git log -z --pretty="tformat:%B%-C()" -n 1 {commit_hash}',
|
||||||
|
None,
|
||||||
|
True,
|
||||||
|
).rstrip("\x00")
|
||||||
except gitversionhelper.unknownGITFatalError as _e:
|
except gitversionhelper.unknownGITFatalError as _e:
|
||||||
raise cls.commitNotFound("no commit found in commit history") from _e
|
raise cls.commitNotFound("no commit found in commit history") from _e
|
||||||
|
|
||||||
return res.replace('\r\n','\n').replace('\n','\r\n')
|
return res.replace("\r\n", "\n").replace("\n", "\r\n")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getFromTag(cls,tag:str) -> str:
|
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:
|
Args:
|
||||||
@@ -180,15 +208,15 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
the commit Id
|
the commit Id
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
res=_exec(f"git rev-list -n 1 {tag}")
|
res = _exec(f"git rev-list -n 1 {tag}")
|
||||||
except gitversionhelper.unknownGITFatalError as _e:
|
except gitversionhelper.unknownGITFatalError as _e:
|
||||||
raise cls.commitNotFound("no commit found in commit history") from _e
|
raise cls.commitNotFound("no commit found in commit history") from _e
|
||||||
if len(res)==0:
|
if len(res) == 0:
|
||||||
raise cls.commitNotFound("no commit found in commit history")
|
raise cls.commitNotFound("no commit found in commit history")
|
||||||
return res[0]
|
return res[0]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getLast(cls,**kwargs) -> str:
|
def getLast(cls, **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
retrieve last commit from repository
|
retrieve last commit from repository
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -196,15 +224,21 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
Returns:
|
Returns:
|
||||||
the commit Id
|
the commit Id
|
||||||
"""
|
"""
|
||||||
if ((cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True)):
|
if (cls.__OptDict["same_branch"] in kwargs) and (
|
||||||
|
kwargs[cls.__OptDict["same_branch"]] is True
|
||||||
|
):
|
||||||
try:
|
try:
|
||||||
res = _exec("git rev-parse HEAD")
|
res = _exec("git rev-parse HEAD")
|
||||||
except gitversionhelper.unknownGITFatalError as _e:
|
except gitversionhelper.unknownGITFatalError as _e:
|
||||||
raise cls.commitNotFound("no commit found in commit history") from _e
|
raise cls.commitNotFound(
|
||||||
|
"no commit found in commit history"
|
||||||
|
) from _e
|
||||||
else:
|
else:
|
||||||
res = _exec("git for-each-ref --sort=-committerdate refs/heads/ --count 1 --format=\"%(objectname)\"")
|
res = _exec(
|
||||||
|
'git for-each-ref --sort=-committerdate refs/heads/ --count 1 --format="%(objectname)"'
|
||||||
|
)
|
||||||
|
|
||||||
if len(res)==0:
|
if len(res) == 0:
|
||||||
raise cls.commitNotFound("no commit found in commit history")
|
raise cls.commitNotFound("no commit found in commit history")
|
||||||
return res[0]
|
return res[0]
|
||||||
|
|
||||||
@@ -212,8 +246,17 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
"""
|
"""
|
||||||
class containing methods focusing on tags
|
class containing methods focusing on tags
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__OptDict = {"same_branch": "same_branch"}
|
__OptDict = {"same_branch": "same_branch"}
|
||||||
__validGitTagSort=["","v:refname","-v:refname","taggerdate","committerdate","-taggerdate","-committerdate"]
|
__validGitTagSort = [
|
||||||
|
"",
|
||||||
|
"v:refname",
|
||||||
|
"-v:refname",
|
||||||
|
"taggerdate",
|
||||||
|
"committerdate",
|
||||||
|
"-taggerdate",
|
||||||
|
"-committerdate",
|
||||||
|
]
|
||||||
|
|
||||||
class tagException(gitversionhelperException):
|
class tagException(gitversionhelperException):
|
||||||
"""
|
"""
|
||||||
@@ -231,7 +274,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getTags(cls,sort:str = "taggerdate",**kwargs) -> list[str|None]:
|
def getTags(cls, sort: str = "taggerdate", **kwargs) -> list[str | None]:
|
||||||
"""
|
"""
|
||||||
retrieve all tags from a repository
|
retrieve all tags from a repository
|
||||||
Args:
|
Args:
|
||||||
@@ -243,13 +286,19 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
if sort not in cls.__validGitTagSort:
|
if sort not in cls.__validGitTagSort:
|
||||||
raise gitversionhelper.wrongArguments("sort option not in allowed list")
|
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 (cls.__OptDict["same_branch"] in kwargs) and (
|
||||||
|
kwargs[cls.__OptDict["same_branch"]] is True
|
||||||
|
):
|
||||||
currentBranch = _exec("git rev-parse --abbrev-ref HEAD")
|
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 --merged {currentBranch[0]} --sort={sort}")
|
||||||
|
)
|
||||||
|
)
|
||||||
return list(reversed(_exec(f"git tag -l --sort={sort}")))
|
return list(reversed(_exec(f"git tag -l --sort={sort}")))
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getLastTag(cls,**kwargs) -> str | None:
|
def getLastTag(cls, **kwargs) -> str | None:
|
||||||
"""
|
"""
|
||||||
retrieve the last tag from a repository
|
retrieve the last tag from a repository
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -257,21 +306,23 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
Returns:
|
Returns:
|
||||||
the tag
|
the tag
|
||||||
"""
|
"""
|
||||||
if ((cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True)):
|
if (cls.__OptDict["same_branch"] in kwargs) and (
|
||||||
|
kwargs[cls.__OptDict["same_branch"]] is True
|
||||||
|
):
|
||||||
res = _exec("git describe --tags --first-parent --abbrev=0")
|
res = _exec("git describe --tags --first-parent --abbrev=0")
|
||||||
else:
|
else:
|
||||||
res = _exec("git rev-list --tags --date-order --max-count=1")
|
res = _exec("git rev-list --tags --date-order --max-count=1")
|
||||||
if len(res)==1:
|
if len(res) == 1:
|
||||||
res = _exec(f"git describe --tags {res[0]}")
|
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")
|
raise cls.tagNotFound("no tag found in commit history")
|
||||||
if len(res)!=1: #pragma: nocover
|
if len(res) != 1: # pragma: nocover
|
||||||
raise cls.moreThanOneTag("multiple tags on same commit is unsupported")
|
raise cls.moreThanOneTag("multiple tags on same commit is unsupported")
|
||||||
return res[0]
|
return res[0]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getDistanceFromTag(cls,tag:str=None,**kwargs) -> int:
|
def getDistanceFromTag(cls, tag: str = None, **kwargs) -> int:
|
||||||
"""
|
"""
|
||||||
retrieve the distance between HEAD and tag in the repository
|
retrieve the distance between HEAD and tag in the repository
|
||||||
Arguments:
|
Arguments:
|
||||||
@@ -289,23 +340,27 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
"""
|
"""
|
||||||
class containing methods focusing on versions
|
class containing methods focusing on versions
|
||||||
"""
|
"""
|
||||||
__OptDict = { "version_std": "version_std",
|
|
||||||
"formated_output": "formated_output",
|
__OptDict = {
|
||||||
"output_format": "output_format",
|
"version_std": "version_std",
|
||||||
"ignore_unknown_tags": "ignore_unknown_tags"}
|
"formated_output": "formated_output",
|
||||||
|
"output_format": "output_format",
|
||||||
|
"ignore_unknown_tags": "ignore_unknown_tags",
|
||||||
|
}
|
||||||
DefaultInputFormat = "Auto"
|
DefaultInputFormat = "Auto"
|
||||||
VersionStds = { "SemVer" : { "regex" : r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)"\
|
VersionStds = {
|
||||||
r"(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)"\
|
"SemVer": {
|
||||||
r"(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?"\
|
"regex": r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)"
|
||||||
r"(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
|
r"(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)"
|
||||||
"regex_preversion_num": r"(?:\.)(?P<num>(?:\d+(?!\w))+)",
|
r"(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?"
|
||||||
"regex_build_num" : r"(?:\.)(?P<num>(?:\d+(?!\w))+)"
|
r"(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
|
||||||
},
|
"regex_preversion_num": r"(?:\.)(?P<num>(?:\d+(?!\w))+)",
|
||||||
"PEP440" : { "regex" : packaging_VERSION_PATTERN,
|
"regex_build_num": r"(?:\.)(?P<num>(?:\d+(?!\w))+)",
|
||||||
"Auto" : None
|
},
|
||||||
}
|
"PEP440": {"regex": packaging_VERSION_PATTERN, "Auto": None},
|
||||||
}
|
}
|
||||||
__versionReseted = False
|
__versionReseted = False
|
||||||
|
|
||||||
class versionException(gitversionhelperException):
|
class versionException(gitversionhelperException):
|
||||||
"""
|
"""
|
||||||
generic version exception
|
generic version exception
|
||||||
@@ -326,33 +381,44 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
generic version object
|
generic version object
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__OptDict = { "bump_type": "bump_type",
|
__OptDict = {
|
||||||
"bump_dev_strategy": "bump_dev_strategy",
|
"bump_type": "bump_type",
|
||||||
"formated_output": "formated_output"}
|
"bump_dev_strategy": "bump_dev_strategy",
|
||||||
DefaultBumpType = "patch"
|
"formated_output": "formated_output",
|
||||||
BumpTypes = ["major","minor","patch","dev"]
|
}
|
||||||
DefaultBumpDevStrategy = "post"
|
DefaultBumpType = "patch"
|
||||||
BumpDevStrategys = ["post","pre-patch","pre-minor","pre-major"]
|
BumpTypes = ["major", "minor", "patch", "dev"]
|
||||||
|
DefaultBumpDevStrategy = "post"
|
||||||
|
BumpDevStrategys = ["post", "pre-patch", "pre-minor", "pre-major"]
|
||||||
|
|
||||||
version_std: str = "None"
|
version_std: str = "None"
|
||||||
major: int = 0
|
major: int = 0
|
||||||
minor: int = 1
|
minor: int = 1
|
||||||
patch: int = 0
|
patch: int = 0
|
||||||
pre_count:int = 0
|
pre_count: int = 0
|
||||||
post_count:int = 0
|
post_count: int = 0
|
||||||
raw:str = "0.1.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"): #pylint: disable=R0913
|
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.version_std = version_std
|
||||||
self.major = major
|
self.major = major
|
||||||
self.minor = minor
|
self.minor = minor
|
||||||
self.patch = patch
|
self.patch = patch
|
||||||
self.pre_count = pre_count
|
self.pre_count = pre_count
|
||||||
self.post_count = post_count
|
self.post_count = post_count
|
||||||
self.raw = raw
|
self.raw = raw
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _getBumpDevStrategy(cls,**kwargs) -> str:
|
def _getBumpDevStrategy(cls, **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
get selected bump_dev_strategy
|
get selected bump_dev_strategy
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -362,14 +428,19 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
"""
|
"""
|
||||||
BumpDevStrategy = cls.DefaultBumpDevStrategy
|
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:
|
if (
|
||||||
|
kwargs[cls.__OptDict["bump_dev_strategy"]]
|
||||||
|
in cls.BumpDevStrategys
|
||||||
|
):
|
||||||
BumpDevStrategy = kwargs[cls.__OptDict["bump_dev_strategy"]]
|
BumpDevStrategy = kwargs[cls.__OptDict["bump_dev_strategy"]]
|
||||||
else:
|
else:
|
||||||
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['bump_type']} requested")
|
raise gitversionhelper.wrongArguments(
|
||||||
|
f"invalid {cls.__OptDict['bump_type']} requested"
|
||||||
|
)
|
||||||
return BumpDevStrategy
|
return BumpDevStrategy
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _getBumpType(cls,**kwargs) -> str:
|
def _getBumpType(cls, **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
get selected bump_type
|
get selected bump_type
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -382,10 +453,14 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
if kwargs[cls.__OptDict["bump_type"]] in cls.BumpTypes:
|
if kwargs[cls.__OptDict["bump_type"]] in cls.BumpTypes:
|
||||||
BumpType = kwargs[cls.__OptDict["bump_type"]]
|
BumpType = kwargs[cls.__OptDict["bump_type"]]
|
||||||
else:
|
else:
|
||||||
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['bump_type']} requested")
|
raise gitversionhelper.wrongArguments(
|
||||||
|
f"invalid {cls.__OptDict['bump_type']} requested"
|
||||||
|
)
|
||||||
return BumpType
|
return BumpType
|
||||||
|
|
||||||
def bump(self,amount:int=1,**kwargs) -> gitversionhelper.version.MetaVersion | str : # pylint: disable=R0912
|
def bump(
|
||||||
|
self, amount: int = 1, **kwargs
|
||||||
|
) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R0912
|
||||||
"""
|
"""
|
||||||
bump the version to the next one
|
bump the version to the next one
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -395,8 +470,8 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
the bumped version
|
the bumped version
|
||||||
"""
|
"""
|
||||||
BumpType = self._getBumpType(**kwargs)
|
BumpType = self._getBumpType(**kwargs)
|
||||||
BumpDevStrategy=self._getBumpDevStrategy(**kwargs)
|
BumpDevStrategy = self._getBumpDevStrategy(**kwargs)
|
||||||
_v=copy(self)
|
_v = copy(self)
|
||||||
|
|
||||||
if BumpType == "dev":
|
if BumpType == "dev":
|
||||||
if BumpDevStrategy == "post":
|
if BumpDevStrategy == "post":
|
||||||
@@ -404,7 +479,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
_v.pre_count = _v.pre_count + amount
|
_v.pre_count = _v.pre_count + amount
|
||||||
else:
|
else:
|
||||||
_v.post_count = _v.post_count + amount
|
_v.post_count = _v.post_count + amount
|
||||||
#elif BumpDevStrategy in ["pre-patch","pre-minor","pre-major"]:
|
# elif BumpDevStrategy in ["pre-patch","pre-minor","pre-major"]:
|
||||||
else:
|
else:
|
||||||
if _v.post_count > 0:
|
if _v.post_count > 0:
|
||||||
_v.post_count = _v.post_count + amount
|
_v.post_count = _v.post_count + amount
|
||||||
@@ -415,7 +490,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
elif BumpDevStrategy == "pre-minor":
|
elif BumpDevStrategy == "pre-minor":
|
||||||
_v.minor = _v.minor + 1
|
_v.minor = _v.minor + 1
|
||||||
_v.patch = 0
|
_v.patch = 0
|
||||||
#elif BumpDevStrategy == "pre-major":
|
# elif BumpDevStrategy == "pre-major":
|
||||||
else:
|
else:
|
||||||
_v.major = _v.major + 1
|
_v.major = _v.major + 1
|
||||||
_v.minor = 0
|
_v.minor = 0
|
||||||
@@ -426,18 +501,20 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
_v.major = _v.major + amount
|
_v.major = _v.major + amount
|
||||||
elif BumpType == "minor":
|
elif BumpType == "minor":
|
||||||
_v.minor = _v.minor + amount
|
_v.minor = _v.minor + amount
|
||||||
#elif BumpType == "patch":
|
# elif BumpType == "patch":
|
||||||
else:
|
else:
|
||||||
_v.patch = _v.patch + amount
|
_v.patch = _v.patch + amount
|
||||||
_v.pre_count=0
|
_v.pre_count = 0
|
||||||
_v.post_count=0
|
_v.post_count = 0
|
||||||
_v.raw=_v.doFormatVersion(**kwargs)
|
_v.raw = _v.doFormatVersion(**kwargs)
|
||||||
|
|
||||||
if ((self.__OptDict["formated_output"] in kwargs) and (kwargs[self.__OptDict["formated_output"]] is True)):
|
if (self.__OptDict["formated_output"] in kwargs) and (
|
||||||
|
kwargs[self.__OptDict["formated_output"]] is True
|
||||||
|
):
|
||||||
return _v.doFormatVersion(**kwargs)
|
return _v.doFormatVersion(**kwargs)
|
||||||
return _v
|
return _v
|
||||||
|
|
||||||
def doFormatVersion(self,**kwargs) -> str:
|
def doFormatVersion(self, **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
output a formated version string
|
output a formated version string
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -445,10 +522,10 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
Returns:
|
Returns:
|
||||||
formated version string
|
formated version string
|
||||||
"""
|
"""
|
||||||
return gitversionhelper.version.doFormatVersion(self,**kwargs)
|
return gitversionhelper.version.doFormatVersion(self, **kwargs)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _getVersionStd(cls,**kwargs) -> str:
|
def _getVersionStd(cls, **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
get selected version_std
|
get selected version_std
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -461,11 +538,13 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
if kwargs[cls.__OptDict["version_std"]] in cls.VersionStds:
|
if kwargs[cls.__OptDict["version_std"]] in cls.VersionStds:
|
||||||
VersionStd = kwargs[cls.__OptDict["version_std"]]
|
VersionStd = kwargs[cls.__OptDict["version_std"]]
|
||||||
else:
|
else:
|
||||||
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['version_std']} requested")
|
raise gitversionhelper.wrongArguments(
|
||||||
|
f"invalid {cls.__OptDict['version_std']} requested"
|
||||||
|
)
|
||||||
return VersionStd
|
return VersionStd
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getCurrentVersion(cls,**kwargs) -> MetaVersion | str :
|
def getCurrentVersion(cls, **kwargs) -> MetaVersion | str:
|
||||||
"""
|
"""
|
||||||
get the current version or bump depending of repository state
|
get the current version or bump depending of repository state
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -478,8 +557,10 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
the last version
|
the last version
|
||||||
"""
|
"""
|
||||||
if gitversionhelper.repository.isDirty() is not False:
|
if gitversionhelper.repository.isDirty() is not False:
|
||||||
raise gitversionhelper.repository.repositoryDirty( "The repository is dirty and a current version" \
|
raise gitversionhelper.repository.repositoryDirty(
|
||||||
" can not be generated.")
|
"The repository is dirty and a current version"
|
||||||
|
" can not be generated."
|
||||||
|
)
|
||||||
saved_kwargs = copy(kwargs)
|
saved_kwargs = copy(kwargs)
|
||||||
if "formated_output" in kwargs:
|
if "formated_output" in kwargs:
|
||||||
del saved_kwargs["formated_output"]
|
del saved_kwargs["formated_output"]
|
||||||
@@ -487,23 +568,25 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
_v = cls.getLastVersion(**saved_kwargs)
|
_v = cls.getLastVersion(**saved_kwargs)
|
||||||
|
|
||||||
if not cls.__versionReseted:
|
if not cls.__versionReseted:
|
||||||
amount = gitversionhelper.tag.getDistanceFromTag(_v.raw,**kwargs)
|
amount = gitversionhelper.tag.getDistanceFromTag(_v.raw, **kwargs)
|
||||||
_v = _v.bump(amount,**saved_kwargs)
|
_v = _v.bump(amount, **saved_kwargs)
|
||||||
|
|
||||||
if ((cls.__OptDict["formated_output"] in kwargs) and (kwargs[cls.__OptDict["formated_output"]] is True)):
|
if (cls.__OptDict["formated_output"] in kwargs) and (
|
||||||
|
kwargs[cls.__OptDict["formated_output"]] is True
|
||||||
|
):
|
||||||
return _v.doFormatVersion(**kwargs)
|
return _v.doFormatVersion(**kwargs)
|
||||||
return _v
|
return _v
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getCurrentFormatedVersion(cls,**kwargs) -> str :
|
def getCurrentFormatedVersion(cls, **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
Same as getCurrentVersion() with formated_output kwarg activated
|
Same as getCurrentVersion() with formated_output kwarg activated
|
||||||
"""
|
"""
|
||||||
kwargs["formated_output"]=True
|
kwargs["formated_output"] = True
|
||||||
return cls.getCurrentVersion(kwargs)
|
return cls.getCurrentVersion(kwargs)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _parseTag(cls,tag,**kwargs): # pylint: disable=R0914, R0912, R0915
|
def _parseTag(cls, tag, **kwargs): # pylint: disable=R0914, R0912, R0915
|
||||||
"""get the last version from tags
|
"""get the last version from tags
|
||||||
Arguments:
|
Arguments:
|
||||||
tag: the tag to be parsed
|
tag: the tag to be parsed
|
||||||
@@ -518,61 +601,84 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
if VersionStd == "Auto":
|
if VersionStd == "Auto":
|
||||||
bAutoVersionStd = True
|
bAutoVersionStd = True
|
||||||
bFound = False
|
bFound = False
|
||||||
if VersionStd == "SemVer" or (bAutoVersionStd is True) :
|
if VersionStd == "SemVer" or (bAutoVersionStd is True):
|
||||||
_r=re.compile(r"^\s*" + cls.VersionStds["SemVer"]["regex"] + r"\s*$", re.VERBOSE | \
|
_r = re.compile(
|
||||||
re.IGNORECASE)
|
r"^\s*" + cls.VersionStds["SemVer"]["regex"] + r"\s*$",
|
||||||
_m = re.match(_r,tag)
|
re.VERBOSE | re.IGNORECASE,
|
||||||
|
)
|
||||||
|
_m = re.match(_r, tag)
|
||||||
if not _m:
|
if not _m:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
major, minor, patch = int(_m.group("major")),\
|
major, minor, patch = (
|
||||||
int(_m.group("minor")),\
|
int(_m.group("major")),
|
||||||
int(_m.group("patch"))
|
int(_m.group("minor")),
|
||||||
|
int(_m.group("patch")),
|
||||||
|
)
|
||||||
|
|
||||||
pre_count = 0
|
pre_count = 0
|
||||||
if _pre := _m.group("prerelease"):
|
if _pre := _m.group("prerelease"):
|
||||||
if (_match := re.search (cls.VersionStds["SemVer"]["regex_preversion_num"],_pre)) is not None:
|
if (
|
||||||
|
_match := re.search(
|
||||||
|
cls.VersionStds["SemVer"]["regex_preversion_num"], _pre
|
||||||
|
)
|
||||||
|
) is not None:
|
||||||
pre_count = int(_match.group("num"))
|
pre_count = int(_match.group("num"))
|
||||||
else:
|
else:
|
||||||
pre_count = 1
|
pre_count = 1
|
||||||
|
|
||||||
post_count = 0
|
post_count = 0
|
||||||
if _post := _m.group("buildmetadata"):
|
if _post := _m.group("buildmetadata"):
|
||||||
if (_match := re.search (cls.VersionStds["SemVer"]["regex_build_num"],_post)) is not None:
|
if (
|
||||||
|
_match := re.search(
|
||||||
|
cls.VersionStds["SemVer"]["regex_build_num"], _post
|
||||||
|
)
|
||||||
|
) is not None:
|
||||||
post_count = int(_match.group("num"))
|
post_count = int(_match.group("num"))
|
||||||
else:
|
else:
|
||||||
post_count = 1
|
post_count = 1
|
||||||
bFound = True
|
bFound = True
|
||||||
VersionStd = "SemVer"
|
VersionStd = "SemVer"
|
||||||
|
|
||||||
if VersionStd == "PEP440" or ( (bAutoVersionStd is True) and (bFound is not True)):
|
if VersionStd == "PEP440" or (
|
||||||
_r=re.compile(r"^\s*" + cls.VersionStds["PEP440"]["regex"] + r"\s*$", re.VERBOSE | \
|
(bAutoVersionStd is True) and (bFound is not True)
|
||||||
re.IGNORECASE)
|
):
|
||||||
_m = re.match(_r,tag)
|
_r = re.compile(
|
||||||
|
r"^\s*" + cls.VersionStds["PEP440"]["regex"] + r"\s*$",
|
||||||
|
re.VERBOSE | re.IGNORECASE,
|
||||||
|
)
|
||||||
|
_m = re.match(_r, tag)
|
||||||
if not _m:
|
if not _m:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
ver=_m.group("release").split(".")
|
ver = _m.group("release").split(".")
|
||||||
ver += ["0"] * (3 - len(ver))
|
ver += ["0"] * (3 - len(ver))
|
||||||
ver[0]=int(ver[0])
|
ver[0] = int(ver[0])
|
||||||
ver[1]=int(ver[1])
|
ver[1] = int(ver[1])
|
||||||
ver[2]=int(ver[2])
|
ver[2] = int(ver[2])
|
||||||
major, minor, patch = tuple(ver)
|
major, minor, patch = tuple(ver)
|
||||||
pre_count = int(_m.group("pre_n")) if _m.group("pre_n") else 0
|
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
|
post_count = int(_m.group("post_n2")) if _m.group("post_n2") else 0
|
||||||
bFound = True
|
bFound = True
|
||||||
VersionStd = "PEP440"
|
VersionStd = "PEP440"
|
||||||
|
|
||||||
if not bFound :
|
if not bFound:
|
||||||
raise gitversionhelper.version.noValidVersion("no valid version found in tags")
|
raise gitversionhelper.version.noValidVersion(
|
||||||
|
"no valid version found in tags"
|
||||||
|
)
|
||||||
|
|
||||||
if pre_count > 0 and post_count > 0:
|
if pre_count > 0 and post_count > 0:
|
||||||
raise cls.PreAndPostVersionUnsupported("can not parse a version with both pre" \
|
raise cls.PreAndPostVersionUnsupported(
|
||||||
" and post release number.")
|
"can not parse a version with both pre" " and post release number."
|
||||||
return cls.MetaVersion(VersionStd, major, minor, patch, pre_count, post_count, tag)
|
)
|
||||||
|
return cls.MetaVersion(
|
||||||
|
VersionStd, major, minor, patch, pre_count, post_count, tag
|
||||||
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def getLastVersion(cls,**kwargs) -> MetaVersion | str : # pylint: disable=R0914, R0912, R0915
|
def getLastVersion(
|
||||||
|
cls, **kwargs
|
||||||
|
) -> MetaVersion | str: # pylint: disable=R0914, R0912, R0915
|
||||||
"""get the last version from tags
|
"""get the last version from tags
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
version_std(str): the given version_std (can be None)
|
version_std(str): the given version_std (can be None)
|
||||||
@@ -582,36 +688,40 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
Returns:
|
Returns:
|
||||||
the last version
|
the last version
|
||||||
"""
|
"""
|
||||||
lastTag=cls.MetaVersion.raw
|
lastTag = cls.MetaVersion.raw
|
||||||
cls.__versionReseted = False
|
cls.__versionReseted = False
|
||||||
try:
|
try:
|
||||||
lastTag = gitversionhelper.tag.getLastTag(**kwargs)
|
lastTag = gitversionhelper.tag.getLastTag(**kwargs)
|
||||||
except gitversionhelper.tag.tagNotFound:
|
except gitversionhelper.tag.tagNotFound:
|
||||||
logging.warning('tag not found, reseting versionning')
|
logging.warning("tag not found, reseting versionning")
|
||||||
cls.__versionReseted = True
|
cls.__versionReseted = True
|
||||||
|
|
||||||
_v=None
|
_v = None
|
||||||
try:
|
try:
|
||||||
_v=cls._parseTag(lastTag,**kwargs)
|
_v = cls._parseTag(lastTag, **kwargs)
|
||||||
except gitversionhelper.version.noValidVersion as _ex:
|
except gitversionhelper.version.noValidVersion as _ex:
|
||||||
if ((cls.__OptDict["ignore_unknown_tags"] in kwargs) and (kwargs[cls.__OptDict["ignore_unknown_tags"]] is True)):
|
if (cls.__OptDict["ignore_unknown_tags"] in kwargs) and (
|
||||||
tags = gitversionhelper.tag.getTags(sort= "taggerdate",**kwargs)
|
kwargs[cls.__OptDict["ignore_unknown_tags"]] is True
|
||||||
|
):
|
||||||
|
tags = gitversionhelper.tag.getTags(sort="taggerdate", **kwargs)
|
||||||
_v = None
|
_v = None
|
||||||
for _tag in tags:
|
for _tag in tags:
|
||||||
try:
|
try:
|
||||||
_v=cls._parseTag(_tag,**kwargs)
|
_v = cls._parseTag(_tag, **kwargs)
|
||||||
break
|
break
|
||||||
except gitversionhelper.version.noValidVersion:
|
except gitversionhelper.version.noValidVersion:
|
||||||
continue
|
continue
|
||||||
if _v is None:
|
if _v is None:
|
||||||
raise gitversionhelper.version.noValidVersion() from _ex
|
raise gitversionhelper.version.noValidVersion() from _ex
|
||||||
|
|
||||||
if ((cls.__OptDict["formated_output"] in kwargs) and (kwargs[cls.__OptDict["formated_output"]] is True)):
|
if (cls.__OptDict["formated_output"] in kwargs) and (
|
||||||
|
kwargs[cls.__OptDict["formated_output"]] is True
|
||||||
|
):
|
||||||
return _v.doFormatVersion(**kwargs)
|
return _v.doFormatVersion(**kwargs)
|
||||||
return _v
|
return _v
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def doFormatVersion(cls,inputversion:MetaVersion,**kwargs) -> str:
|
def doFormatVersion(cls, inputversion: MetaVersion, **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
output a formated version string
|
output a formated version string
|
||||||
Keyword Arguments:
|
Keyword Arguments:
|
||||||
@@ -623,41 +733,45 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
VersionStd = cls._getVersionStd(**kwargs)
|
VersionStd = cls._getVersionStd(**kwargs)
|
||||||
if VersionStd=="Auto" :
|
if VersionStd == "Auto":
|
||||||
VersionStd = inputversion.version_std
|
VersionStd = inputversion.version_std
|
||||||
|
|
||||||
OutputFormat = None
|
OutputFormat = None
|
||||||
revpattern=""
|
revpattern = ""
|
||||||
revcount=""
|
revcount = ""
|
||||||
post_count = inputversion.post_count
|
post_count = inputversion.post_count
|
||||||
pre_count = inputversion.pre_count
|
pre_count = inputversion.pre_count
|
||||||
patch = inputversion.patch
|
patch = inputversion.patch
|
||||||
|
|
||||||
if cls.__OptDict["output_format"] in kwargs:
|
if cls.__OptDict["output_format"] in kwargs:
|
||||||
OutputFormat=kwargs[cls.__OptDict["output_format"]]
|
OutputFormat = kwargs[cls.__OptDict["output_format"]]
|
||||||
|
|
||||||
if OutputFormat is None:
|
if OutputFormat is None:
|
||||||
OutputFormat = "{major}.{minor}.{patch}{revpattern}{revcount}"
|
OutputFormat = "{major}.{minor}.{patch}{revpattern}{revcount}"
|
||||||
if post_count > 0 and pre_count > 0:
|
if post_count > 0 and pre_count > 0:
|
||||||
raise gitversionhelper.version.PreAndPostVersionUnsupported("cannot output a version with both pre " \
|
raise gitversionhelper.version.PreAndPostVersionUnsupported(
|
||||||
"and post release number.")
|
"cannot output a version with both pre "
|
||||||
if VersionStd == "PEP440":
|
"and post release number."
|
||||||
|
)
|
||||||
|
if VersionStd == "PEP440":
|
||||||
if post_count > 0:
|
if post_count > 0:
|
||||||
revpattern=".post"
|
revpattern = ".post"
|
||||||
revcount=f"{post_count}"
|
revcount = f"{post_count}"
|
||||||
elif pre_count > 0:
|
elif pre_count > 0:
|
||||||
revpattern=".pre"
|
revpattern = ".pre"
|
||||||
revcount=f"{pre_count}"
|
revcount = f"{pre_count}"
|
||||||
#elif VersionStd == "SemVer":
|
# elif VersionStd == "SemVer":
|
||||||
else:
|
else:
|
||||||
if post_count > 0:
|
if post_count > 0:
|
||||||
revpattern="+post"
|
revpattern = "+post"
|
||||||
revcount=f".{post_count}"
|
revcount = f".{post_count}"
|
||||||
elif pre_count > 0:
|
elif pre_count > 0:
|
||||||
revpattern="-pre"
|
revpattern = "-pre"
|
||||||
revcount=f".{pre_count}"
|
revcount = f".{pre_count}"
|
||||||
return OutputFormat.format( major=inputversion.major, \
|
return OutputFormat.format(
|
||||||
minor=inputversion.minor, \
|
major=inputversion.major,
|
||||||
patch=patch, \
|
minor=inputversion.minor,
|
||||||
revpattern=revpattern, \
|
patch=patch,
|
||||||
revcount=revcount)
|
revpattern=revpattern,
|
||||||
|
revcount=revcount,
|
||||||
|
)
|
||||||
|
|||||||
@@ -4,4 +4,4 @@
|
|||||||
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
|
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Unported License.
|
||||||
#
|
#
|
||||||
# You should have received a copy of the license along with this
|
# You should have received a copy of the license along with this
|
||||||
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
|
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.
|
||||||
|
|||||||
@@ -97,6 +97,7 @@ class Test_gitversionhelper(unittest.TestCase):
|
|||||||
self._test_version_readback_simple("1.1.1")
|
self._test_version_readback_simple("1.1.1")
|
||||||
def test_nominal__version__auto_9(self):
|
def test_nominal__version__auto_9(self):
|
||||||
self._test_version_readback_simple("1.2.1")
|
self._test_version_readback_simple("1.2.1")
|
||||||
|
|
||||||
def test_nominal__version__auto_PEP440_post(self):
|
def test_nominal__version__auto_PEP440_post(self):
|
||||||
self._test_version_readback_simple("1.2.1.post1")
|
self._test_version_readback_simple("1.2.1.post1")
|
||||||
def test_nominal__version__auto_PEP440_pre(self):
|
def test_nominal__version__auto_PEP440_pre(self):
|
||||||
|
|||||||
Reference in New Issue
Block a user