Compare commits

..

24 Commits

Author SHA1 Message Date
f5d61d8d04 Merge pull request 'fix: twine cmd line' (#24) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/24
new-tag: 1.0.8
2023-03-22 10:49:23 +01:00
d21c839f07 Merge pull request 'dev' (#23) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/23
new-tag: 1.0.7
2023-03-22 10:03:04 +01:00
6542c80e8f Merge pull request 'fix usernamePassword in jenkins' (#22) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/22
new-tag:1.0.6
2023-03-22 01:00:21 +01:00
4272a55dde Merge pull request 'dev' (#21) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/21
new-tag:1.0.5
2023-03-22 00:49:37 +01:00
382e39e684 Merge pull request 'dev' (#20) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/20
new-tag:1.0.4
2023-03-20 10:12:13 +01:00
34c07e0d9f Merge pull request 'escape toml' (#19) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/19
new-tag:1.0.3
2023-03-20 01:16:37 +01:00
2c9886b251 Merge pull request 'test: tag_regex to extract verison only' (#18) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/18
new-tag:1.0.4
2023-03-20 01:14:17 +01:00
782562eef8 Merge pull request 'dev' (#17) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/17
new-tag:1.0.3
2023-03-20 00:15:31 +01:00
82c32ff58c Merge pull request 'dev' (#16) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/16
new-tag:1.0.2
2023-03-19 22:59:59 +01:00
794e54c88b Merge pull request 'dev' (#15) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/15
new-tag:1.0.1
2023-03-19 21:58:48 +01:00
078f5624b2 Merge pull request 'fix: project username' (#14) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/14
new-tag: 1.0.0
2023-03-19 21:02:07 +01:00
44c10b88a5 Merge pull request 'fix: typo in jenkins pipeline file' (#13) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/13
new-tag: 1.0.0
2023-03-19 20:57:20 +01:00
a4b7b27a65 Merge pull request 'dev' (#12) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/12
new-tag:1.0.0
2023-03-19 20:53:01 +01:00
77e2be2714 Merge pull request 'fix: remove branch on git push (useless)' (#11) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/11
new-tag:1.0.0
2023-03-19 20:41:37 +01:00
f422b9ff7d Merge pull request 'fix git tag cmd' (#10) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/10
new-tag:1.0.0
2023-03-19 20:34:23 +01:00
660270d49b Merge pull request 'fix git username/address in jenkinsfile' (#9) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/9
new-tag:1.0.0
2023-03-19 20:29:40 +01:00
9f442a7b8e Merge pull request 'update jenkinsfile' (#8) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/8
new-tag:1.0.0
2023-03-19 20:24:31 +01:00
8fb9ba8406 Merge pull request 'dev' (#7) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/7
2023-03-19 20:02:38 +01:00
38abaa58c5 Merge pull request 'fix deps' (#6) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/6
2023-03-19 19:47:06 +01:00
35d75ea019 Merge pull request 'dev' (#5) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/5
2023-03-19 19:43:17 +01:00
0b8651a30a Merge pull request 'dev' (#4) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/4
2023-03-19 19:22:48 +01:00
c5b3055bfe Merge pull request 'feature: add log-line in pipeline' (#3) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/3
2023-03-19 11:39:08 +01:00
92a1d1a30f Merge pull request 'update jenkinsFile' (#2) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/2
2023-03-19 11:29:50 +01:00
f2c0bf1ddd Merge pull request 'bump master release' (#1) from dev into master
Reviewed-on: https://chacha.ddns.net/gitea/chacha/pygitversionhelper/pulls/1
2023-03-19 11:23:54 +01:00
15 changed files with 962 additions and 1025 deletions

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>pygitversionhelper</name>
<name>gitversionhelper</name>
<comment></comment>
<projects>
</projects>

103
Jenkinsfile vendored
View File

@@ -6,13 +6,7 @@
// 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/>.
import groovy.xml.XmlUtil
import static javax.xml.xpath.XPathConstants.*
import javax.xml.xpath.*
import groovy.xml.DOMBuilder
import groovy.xml.dom.DOMCategory
import java.math.RoundingMode
import java.math.BigDecimal
// configurable settings:
// use to send email if workflow problem
@@ -34,11 +28,6 @@ def _MkDocsWebURL = "dabauto--mkdocs-web.dmz.chacha.home/mkdocs-web/"
def _MkDocsWebCredentials = "2c5b684e-3787-4b37-8aca-b3dd4a383fe2"
def _PypiCredentials = "Pypi"
def badge_coverage = addEmbeddableBadgeConfiguration(id: "coverage", subject: "coverage")
def badge_maintainability = addEmbeddableBadgeConfiguration(id: "maintainability", subject: "maintainability")
def badge_quality = addEmbeddableBadgeConfiguration(id: "quality", subject: "quality score")
// commands Helper: /!\ Made for GITEA /!\
String determineRepoUserName() {
return scm.getUserRemoteConfigs()[0].getUrl().tokenize('/')[3].split("\\.")[0]
@@ -74,46 +63,6 @@ String ExtractBaseVersion(inVersion) {
return matcher[0][1]
}
int GetCoverageValue(String CoverageFilePath,String XPath)
{
//File file = new File(CoverageFilePath)
//coverageReportRaw = file.getText('UTF-8')
coverageReportRaw = readFile(CoverageFilePath)
coverageReport = DOMBuilder.parse(new StringReader(coverageReportRaw), false, false)
coverageReportRoot = coverageReport.documentElement
def xpath = XPathFactory.newInstance().newXPath()
res = xpath.evaluate(XPath,coverageReportRoot,NUMBER)
return res
}
String getColorScale(BigDecimal value)
{
if( value >9) { return "Goldenrod"}
else if( value >6) { return "seagreen"}
else if( value >4) { return "orange"}
else if( value >2) { return "darkred"}
else { return "dimgrey"}
}
String getColorScale_reversed(BigDecimal value)
{
if( value >9) { return "dimgrey"}
else if( value >6) { return "darkred"}
else if( value >4) { return "orange"}
else if( value >2) { return "seagreen"}
else { return "Goldenrod"}
}
int GetCoverageValue_lines_valid(String CoverageFilePath) { return GetCoverageValue(CoverageFilePath,"/coverage/@lines-valid") }
int GetCoverageValue_lines_covered(String CoverageFilePath) { return GetCoverageValue(CoverageFilePath,"/coverage/@lines-covered") }
int GetCoverageValue_line_rate(String CoverageFilePath) { return GetCoverageValue(CoverageFilePath,"/coverage/@line-rate") }
int GetCoverageValue_branches_valid(String CoverageFilePath) { return GetCoverageValue(CoverageFilePath,"/coverage/@branches-valid") }
int GetCoverageValue_branches_covered(String CoverageFilePath) { return GetCoverageValue(CoverageFilePath,"/coverage/@branches-covered") }
int GetCoverageValue_branch_rate(String CoverageFilePath) { return GetCoverageValue(CoverageFilePath,"/coverage/@branch-rate") }
int GetCoverageValue_complexity(String CoverageFilePath) { return GetCoverageValue(CoverageFilePath,"/coverage/@complexity") }
pipeline {
// for Docker based build (preferable)
@@ -188,7 +137,7 @@ pipeline {
script {
if(_PROJECT_NAME!="pygitversionhelper") {
sh(". ~/TOOLS_ENV/bin/activate && pip install pygitversionhelper")
sh(". ~/TOOLS_ENV/bin/activate && pip install git+https://chacha.ddns.net/gitea/chacha/pygitversionhelper.git@master")
}
else
{
@@ -375,7 +324,7 @@ pipeline {
def wheelPath = findFiles(glob: "**/dist/*.whl")[0]
echo "wheel artifact path: $wheelPath"
// install the package, with *test* optionnal packages, as user
sh(". ~/TEST_ENV/bin/activate && pip install --find-links dist/ ${PY_PROJECT_NAME} .[test,coverage-check,quality-check,type-check,doc-gen,complexity-check]")
sh(". ~/TEST_ENV/bin/activate && pip install --find-links dist/ ${PY_PROJECT_NAME} .[test,coverage-check,quality-check,type-check,doc-gen]")
}
}
}
@@ -385,14 +334,6 @@ pipeline {
steps {
dir("gitrepo") {
sh(". ~/TEST_ENV/bin/activate && python -m helpers --type-check --quality-check")
script {
def jsonObj = readJSON file: "helpers-results/quality_check/metrics.json"
quality_score = new BigDecimal(jsonObj["GlobalScore"])
sz_quality_score = quality_score.setScale(2, RoundingMode.HALF_EVEN).toString()
badge_quality.setStatus(sz_quality_score)
badge_quality.setColor(getColorScale(quality_score))
}
sh(". ~/TEST_ENV/bin/activate && python -m helpers --complexity-check")
}
}
post {
@@ -447,14 +388,6 @@ pipeline {
style: 'stackedArea',
keepRecords: true,
numBuilds: ''])
plot([ csvFileName: 'plot-4ceb9ee2-ca78-11ed-afa1-0242ac120002.csv',
csvSeries: [[ file: 'gitrepo/helpers-results/complexity_check/MI.csv', inclusionFlag: 'INCLUDE_BY_STRING',exclusionValues: 'MeanMaintainability', url: '']],
group: 'metrics',
title: 'maintainability',
style: 'stackedArea',
keepRecords: true,
numBuilds: ''])
}
}
@@ -467,36 +400,6 @@ pipeline {
println unit_test_full_name__html
unit_test_full_name__xml=findFiles(glob: "helpers-results/unit_test_full/*.xml")[0].getName()
println unit_test_full_name__xml
coverage_report_path = "helpers-results/unit_test_coverage/test_coverage.xml"
println GetCoverageValue_lines_valid(coverage_report_path)
println GetCoverageValue_lines_covered(coverage_report_path)
println GetCoverageValue_line_rate(coverage_report_path)
println GetCoverageValue_branches_valid(coverage_report_path)
println GetCoverageValue_branches_covered(coverage_report_path)
println GetCoverageValue_branch_rate(coverage_report_path)
println GetCoverageValue_complexity(coverage_report_path)
full_rate = new BigDecimal( 10*(GetCoverageValue_line_rate(coverage_report_path) + GetCoverageValue_branch_rate(coverage_report_path)) / 2 )
sz_full_rate = full_rate.setScale(2, RoundingMode.HALF_EVEN).toString()
badge_coverage.setStatus(sz_full_rate)
badge_coverage.setColor(getColorScale(full_rate))
//complexity = new BigDecimal( 10*GetCoverageValue_complexity(coverage_report_path))
//sz_complexity = complexity.setScale(2, RoundingMode.HALF_EVEN).toString()
//badge_complexity.setStatus(sz_complexity)
//badge_quality.setColor(getColorScale_reversed(complexity))
//badge_maintainability
records = readCSV file: 'helpers-results/complexity_check/MI.csv'
maintainability = records[1][1]
badge_maintainability.setStatus(maintainability)
if ( maintainability == 'D') { badge_maintainability.setColor( "dimgrey")}
else if( maintainability == 'C') { badge_maintainability.setColor( "darkred")}
else if( maintainability == 'B') { badge_maintainability.setColor( "orange")}
else if( maintainability == 'A') { badge_maintainability.setColor( "seagreen")}
else if( maintainability == 'A+') { badge_maintainability.setColor( "Goldenrod")}
}
}
}

View File

@@ -1,10 +1,5 @@
![](https://chacha.ddns.net/jenkins/buildStatus/icon?subject=status&status=active&color=seagreen)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?subject=doc&status=MkDocs&color=blue)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?subject=jenkins-unittest&job={{repository}}-{{branch}})
![](https://chacha.ddns.net/jenkins/buildStatus/icon?job={{repository}}-{{branch}}&build=0&config=coverage)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?job={{repository}}-{{branch}}&build=0&config=maintainability)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?job={{repository}}-{{branch}}&build=0&config=quality)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?subject=licence&status=CC%20BY-NC-SA%204.0&color=teal)
![](https://chacha.ddns.net/jenkins/buildStatus/icon?subject=licence&status=CC%20BY-NC-SA%204.0&color=blue)
![](docs-static/Library.jpg)
@@ -24,7 +19,6 @@ Checkout [Latest Documentation](https://chacha.ddns.net/mkdocs-web/chacha/pygitv
- get current version (bumped)
- convert / switch from SemVer to PEP440 (both ways)
- automatic version format detection (SemVer by default)
- Get commit message history
## Options
- restrict to same branch

View File

@@ -4,4 +4,4 @@
# 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/>.
# work. If not, see <https://creativecommons.org/licenses/by-nc-sa/4.0/>.

View File

@@ -23,7 +23,6 @@ if __package__ == "helpers":
from .unit_test import unit_test
from .doc_gen import doc_gen
from .changelog_gen import changelog_gen
from .complexity_check import complexity_check
else:
# when calling the __main__.py file (from IDE)
from helpers.types_check import types_check
@@ -31,7 +30,6 @@ else:
from helpers.unit_test import unit_test
from helpers.doc_gen import doc_gen
from helpers.changelog_gen import changelog_gen
from helpers.complexity_check import complexity_check
logging.getLogger().setLevel(logging.INFO)
@@ -42,26 +40,63 @@ if __name__ == "__main__":
pyproject = tomli.load(fp)
parser = argparse.ArgumentParser(
prog="continuous-integration-helper", description="A tiny set of scripts to help continous integration on python"
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)"
"-tc",
"--type-check",
dest="typecheck",
action="store_true",
help="enable static typing check",
)
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)"
"-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("-clg", "--changelog-gen", dest="changeloggen", action="store_true", help="enable changelog generation")
parser.add_argument(
"-qc",
"--quality-check",
dest="qualitycheck",
action="store_true",
help="enable code quality check",
)
parser.add_argument("-cpc", "--complexity-check", dest="complexitycheck", action="store_true", help="enable complexity 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()
@@ -77,7 +112,6 @@ if __name__ == "__main__":
# args.docgen = True
# args.docgenpdf = True
# args.changeloggen = True
# args.complexitycheck = True
helpers = []
if args.typecheck == True:
@@ -107,9 +141,6 @@ if __name__ == "__main__":
if args.changeloggen == True:
helpers.append(changelog_gen)
if args.complexitycheck == True:
helpers.append(complexity_check)
for helper in helpers:
helper.set_context(project_rootdir_path, pyproject)
helper.reset_result_dir()

View File

@@ -1,70 +0,0 @@
# 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/>.
from __future__ import annotations
from typing import TYPE_CHECKING
# from pathlib import Path
# import os
import statistics
import csv
from json import loads as JSON_LOADS
from radon.complexity import cc_rank, SCORE
from radon.cli import Config
from radon.cli.harvest import CCHarvester, HCHarvester, MIHarvester
from .helper_base import helper_withresults_base
from pprint import pprint
class complexity_check(helper_withresults_base):
@classmethod
def do_job(cls):
config = Config(
exclude="__init__\.py",
ignore=None,
order=SCORE,
show_closures=False,
no_assert=True,
min="A",
max="F",
multi=False,
)
h = MIHarvester([str(_) for _ in sorted((cls.project_rootdir_path / "src").rglob("*.py"))], config).as_json()
res = JSON_LOADS(h)
with open(cls.get_result_dir() / "MI.json", "w", newline="") as oFile:
oFile.write(h)
mean = statistics.mean(_["mi"] for _ in res.values())
if mean >= 65:
rank = "A+"
elif mean >= 20:
rank = "A"
elif mean >= 10:
rank = "B"
else:
rank = "C"
RES_MI = {"MeanMaintainability": mean, "MaintainabilityIndex": rank}
with open(cls.get_result_dir() / "MI.csv", "w", newline="") as oFile:
writer = csv.DictWriter(oFile, fieldnames=RES_MI.keys())
writer.writeheader()
writer.writerow(RES_MI)
config = Config(exclude=None, ignore=None, order=SCORE, show_closures=False, no_assert=True, min="A", max="F", multi=False)
h = CCHarvester([str(_) for _ in sorted((cls.project_rootdir_path / "src").rglob("*.py"))], config).as_json()
with open(cls.get_result_dir() / "CC.json", "w", newline="") as oFile:
oFile.write(h)
config = Config(exclude=None, ignore=None, order=SCORE, show_closures=False, no_assert=True, min="A", max="F", by_function=None)
h = HCHarvester([str(_) for _ in sorted((cls.project_rootdir_path / "src").rglob("*.py"))], config).as_json()
with open(cls.get_result_dir() / "HC.json", "w", newline="") as oFile:
oFile.write(h)

View File

@@ -31,6 +31,8 @@ class doc_gen(helper_withresults_base):
@classmethod
def do_job(cls):
print(cls.project_rootdir_path)
print()
# create doc root dir
doc_path = cls.project_rootdir_path / "docs"
@@ -40,8 +42,12 @@ class doc_gen(helper_withresults_base):
cls._reset_dir(site_path)
# copy files from main project dir
shutil.copyfile(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"))
shutil.copyfile(
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_tree(str(cls.project_rootdir_path / "docs-static"), str(doc_path))
@@ -51,8 +57,12 @@ class doc_gen(helper_withresults_base):
cls._reset_dir(reference_path)
for path in sorted((cls.project_rootdir_path / "src").rglob("*.py")):
module_path = path.relative_to(cls.project_rootdir_path / "src").with_suffix("")
doc_path = path.relative_to(cls.project_rootdir_path / "src").with_suffix(".md")
module_path = path.relative_to(
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)
parts = list(module_path.parts)
@@ -67,7 +77,16 @@ class doc_gen(helper_withresults_base):
identifier = "src." + ".".join(parts)
print("::: " + identifier, file=fd)
cmdopts = [f"{sys.executable}", "-m", "mkdocs", "-v", "build", "--site-dir", str(site_path), "--clean"]
cmdopts = [
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
# => reason is mkdocs seems to try loading the plugin even if we disable it, so we need to
@@ -81,9 +100,12 @@ class doc_gen(helper_withresults_base):
{
"with-pdf": {
"cover_subtitle": "User Manual",
"cover_logo": str(cls.project_rootdir_path / "docs-static" / "Library.jpg"),
"cover_logo": str(
cls.project_rootdir_path / "docs-static" / "Library.jpg"
),
"verbose": False,
"media_type": "print",
"headless_chrome_path": "chromium",
"exclude_pages": ["LICENSE"],
"output_path": str(site_path / "pdf" / "manual.pdf"),
}
@@ -97,7 +119,11 @@ class doc_gen(helper_withresults_base):
break
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)
print(res.decode())

View File

@@ -53,7 +53,13 @@ class helper_base(ABC):
@classmethod
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
@classmethod
@@ -71,4 +77,8 @@ class helper_withresults_base(helper_base):
def get_result_dir(cls):
if cls.helper_results_dir == None:
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
)

View File

@@ -37,7 +37,9 @@ class quality_check(helper_withresults_base):
def GetPylintMessageList(cls):
Messagelist = dict()
regex = r"^:([a-zA-Z-]+) \(([^\)]+)\)"
for line in cls.run_cmd([sys.executable, "-m", "pylint", "--list-msgs"]).splitlines():
for line in cls.run_cmd(
[sys.executable, "-m", "pylint", "--list-msgs"]
).splitlines():
if res := re.search(regex, line.decode()):
Messagelist[res.group(1)] = res.group(2)
cls.PylintMessageList = Messagelist
@@ -60,7 +62,6 @@ class quality_check(helper_withresults_base):
with redirect_stdout(StdOutput):
pylint_Run(
[
"--load-plugins=pylint.extensions.mccabe",
"--output-format=json,parseable",
"--disable=invalid-name",
"--ignore=_version.py",
@@ -72,7 +73,9 @@ class quality_check(helper_withresults_base):
exit=False,
)
with open(cls.get_result_dir() / "report.json", "w+", encoding="utf-8") as Outfile:
with open(
cls.get_result_dir() / "report.json", "w+", encoding="utf-8"
) as Outfile:
# hacky way of exctracting json + having overall score...
class TScanState(Enum):
TEXT_REPORT = 1
@@ -119,45 +122,81 @@ class quality_check(helper_withresults_base):
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(
r"^(\d+)(?= lines have been analyzed)", line
):
RES_all["NbAnalysedLines"] = float(res.group(1))
elif line == "Raw metrics":
ScanState = TScanState.OTHER_REPORT_METRICS
else:
with suppress(PyLintMetricNotFound):
RES_all["Statistics"]["module"] = cls.TryExtractPYReportMetric(line, "module")
RES_all["Statistics"][
"module"
] = cls.TryExtractPYReportMetric(line, "module")
with suppress(PyLintMetricNotFound):
RES_all["Statistics"]["class"] = cls.TryExtractPYReportMetric(line, "class")
RES_all["Statistics"][
"class"
] = cls.TryExtractPYReportMetric(line, "class")
with suppress(PyLintMetricNotFound):
RES_all["Statistics"]["method"] = cls.TryExtractPYReportMetric(line, "method")
RES_all["Statistics"][
"method"
] = cls.TryExtractPYReportMetric(line, "method")
with suppress(PyLintMetricNotFound):
RES_all["Statistics"]["function"] = cls.TryExtractPYReportMetric(line, "function")
RES_all["Statistics"][
"function"
] = cls.TryExtractPYReportMetric(line, "function")
elif ScanState == TScanState.OTHER_REPORT_METRICS:
if line == "Duplication":
RES_all["RawMetricsPercent"]["code"] = RES_all["RawMetrics"]["code"] / 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"]
RES_all["RawMetricsPercent"]["code"] = (
RES_all["RawMetrics"]["code"]
/ 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
else:
with suppress(PyLintMetricNotFound):
RES_all["RawMetrics"]["code"] = cls.TryExtractPYReportMetric(line, "code")
RES_all["RawMetrics"][
"code"
] = cls.TryExtractPYReportMetric(line, "code")
with suppress(PyLintMetricNotFound):
RES_all["RawMetrics"]["docstring"] = cls.TryExtractPYReportMetric(line, "docstring")
RES_all["RawMetrics"][
"docstring"
] = cls.TryExtractPYReportMetric(line, "docstring")
with suppress(PyLintMetricNotFound):
RES_all["RawMetrics"]["comment"] = cls.TryExtractPYReportMetric(line, "comment")
RES_all["RawMetrics"][
"comment"
] = cls.TryExtractPYReportMetric(line, "comment")
with suppress(PyLintMetricNotFound):
RES_all["RawMetrics"]["empty"] = cls.TryExtractPYReportMetric(line, "empty")
RES_all["RawMetrics"][
"empty"
] = cls.TryExtractPYReportMetric(line, "empty")
elif ScanState == TScanState.OTHER_REPORT_DUPLICATION:
if line == "Messages by category":
ScanState = TScanState.OTHER_REPORT_MESSAGES_CAT
else:
with suppress(PyLintMetricNotFound):
RES_all["Duplication"]["NbDupLines"] = cls.TryExtractPYReportMetric(line, "nb duplicated lines")
RES_all["Duplication"][
"NbDupLines"
] = cls.TryExtractPYReportMetric(
line, "nb duplicated lines"
)
with suppress(PyLintMetricNotFound):
RES_all["Duplication"]["PersentDuplicatedLines"] = cls.TryExtractPYReportMetric(
RES_all["Duplication"][
"PersentDuplicatedLines"
] = cls.TryExtractPYReportMetric(
line, "percent duplicated lines"
)
@@ -166,13 +205,21 @@ class quality_check(helper_withresults_base):
ScanState = TScanState.OTHER_REPORT_MESSAGES
else:
with suppress(PyLintMetricNotFound):
RES_all["MessagesCat"]["Convention"] = cls.TryExtractPYReportMetric(line, "convention")
RES_all["MessagesCat"][
"Convention"
] = cls.TryExtractPYReportMetric(line, "convention")
with suppress(PyLintMetricNotFound):
RES_all["MessagesCat"]["Refactor"] = cls.TryExtractPYReportMetric(line, "refactor")
RES_all["MessagesCat"][
"Refactor"
] = cls.TryExtractPYReportMetric(line, "refactor")
with suppress(PyLintMetricNotFound):
RES_all["MessagesCat"]["Warning"] = cls.TryExtractPYReportMetric(line, "warning")
RES_all["MessagesCat"][
"Warning"
] = cls.TryExtractPYReportMetric(line, "warning")
with suppress(PyLintMetricNotFound):
RES_all["MessagesCat"]["Error"] = cls.TryExtractPYReportMetric(line, "error")
RES_all["MessagesCat"][
"Error"
] = cls.TryExtractPYReportMetric(line, "error")
elif ScanState == TScanState.OTHER_REPORT_MESSAGES:
# approx match because the number of '-' depend on screen width..
@@ -181,10 +228,16 @@ class quality_check(helper_withresults_base):
else:
for PylintMessage in cls.PylintMessageList.keys():
with suppress(PyLintMetricNotFound):
RES_all["Messages"][PylintMessage] = cls.TryExtractPYReportMetric(line, PylintMessage)
RES_all["Messages"][
PylintMessage
] = cls.TryExtractPYReportMetric(
line, PylintMessage
)
elif ScanState == TScanState.OTHER_REPORT_END:
if res := re.search(r"(?<=Your code has been rated at )(\d+(?:\.\d+)?)/10", line):
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:
@@ -198,7 +251,9 @@ class quality_check(helper_withresults_base):
# => to export a working full csv we need to a 'flat' dict (no more nested dict)
RES_all_trim = copy.deepcopy(RES_all)
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"
)[0]
with open(cls.get_result_dir() / "metrics.csv", "w", newline="") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=flat_RES_all.keys())
@@ -207,7 +262,9 @@ class quality_check(helper_withresults_base):
# splited csv exports for jenkins plots: RawMetricsPercent
RES_all_percent = RES_all["RawMetricsPercent"]
with open(cls.get_result_dir() / "metrics_rawpercent.csv", "w", newline="") as csv_file:
with open(
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.writerow(RES_all_percent)
@@ -215,30 +272,40 @@ class quality_check(helper_withresults_base):
# splited csv exports for jenkins plots: Statistics + Duplication + NbAnalysedStatments + NbAnalysedLines
RES_all_stats = copy.deepcopy(RES_all["Statistics"])
RES_all_stats["NbDupLines"] = RES_all["Duplication"]["NbDupLines"]
RES_all_stats["PersentDuplicatedLines"] = RES_all["Duplication"]["PersentDuplicatedLines"]
RES_all_stats["PersentDuplicatedLines"] = RES_all["Duplication"][
"PersentDuplicatedLines"
]
RES_all_stats["NbAnalysedStatments"] = RES_all["NbAnalysedStatments"]
RES_all_stats["NbAnalysedLines"] = RES_all["NbAnalysedLines"]
with open(cls.get_result_dir() / "metrics_Statistics.csv", "w", newline="") as csv_file:
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.writerow(RES_all_stats)
# splited csv exports for jenkins plots: Statistics + Duplication
RES_all_MessagesCat = RES_all["MessagesCat"]
with open(cls.get_result_dir() / "metrics_MessagesCat.csv", "w", newline="") as csv_file:
with open(
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.writerow(RES_all_MessagesCat)
# splited csv exports for jenkins plots: GlobalScore
RES_GlobalScore = {"GlobalScore": RES_all["GlobalScore"]}
with open(cls.get_result_dir() / "metrics_GlobalScore.csv", "w", newline="") as csv_file:
with open(
cls.get_result_dir() / "metrics_GlobalScore.csv", "w", newline=""
) as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=RES_GlobalScore.keys())
writer.writeheader()
writer.writerow(RES_GlobalScore)
# 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)
report = pylint_json2html.Report(raw_data)
Outfile.write(report.render())

View File

@@ -40,11 +40,16 @@ class unit_test(helper_withresults_base):
# we start coverage now because module files discovery is part of the coverage measurement
CoverageReportPath = Path(str(cls.get_result_dir()) + "_coverage")
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()
package_tests = test_loader.discover(
start_dir=str(cls.project_rootdir_path / "test"), top_level_dir=str(cls.project_rootdir_path / "test")
start_dir=str(cls.project_rootdir_path / "test"),
top_level_dir=str(cls.project_rootdir_path / "test"),
)
if cls.enable_xml_export:
testRunner = xmlrunner.XMLTestRunner(output=str(str(cls.get_result_dir())))
@@ -59,7 +64,9 @@ class unit_test(helper_withresults_base):
cov.stop()
cov.save()
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)
if cls.enable_full_xml_export == True:
@@ -68,14 +75,22 @@ class unit_test(helper_withresults_base):
cls._reset_dir(FullReportPath)
FullJUnitReport = JUnitXml()
for fname in [fname for fname in os.listdir(cls.get_result_dir()) if fname.endswith(".xml")]:
for fname in [
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")
full_report_base_name = f'{cls.pyproject["project"]["name"]}-{cls.FullReportName}-{current_datetime}'
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()
with open(FullReportPath / f"{full_report_base_name}.html", "wb") as outfile:
with open(
FullReportPath / f"{full_report_base_name}.html", "wb"
) as outfile:
outfile.write(html.encode("utf-8"))
print("Done")

View File

@@ -1,11 +1,3 @@
# 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
site_name: pygitversionhelper
site_url: 'https://chacha.ddns.net/mkdocs-web/chacha/pygitversionhelper/latest/'

View File

@@ -12,6 +12,7 @@ build-backend = "setuptools.build_meta"
[tool.setuptools_scm]
version_scheme= "post-release"
# tag_regex="^(?:v)?(?P<version>\\d+\\.\\d+\\.\\d+)([\\.\\-\\+])?(?:.*)?"
[project]
name = "pygitversionhelper"
@@ -56,7 +57,6 @@ Tracker = "https://chacha.ddns.net/gitea/chacha/pygitversionhelper/issue
[project.optional-dependencies]
test = ["junitparser>=2.8","junit2html>=30.1","xmlrunner>=1.7","mypy>=0.99" ]
coverage-check = ["coverage>=7.0"]
complexity-check = ["radon>=5.1"]
quality-check = ["pylint>=2.15","pylint-json2html>=0.4","pandas>=1.5"]
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","pymdown-extensions>=9","mkdocs-markdownextradata-plugin","mkdocs-mermaid2-plugin"]

View File

@@ -14,9 +14,8 @@ from importlib.metadata import version, PackageNotFoundError
try: # pragma: no cover
__version__ = version("pygitversionhelper")
except PackageNotFoundError: # pragma: no cover
except PackageNotFoundError: # pragma: no cover
import warnings
warnings.warn("can not read __version__, assuming local test context, setting it to ?.?.?")
__version__ = "?.?.?"

View File

@@ -37,7 +37,9 @@ import logging
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
Args:
@@ -58,9 +60,9 @@ def _exec(cmd: str, root: str | os.PathLike | None = None, raw: bool = False) ->
)
if re.search("not a git repository", p.stderr):
raise gitversionhelper.repository.notAGitRepository()
if re.search("fatal:", p.stderr):
if re.search("fatal:", p.stderr): # pragma: nocover
raise gitversionhelper.unknownGITFatalError(p.stderr)
if int(p.returncode) < 0:
if int(p.returncode) < 0: # pragma: nocover
raise gitversionhelper.unknownGITError(p.stderr)
if raw:
@@ -145,7 +147,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
def getMessagesSinceTag(cls, tag: str, **kwargs) -> str:
"""
retrieve a commits message history from repository
from Latest commit to the given tag
from LastCommit to the given tag
Keyword Arguments:
merged_output: output one single merged string
same_branch(bool): force searching only in the same branch
@@ -155,15 +157,23 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
current_commit_id = cls.getLast(**kwargs)
tag_commit_id = cls.getFromTag(tag)
if (cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True):
commits = _exec(f"git rev-list --first-parent --ancestry-path {tag_commit_id}..{current_commit_id}")
if (cls.__OptDict["same_branch"] in kwargs) and (
kwargs[cls.__OptDict["same_branch"]] is True
):
commits = _exec(
f"git rev-list --first-parent --ancestry-path {tag_commit_id}..{current_commit_id}"
)
else:
commits = _exec(f"git rev-list --ancestry-path {tag_commit_id}..{current_commit_id}")
commits = _exec(
f"git rev-list --ancestry-path {tag_commit_id}..{current_commit_id}"
)
result = []
for commit in commits:
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")
return os.linesep.join(result)
return result
@@ -214,13 +224,19 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
Returns:
the commit Id
"""
if (cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True):
if (cls.__OptDict["same_branch"] in kwargs) and (
kwargs[cls.__OptDict["same_branch"]] is True
):
try:
res = _exec("git rev-parse HEAD")
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:
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:
raise cls.commitNotFound("no commit found in commit history")
@@ -270,21 +286,29 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
if sort not in cls.__validGitTagSort:
raise gitversionhelper.wrongArguments("sort option not in allowed list")
if (cls.__OptDict["same_branch"] in kwargs) and (kwargs[cls.__OptDict["same_branch"]] is True):
if (cls.__OptDict["same_branch"] in kwargs) and (
kwargs[cls.__OptDict["same_branch"]] is True
):
currentBranch = _exec("git rev-parse --abbrev-ref HEAD")
return list(reversed(_exec(f"git tag --merged {currentBranch[0]} --sort={sort}")))
return list(
reversed(
_exec(f"git tag --merged {currentBranch[0]} --sort={sort}")
)
)
return list(reversed(_exec(f"git tag -l --sort={sort}")))
@classmethod
def getLastTag(cls, **kwargs) -> str | None:
"""
retrieve the Latest tag from a repository
retrieve the last tag from a repository
Keyword Arguments:
same_branch(bool): force searching only in the same branch
Returns:
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")
else:
res = _exec("git rev-list --tags --date-order --max-count=1")
@@ -293,14 +317,14 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
if len(res) == 0:
raise cls.tagNotFound("no tag found in commit history")
if len(res) != 1:
if len(res) != 1: # pragma: nocover
raise cls.moreThanOneTag("multiple tags on same commit is unsupported")
return res[0]
@classmethod
def getDistanceFromTag(cls, tag: str = None, **kwargs) -> int:
"""
retrieve the distance between Latest commit and tag in the repository
retrieve the distance between HEAD and tag in the repository
Arguments:
tag: reference tag, if None the most recent one will be used
Keyword Arguments:
@@ -404,10 +428,15 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
"""
BumpDevStrategy = cls.DefaultBumpDevStrategy
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"]]
else:
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['bump_type']} requested")
raise gitversionhelper.wrongArguments(
f"invalid {cls.__OptDict['bump_type']} requested"
)
return BumpDevStrategy
@classmethod
@@ -424,10 +453,14 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
if kwargs[cls.__OptDict["bump_type"]] in cls.BumpTypes:
BumpType = kwargs[cls.__OptDict["bump_type"]]
else:
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['bump_type']} requested")
raise gitversionhelper.wrongArguments(
f"invalid {cls.__OptDict['bump_type']} requested"
)
return BumpType
def bump(self, amount: int = 1, **kwargs) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R0912
def bump(
self, amount: int = 1, **kwargs
) -> gitversionhelper.version.MetaVersion | str: # pylint: disable=R0912
"""
bump the version to the next one
Keyword Arguments:
@@ -475,7 +508,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
_v.post_count = 0
_v.raw = _v.doFormatVersion(**kwargs)
if (self.__OptDict["formated_output"] in kwargs) and (kwargs[self.__OptDict["formated_output"]] is True):
if (self.__OptDict["formated_output"] in kwargs) and (
kwargs[self.__OptDict["formated_output"]] is True
):
return _v.doFormatVersion(**kwargs)
return _v
@@ -503,7 +538,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
if kwargs[cls.__OptDict["version_std"]] in cls.VersionStds:
VersionStd = kwargs[cls.__OptDict["version_std"]]
else:
raise gitversionhelper.wrongArguments(f"invalid {cls.__OptDict['version_std']} requested")
raise gitversionhelper.wrongArguments(
f"invalid {cls.__OptDict['version_std']} requested"
)
return VersionStd
@classmethod
@@ -520,7 +557,10 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
the last version
"""
if gitversionhelper.repository.isDirty() is not False:
raise gitversionhelper.repository.repositoryDirty("The repository is dirty and a current version can not be generated.")
raise gitversionhelper.repository.repositoryDirty(
"The repository is dirty and a current version"
" can not be generated."
)
saved_kwargs = copy(kwargs)
if "formated_output" in kwargs:
del saved_kwargs["formated_output"]
@@ -531,7 +571,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
amount = gitversionhelper.tag.getDistanceFromTag(_v.raw, **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
@@ -541,7 +583,7 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
Same as getCurrentVersion() with formated_output kwarg activated
"""
kwargs["formated_output"] = True
return cls.getCurrentVersion(**kwargs)
return cls.getCurrentVersion(kwargs)
@classmethod
def _parseTag(cls, tag, **kwargs): # pylint: disable=R0914, R0912, R0915
@@ -576,21 +618,31 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
pre_count = 0
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"))
else:
pre_count = 1
post_count = 0
if _post := _m.group("buildmetadata"):
if (_match := re.search(cls.VersionStds["SemVer"]["regex_build_num"], _post)) is not None:
if (
_match := re.search(
cls.VersionStds["SemVer"]["regex_build_num"], _post
)
) is not None:
post_count = int(_match.group("num"))
else:
post_count = 1
bFound = True
VersionStd = "SemVer"
if VersionStd == "PEP440" or ((bAutoVersionStd is True) and (bFound is not True)):
if VersionStd == "PEP440" or (
(bAutoVersionStd is True) and (bFound is not True)
):
_r = re.compile(
r"^\s*" + cls.VersionStds["PEP440"]["regex"] + r"\s*$",
re.VERBOSE | re.IGNORECASE,
@@ -611,14 +663,22 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
VersionStd = "PEP440"
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:
raise cls.PreAndPostVersionUnsupported("can not parse a version with both pre and post release number.")
return cls.MetaVersion(VersionStd, major, minor, patch, pre_count, post_count, tag)
raise cls.PreAndPostVersionUnsupported(
"can not parse a version with both pre" " and post release number."
)
return cls.MetaVersion(
VersionStd, major, minor, patch, pre_count, post_count, tag
)
@classmethod
def getLastVersion(cls, **kwargs) -> MetaVersion | str: # pylint: disable=R0914, R0912, R0915
def getLastVersion(
cls, **kwargs
) -> MetaVersion | str: # pylint: disable=R0914, R0912, R0915
"""get the last version from tags
Keyword Arguments:
version_std(str): the given version_std (can be None)
@@ -640,7 +700,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
try:
_v = cls._parseTag(lastTag, **kwargs)
except gitversionhelper.version.noValidVersion as _ex:
if (cls.__OptDict["ignore_unknown_tags"] in kwargs) and (kwargs[cls.__OptDict["ignore_unknown_tags"]] is True):
if (cls.__OptDict["ignore_unknown_tags"] in kwargs) and (
kwargs[cls.__OptDict["ignore_unknown_tags"]] is True
):
tags = gitversionhelper.tag.getTags(sort="taggerdate", **kwargs)
_v = None
for _tag in tags:
@@ -652,7 +714,9 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
if _v is None:
raise gitversionhelper.version.noValidVersion() from _ex
if (cls.__OptDict["formated_output"] in kwargs) and (kwargs[cls.__OptDict["formated_output"]] is True):
if (cls.__OptDict["formated_output"] in kwargs) and (
kwargs[cls.__OptDict["formated_output"]] is True
):
return _v.doFormatVersion(**kwargs)
return _v
@@ -686,7 +750,8 @@ class gitversionhelper: # pylint: disable=too-few-public-methods
OutputFormat = "{major}.{minor}.{patch}{revpattern}{revcount}"
if post_count > 0 and pre_count > 0:
raise gitversionhelper.version.PreAndPostVersionUnsupported(
"cannot output a version with both pre and post release number."
"cannot output a version with both pre "
"and post release number."
)
if VersionStd == "PEP440":
if post_count > 0:

File diff suppressed because it is too large Load Diff