Compare commits

...

3 Commits

Author SHA1 Message Date
Semantic Versioner
66c1b9ba89 p4 rough draft 2023-07-02 23:31:54 -04:00
Semantic Versioner
fa41212e77 Rework get_version and various improvements 2023-07-02 23:03:34 -04:00
d1e2d77a29 Implement unittests 2023-07-02 18:29:32 -04:00
17 changed files with 813 additions and 352 deletions

1
.gitignore vendored
View File

@ -7,7 +7,6 @@ dist/
*.zip
env
# Byte-compiled / optimized / DLL files
tests/
__pycache__/
*.py[cod]
*$py.class

View File

@ -12,30 +12,17 @@ from semver.scm import SCM
from semver.scm.git import Git
from semver.semver import SemVer
from semver.utils import setting_to_array
from semver.exceptions import (
NoMergeFoundException,
NotMainBranchException,
NoGitFlowException,
SemverException,
)
version = "0.0.0"
def _setting_to_array(setting) -> List[str]:
"""
Get a setting from the config file and return it as a list
:param setting: The setting to get from the config file
:return: The setting as a list
"""
config: dict = toml.load("./.bumpversion.cfg")
semver: dict = config.get("semver", {})
value: str = semver.get(setting, "")
return [v.strip() for v in value.split(",") if v.strip()]
def main():
"""Main entry point for the application"""
parser = argparse.ArgumentParser(description="Bump Semantic Version.")
@ -63,10 +50,10 @@ def main():
app = SemVer(
scm=scm,
main_branches=_setting_to_array("main_branches"),
major_branches=_setting_to_array("major_branches"),
minor_branches=_setting_to_array("minor_branches"),
patch_branches=_setting_to_array("patch_branches"),
main_branches=setting_to_array("main_branches"),
major_branches=setting_to_array("major_branches"),
minor_branches=setting_to_array("minor_branches"),
patch_branches=setting_to_array("patch_branches"),
)
if args.debug:

View File

@ -1,62 +1,57 @@
import argparse
import re
import subprocess
from semver.logger import logging, logger, console_logger
from semver.utils import get_tag_version, get_file_version, DEVNULL
from semver.logger import logging, console_logger
from semver import SemVer
from semver.bump import bump_version
def get_version(build=0,version_format=None,dot=False):
version = get_tag_version()
# Get the commit hash of the version
v_hash = subprocess.Popen(['git', 'rev-list', '-n', '1', version], stdout=subprocess.PIPE,
stderr=DEVNULL, cwd='.').stdout.read().decode('utf-8').rstrip()
# Get the current commit hash
c_hash = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE,
stderr=DEVNULL, cwd='.').stdout.read().decode('utf-8').rstrip()
# If the version commit hash and current commit hash
# do not match return the branch name else return the version
if v_hash != c_hash:
logger.debug("v_hash and c_hash do not match!")
branch = subprocess.Popen(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=subprocess.PIPE,
stderr=DEVNULL, cwd='.').stdout.read().decode('utf-8').rstrip()
semver = SemVer()
semver.merged_branch = branch
logger.debug("merged branch is: {}".format(semver.merged_branch))
version_type = semver.get_version_type()
logger.debug("version type is: {}".format(version_type))
if version_type:
next_version = bump_version(get_tag_version(), version_type, False, False)
if version_format in ('npm','docker'):
return "{}-{}.{}".format(next_version,re.sub(r'[/_]', '-', branch),build)
if version_format == 'maven':
qualifier = 'SNAPSHOT' if build == 0 else build
return "{}-{}-{}".format(next_version,re.sub(r'[/_]', '-', branch),qualifier)
if dot:
branch = branch.replace('/','.')
return branch
return version
from semver.utils import setting_to_array
from semver.scm.git import Git
def main():
parser = argparse.ArgumentParser(description='Get Version or Branch.')
parser.add_argument('-d', '--dot', help='Switch out / for . to be used in docker tag', action='store_true', dest='dot')
parser.add_argument('-D', '--debug', help='Sets logging level to DEBUG', action='store_true', dest='debug', default=False)
parser.add_argument('-f', '--format', help='Format for pre-release version syntax', choices=['npm','maven','docker'], default=None)
parser.add_argument('-b', '--build-number', help='Build number, used in pre-releases', default=0)
parser = argparse.ArgumentParser(description="Get Version or Branch.")
parser.add_argument(
"-d",
"--dot",
help="Switch out / for . to be used in docker tag",
action="store_true",
dest="dot",
)
parser.add_argument(
"-D",
"--debug",
help="Sets logging level to DEBUG",
action="store_true",
dest="debug",
default=False,
)
parser.add_argument(
"-f",
"--format",
help="Format for pre-release version syntax",
choices=["npm", "maven", "docker"],
default=None,
)
parser.add_argument(
"-b", "--build-number", help="Build number, used in pre-releases", default=0
)
args = parser.parse_args()
if args.debug:
console_logger.setLevel(logging.DEBUG)
print(get_version(args.build_number,args.format,args.dot))
semver = SemVer(
scm=Git(),
main_branches=setting_to_array("main_branches"),
major_branches=setting_to_array("major_branches"),
minor_branches=setting_to_array("minor_branches"),
patch_branches=setting_to_array("patch_branches"),
)
if __name__ == '__main__':
try: main()
except: raise
print(semver.get_version(args.build_number, args.format, args.dot))
if __name__ == "__main__":
try:
main()
except Exception as e:
raise e

View File

@ -8,42 +8,42 @@ from semver.logger import logger
class SCM(ABC):
@abstractmethod
def get_tag_version(self) -> str:
raise NotImplementedError
raise NotImplementedError()
@abstractmethod
def get_branch(self) -> str:
raise NotImplementedError
raise NotImplementedError()
@abstractmethod
def get_merge_branch(self) -> Union[str, None]:
raise NotImplementedError
raise NotImplementedError()
@abstractmethod
def commit_and_push(self, branch: str) -> None:
raise NotImplementedError
raise NotImplementedError()
@abstractmethod
def tag_version(self, version: str) -> None:
raise NotImplementedError
raise NotImplementedError()
@abstractmethod
def get_version_hash(self, version: str) -> str:
raise NotImplementedError()
@abstractmethod
def get_hash(self) -> str:
raise NotImplementedError()
def get_file_version(self, config: dict) -> str:
"""
:param config: The bumpversion config as a dict
:return: The current version from the config file
"""
bumpversion: Union[str, None] = config.get("bumpversion", None)
version: Union[str, None] = (
bumpversion.get("current_version", None) if bumpversion else None
bump_version: Union[str, None] = config.get("bumpversion", None)
version: str = (
bump_version.get("current_version", "0.0.0") if bump_version else "0.0.0"
)
if not bumpversion:
config["bumpversion"] = {}
version = "0.0.0"
if not version:
config["bumpversion"]["current_version"] = "0.0.0"
version = "0.0.0"
return version
def get_version_type(

View File

@ -26,12 +26,14 @@ class Git(SCM):
super().__init__()
def _run_command(self, *args: str) -> subprocess.CompletedProcess[str]:
def _run_command(
self, *args: str, throwExceptions: bool = True
) -> subprocess.CompletedProcess[str]:
return subprocess.run(
args,
capture_output=True,
text=True,
check=True,
check=throwExceptions,
)
def _setup_git_user(self) -> None:
@ -75,7 +77,7 @@ class Git(SCM):
)
tagged_versions = proc.stdout.rstrip().split("\n")
except subprocess.CalledProcessError as e:
raise RuntimeError(
raise SemverException(
f"Error getting latest tagged git version: {str(e.stderr).rstrip()}"
)
@ -104,8 +106,6 @@ class Git(SCM):
branch: str = self.get_branch()
logger.info(f"Main branch is {branch}")
matches = self.git_commit_pattern.search(
message.replace("\\n", "\n").replace("\\", "")
)
@ -122,16 +122,41 @@ class Git(SCM):
Commit and push the versioning changes
:param branch: The branch to push
"""
proc = self._run_command(self.git_bin, "push", "origin", branch)
proc = self._run_command(
self.git_bin, "push", "origin", branch, throwExceptions=False
)
if proc.returncode != 0:
raise SemverException(
f"Error pushing versioning changes to {branch}: {proc.stderr}"
)
proc = self._run_command(self.git_bin, "push", "origin", "--tags")
proc = self._run_command(
self.git_bin, "push", "origin", "--tags", throwExceptions=False
)
if proc.returncode != 0:
raise SemverException(
f"Error pushing versioning changes to {branch}: {proc.stderr}"
)
def tag_version(self, version: str) -> None:
self._run_command(self.git_bin, "tag", version)
"""
Creates a git tag at HEAD with the given version
:param version: The version to tag
"""
self._run_command(self.git_bin, "tag", version)
def get_version_hash(self, version: str) -> str:
"""
Get the hash of the commit that has the given version
:param version: The version to get the hash for
:return: The hash of the commit that has the given version
"""
proc = self._run_command(self.git_bin, "rev-list", "-n", "1", version)
return proc.stdout.rstrip()
def get_hash(self) -> str:
"""
Get the hash of the current commit
:return: The hash of the current commit
"""
proc = self._run_command(self.git_bin, "rev-parse", "HEAD")
return proc.stdout.rstrip()

26
semver/scm/mock.py Normal file
View File

@ -0,0 +1,26 @@
from typing import Union
from semver.scm import SCM
class MockSCM(SCM):
def get_tag_version(self) -> str:
return "1.0.0"
def get_branch(self) -> str:
return "main"
def get_merge_branch(self) -> Union[str, None]:
return "main"
def commit_and_push(self, branch: str) -> None:
pass
def tag_version(self, version: str) -> None:
pass
def get_version_hash(self, version: str) -> str:
return "HASH"
def get_hash(self) -> str:
return "HASH"

View File

@ -5,18 +5,32 @@ import toml
from semver.scm import SCM
from semver.logger import logger
from semver.utils import get_settings
from semver.exceptions import SemverException
class Perforce(SCM):
def __init__(self) -> None:
self.p4_bin = "p4"
super().__init__()
def _run_command(
self, *args: str, throwExceptions: bool = True
) -> subprocess.CompletedProcess[str]:
return subprocess.run(
args,
capture_output=True,
text=True,
check=throwExceptions,
)
def get_tag_version(self) -> str:
"""
Get the latest tagged version from Perforce labels
:return: The latest tagged version
"""
config: dict = toml.load("./.bumpversion.cfg")
config: dict = get_settings()
tag_expression: str = config["bumpversion"]["tag_name"].replace(
"{new_version}", "[0-9]*.[0-9]*.[0-9]*"
@ -30,15 +44,10 @@ class Perforce(SCM):
# If a version is found in Perforce labels, use that the latest labeled version
labeled_versions: Union[List[str], None] = None
try:
proc = subprocess.run(
["p4", "labels", "-e", tag_expression, "-m1"],
capture_output=True,
text=True,
check=True,
)
proc = self._run_command(self.p4_bin, "labels", "-e", tag_expression, "-m1")
labeled_versions = proc.stdout.rstrip().split("\n")
except subprocess.CalledProcessError as e:
raise RuntimeError(
raise SemverException(
f"Error getting latest labeled Perforce version: {str(e.stderr).rstrip()}"
)
@ -47,3 +56,97 @@ class Perforce(SCM):
logger.debug("Label Version: " + str(version))
return version
def get_branch(self) -> str:
"""
Returns the name of the current Perforce stream
:return: The current Perforce stream
"""
try:
proc = self._run_command(self.p4_bin, "client", "-o")
client = toml.loads(proc.stdout)
return client["Stream"]
except subprocess.CalledProcessError as e:
raise SemverException(
f"Error getting current Perforce stream: {str(e.stderr).rstrip()}"
)
def get_merge_branch(self) -> Union[str, None]:
"""
Returns the name of the stream being intergrated into mainline
:return: The Perforce stream being intergrated into mainline
"""
try:
proc = self._run_command(self.p4_bin, "client", "-o")
client = toml.loads(proc.stdout)
return client["StreamAtChange"]
except subprocess.CalledProcessError as e:
raise SemverException(
f"Error getting current Perforce stream: {str(e.stderr).rstrip()}"
)
def commit_and_push(self, branch: str) -> None:
"""
Creates a changelist and submits it to Perforce
:param branch: The current Perforce stream
"""
try:
proc = self._run_command(self.p4_bin, "change", "-o")
change = toml.loads(proc.stdout)
change["Description"] = f"Version Bump"
change["Files"] = [f"//{branch}/..."]
proc = subprocess.Popen([self.p4_bin, "change", "-i"], stdin=subprocess.PIPE)
proc.communicate(input=toml.dumps(change).encode())
proc.wait()
proc = self._run_command(self.p4_bin, "submit", "-c", str(change["Change"]))
except subprocess.CalledProcessError as e:
raise SemverException(
f"Error creating a CL and submitting to Perforce: {str(e.stderr).rstrip()}"
)
def tag_version(self, version: str) -> None:
"""
Creates a Perforce label
:param version: The version to label
"""
try:
proc = self._run_command(self.p4_bin, "label", "-o", version)
label = toml.loads(proc.stdout)
label["Description"] = f"Version {version}"
label["Options"] = "locked"
label["Revision"] = f"//{self.get_branch()}/..."
proc = subprocess.Popen([self.p4_bin, "label", "-i"], stdin=subprocess.PIPE)
proc.communicate(input=toml.dumps(label).encode())
proc.wait()
except subprocess.CalledProcessError as e:
raise SemverException(
f"Error creating a Perforce label: {str(e.stderr).rstrip()}"
)
def get_version_hash(self, version: str) -> str:
"""
Returns the hash of the version label
:param version: The version label
:return: The hash of the version label
"""
try:
proc = self._run_command(self.p4_bin, "labels", "-e", version, "-m1")
label = toml.loads(proc.stdout)
return label["Revision"]
except subprocess.CalledProcessError as e:
raise SemverException(
f"Error getting hash of version label: {str(e.stderr).rstrip()}"
)
def get_hash(self) -> str:
"""
Returns the hash of the current commit
:return: The hash of the current commit
"""
try:
proc = self._run_command(self.p4_bin, "changes", "-m1")
change = toml.loads(proc.stdout)
return change["Change"]
except subprocess.CalledProcessError as e:
raise SemverException(
f"Error getting hash of current commit: {str(e.stderr).rstrip()}"
)

View File

View File

@ -0,0 +1,117 @@
import unittest
from unittest import mock
import subprocess
from semver.version_type import VersionType
from semver.exceptions import SemverException
from semver.scm import SCM
from semver.scm.git import Git
class TestMockSCM(unittest.TestCase):
@mock.patch("subprocess.run")
def setUp(self, mock_subprocess_run: mock.Mock):
# Mock the subprocess.run function to avoid
# running actual git commands
mock_subprocess_run.return_value.returncode = 0
mock_subprocess_run.return_value.stdout = ""
self.scm = Git()
def test_run_command(self):
proc: subprocess.CompletedProcess[str] = self.scm._run_command("echo", "hello")
self.assertEqual(proc.stdout, "hello\n")
@mock.patch("toml.load")
@mock.patch("subprocess.run")
def test_get_tag_version(
self, mock_subprocess_run: mock.Mock, mock_toml_load: mock.Mock
):
mock_toml_load.return_value = {"bumpversion": {"tag_name": "v{new_version}"}}
mock_subprocess_run.return_value.stdout = "v1.0.0\n"
expected_version = "v1.0.0"
version = self.scm.get_tag_version()
self.assertEqual(version, expected_version)
@mock.patch("toml.load")
@mock.patch("subprocess.run")
def test_get_tag_version_git_fail(
self, mock_subprocess_run: mock.Mock, mock_toml_load: mock.Mock
):
mock_toml_load.return_value = {"bumpversion": {"tag_name": "v{new_version}"}}
mock_subprocess_run.return_value.returncode = 1
mock_subprocess_run.side_effect = subprocess.CalledProcessError(
1, "git", "git error"
)
with self.assertRaises(SemverException):
self.scm.get_tag_version()
@mock.patch("subprocess.run")
def test_get_branch(self, mock_subprocess_run: mock.Mock):
mock_subprocess_run.return_value.stdout = "main\n"
expected_branch = "main"
branch = self.scm.get_branch()
self.assertEqual(branch, expected_branch)
@mock.patch("subprocess.run")
def test_get_merge_branch(self, mock_subprocess_run: mock.Mock):
mock_subprocess_run.return_value.stdout = (
"Merge pull request #1 from RightBrain-Networks/feature/example\n"
)
expected_merge_branch = "feature/example"
merge_branch = self.scm.get_merge_branch()
self.assertEqual(merge_branch, expected_merge_branch)
@mock.patch("subprocess.run")
def test_commit_and_push(self, mock_subprocess_run: mock.Mock):
mock_subprocess_run.return_value.returncode = 0
branch = "main"
self.scm.commit_and_push(branch)
@mock.patch("subprocess.run")
def test_commit_and_push_git_fail(self, mock_subprocess_run: mock.Mock):
mock_subprocess_run.return_value.returncode = 1
branch = "main"
with self.assertRaises(SemverException):
self.scm.commit_and_push(branch)
@mock.patch("subprocess.run")
def test_commit_and_push_git_fail_tags(self, mock_subprocess_run: mock.Mock):
mock_subprocess_run.side_effect = [
mock.Mock(returncode=0),
mock.Mock(returncode=1),
]
branch = "main"
with self.assertRaises(SemverException):
self.scm.commit_and_push(branch)
@mock.patch("subprocess.run")
def test_tag_version(self, mock_subprocess_run: mock.Mock):
mock_subprocess_run.return_value.returncode = 0
version = "1.0.0"
self.scm.tag_version(version)
@mock.patch("subprocess.run")
def test_get_version_hash(self, mock_subprocess_run: mock.Mock):
mock_subprocess_run.return_value.stdout = "HASH\n"
version = "1.0.0"
expected_hash = "HASH"
version_hash = self.scm.get_version_hash(version)
self.assertEqual(version_hash, expected_hash)
@mock.patch("subprocess.run")
def test_get_hash(self, mock_subprocess_run: mock.Mock):
mock_subprocess_run.return_value.stdout = "HASH\n"
expected_hash = "HASH"
version_hash = self.scm.get_hash()
self.assertEqual(version_hash, expected_hash)

View File

@ -0,0 +1,45 @@
import unittest
from semver.version_type import VersionType
from semver.scm import SCM
from semver.scm.mock import MockSCM
class TestMockSCM(unittest.TestCase):
def setUp(self):
self.scm: SCM = MockSCM()
def test_get_tag_version(self):
expected_version = "1.0.0"
version = self.scm.get_tag_version()
self.assertEqual(version, expected_version)
def test_get_branch(self):
expected_branch = "main"
branch = self.scm.get_branch()
self.assertEqual(branch, expected_branch)
def test_get_merge_branch(self):
expected_merge_branch = "main"
merge_branch = self.scm.get_merge_branch()
self.assertEqual(merge_branch, expected_merge_branch)
def test_commit_and_push(self):
branch = "main"
self.scm.commit_and_push(branch)
def test_tag_version(self):
version = "1.0.0"
self.scm.tag_version(version)
def test_get_version_hash(self):
version = "1.0.0"
expected_hash = "HASH"
version_hash = self.scm.get_version_hash(version)
self.assertEqual(version_hash, expected_hash)
def test_get_hash(self):
expected_hash = "HASH"
version_hash = self.scm.get_hash()
self.assertEqual(version_hash, expected_hash)

View File

@ -0,0 +1,72 @@
import unittest
from semver.version_type import VersionType
from semver.scm import SCM
from semver.scm.mock import MockSCM
class TestSCM(unittest.TestCase):
def setUp(self):
self.scm: SCM = MockSCM()
def test_get_file_version_existing_config(self):
config = {"bumpversion": {"current_version": "1.2.3"}}
expected_version = "1.2.3"
version = self.scm.get_file_version(config)
self.assertEqual(version, expected_version)
def test_get_file_version_no_config(self):
config = {}
expected_version = "0.0.0"
version = self.scm.get_file_version(config)
self.assertEqual(version, expected_version)
def test_get_file_version_no_version(self):
config = {"bumpversion": {}}
expected_version = "0.0.0"
version = self.scm.get_file_version(config)
self.assertEqual(version, expected_version)
def test_get_version_type_major(self):
merged_branch = "main"
major_branches = ["main"]
minor_branches = ["develop"]
patch_branches = ["hotfix"]
expected_version_type = VersionType.MAJOR
version_type = self.scm.get_version_type(
merged_branch, major_branches, minor_branches, patch_branches
)
self.assertEqual(version_type, expected_version_type)
def test_get_version_type_minor(self):
merged_branch = "develop"
major_branches = ["main"]
minor_branches = ["develop"]
patch_branches = ["hotfix"]
expected_version_type = VersionType.MINOR
version_type = self.scm.get_version_type(
merged_branch, major_branches, minor_branches, patch_branches
)
self.assertEqual(version_type, expected_version_type)
def test_get_version_type_patch(self):
merged_branch = "hotfix"
major_branches = ["main"]
minor_branches = ["develop"]
patch_branches = ["hotfix"]
expected_version_type = VersionType.PATCH
version_type = self.scm.get_version_type(
merged_branch, major_branches, minor_branches, patch_branches
)
self.assertEqual(version_type, expected_version_type)
def test_get_version_type_none(self):
merged_branch = "feature"
major_branches = ["main"]
minor_branches = ["develop"]
patch_branches = ["hotfix"]
expected_version_type = None
version_type = self.scm.get_version_type(
merged_branch, major_branches, minor_branches, patch_branches
)
self.assertEqual(version_type, expected_version_type)

View File

@ -1,5 +1,6 @@
from typing import List, Union
from pathlib import Path
import re
import toml
@ -44,16 +45,17 @@ class SemVer:
self._scm: SCM = scm
def _version_repo(self) -> None:
def _version_repo(self) -> str:
"""
Use bump_version to update the repo version
:return: The new version
"""
version = self._scm.get_tag_version()
if not self._version_type:
raise NoMergeFoundException()
logger.debug(f"Running bumpversion of type: {self._version_type.name}")
self._bump_version(version, self._version_type)
return self._bump_version(version, self._version_type)
def _process_config_string(self, cfg_string, new_version, version):
return cfg_string.replace("{new_version}", new_version).replace(
@ -138,6 +140,52 @@ class SemVer:
f"Tried to version file: '{file_path}' but it doesn't exist!"
)
def get_version(
self, build: int = 0, version_format: Union[str, None] = None, dot: bool = False
):
"""
Get the version of the repo
:param build: The build number
:param version_format: The format of the version
:param dot: Whether or not to replace / with .
:return: The version
"""
version = self._scm.get_tag_version()
# Get the commit hash of the version
v_hash = self._scm.get_version_hash(version)
# Get the current commit hash
c_hash = self._scm.get_hash()
# If the version commit hash and current commit hash
# do not match return the branch name else return the version
if v_hash != c_hash:
logger.debug("v_hash and c_hash do not match!")
branch = self._scm.get_branch()
logger.debug("merged branch is: {}".format(branch))
version_type = self._scm.get_version_type(
branch, self._major_branches, self._minor_branches, self._patch_branches
)
logger.debug("version type is: {}".format(version_type))
if version_type:
next_version = self._bump_version(
self._scm.get_tag_version(), version_type, False, False
)
if version_format in ("npm", "docker"):
return "{}-{}.{}".format(
next_version, re.sub(r"[/_]", "-", branch), build
)
if version_format == "maven":
qualifier = "SNAPSHOT" if build == 0 else build
return "{}-{}-{}".format(
next_version, re.sub(r"[/_]", "-", branch), qualifier
)
if dot:
branch = branch.replace("/", ".")
return branch
return version
def run(self, push=True):
"""
Run the versioning process
@ -151,9 +199,9 @@ class SemVer:
self._merged_branch = self._scm.get_merge_branch()
if not self._merged_branch:
raise NoMergeFoundException()
raise NoMergeFoundException("No merge found")
if self._branch not in self._main_branches:
raise NotMainBranchException()
raise NotMainBranchException("Not a main branch")
self._version_type = self._scm.get_version_type(
self._branch,
@ -163,7 +211,7 @@ class SemVer:
)
if not self._version_type:
raise NoGitFlowException()
raise NoGitFlowException("Could not determine version type")
self._version_repo()
if push:

View File

@ -1,246 +0,0 @@
import unittest, os, subprocess, re, semver
from semver.logger import logging, logger, console_logger
from semver import bump, get_version, utils, NO_MERGE_FOUND, GET_COMMIT_MESSAGE
config_data = """
[bumpversion]
current_version = 0.0.0
commit = False
tag = True
tag_name = {new_version}
[bumpversion:file:file.txt]
search = 0.0.0
replace = {new_version}
[semver]
main_branches = master
major_branches = major
minor_branches = minor
patch_branches = patch
"""
test_directory = "test"
class TestSemverObject(unittest.TestCase):
def test_get_version_type_major_merge(self):
semver_object = semver.SemVer()
semver_object.merged_branch = "major/unittest"
semver_object.get_version_type()
self.assertEqual(semver_object.version_type, semver.VersionType.MAJOR)
def test_get_version_type_minor_merge(self):
semver_object = semver.SemVer()
semver_object.merged_branch = "minor/unittest"
semver_object.get_version_type()
self.assertEqual(semver_object.version_type, semver.VersionType.MINOR)
def test_get_version_type_patch_merge(self):
semver_object = semver.SemVer()
semver_object.merged_branch = "patch/unittest"
semver_object.get_version_type()
self.assertEqual(semver_object.version_type, semver.VersionType.PATCH)
def test_run_no_merge(self):
semver_object = semver.SemVer()
try:
result = semver_object.run(False)
except Exception as e:
if e == NO_MERGE_FOUND:
self.assertTrue(True)
else:
self.assertTrue(False)
class TestGetVersion(unittest.TestCase):
def test_get_branch_version(self):
create_git_environment()
branch = get_version.get_version()
self.assertEqual(branch, "master")
def test_branch_dotting(self):
create_git_environment()
subprocess.call(['git', 'checkout', '-b', 'test/branch'])
branch = get_version.get_version(dot=True)
self.assertEqual(branch, "test.branch")
def test_branch_dotting_false(self):
create_git_environment()
subprocess.call(['git', 'checkout', '-b', 'test/branch'])
branch = get_version.get_version(dot=False)
self.assertEqual(branch, "test/branch")
def test_branch_npm_pre_release(self):
create_git_environment()
subprocess.call(['git', 'checkout', '-b', 'patch/branch'])
branch = get_version.get_version(version_format='npm')
self.assertEqual(branch, "0.0.1-patch-branch.0")
def test_branch_docker_pre_release(self):
create_git_environment()
subprocess.call(['git', 'checkout', '-b', 'patch/branch'])
branch = get_version.get_version(build=2,version_format='docker')
self.assertEqual(branch, "0.0.1-patch-branch.2")
def test_branch_maven_pre_release(self):
create_git_environment()
subprocess.call(['git', 'checkout', '-b', 'minor/branch'])
branch = get_version.get_version(version_format='maven')
self.assertEqual(branch, "0.1.0-minor-branch-SNAPSHOT")
def test_branch_maven_bad_branch(self):
create_git_environment()
subprocess.call(['git', 'checkout', '-b', 'test/branch'])
branch = get_version.get_version(version_format='maven')
self.assertEqual(branch, "test/branch")
def test_get_version_run(self):
create_git_environment()
val = subprocess.Popen(['python', '../get_version.py', '-d'], stdout=subprocess.PIPE,
stderr=open(os.devnull, 'wb'), cwd='.').stdout.read().decode('utf-8').rstrip()
self.assertEqual(val, "master")
class TestGetTagVersion(unittest.TestCase):
def test_get_version_tag(self):
create_git_environment()
subprocess.call(['git', 'tag', '1.0.0'])
tag = utils.get_tag_version()
self.assertEqual(tag, "1.0.0")
def test_get_version_multiple(self):
create_git_environment()
subprocess.call(['git', 'tag', '0.1.0'])
subprocess.call(['git', 'tag', '0.1.1'])
subprocess.call(['git', 'tag', '0.1.2'])
subprocess.call(['git', 'tag', '0.1.3'])
subprocess.call(['git', 'tag', '0.2.0'])
subprocess.call(['git', 'tag', '0.3.0'])
subprocess.call(['git', 'tag', '0.3.1'])
subprocess.call(['git', 'tag', '1.0.0'])
subprocess.call(['git', 'tag', '1.1.0'])
subprocess.call(['git', 'tag', '1.2.0'])
subprocess.call(['git', 'tag', '1.2.1'])
tag = utils.get_tag_version()
self.assertEqual(tag, "1.2.1")
def test_get_version_out_of_order(self):
subprocess.call(['git', 'tag', '0.1.0'])
subprocess.call(['git', 'tag', '0.1.1'])
subprocess.call(['git', 'tag', '0.5.2'])
subprocess.call(['git', 'tag', '0.1.3'])
subprocess.call(['git', 'tag', '8.1.0'])
subprocess.call(['git', 'tag', '0.3.8'])
subprocess.call(['git', 'tag', '3.3.1'])
subprocess.call(['git', 'tag', '1.4.0'])
subprocess.call(['git', 'tag', '1.1.7'])
subprocess.call(['git', 'tag', '1.2.0'])
subprocess.call(['git', 'tag', '0.2.1'])
tag = utils.get_tag_version()
self.assertEqual(tag, "8.1.0")
def test_default_get_version_tag(self):
create_git_environment()
tag = utils.get_tag_version()
self.assertEqual(tag, "0.0.0")
class TestGetCommitMessageRegex(unittest.TestCase):
def test_github_message(self):
matches = GET_COMMIT_MESSAGE.search("Merge pull request #1 from user/branch")
if matches:
self.assertEqual(matches.group(4), None)
self.assertEqual(matches.group(5), "branch")
else:
self.assertTrue(False)
pass
def test_gitlab_message(self):
matches = GET_COMMIT_MESSAGE.search("Merge branch 'branch' into 'master'")
if matches:
self.assertEqual(matches.group(4), "master")
self.assertEqual(matches.group(2), "branch")
else:
self.assertTrue(False)
def test_branch_in_message(self):
matches = GET_COMMIT_MESSAGE.search(str(b'commit examplehash\nMerge: example\nAuthor: Test <test@nodomain.rightbrainnetworks.com>\nDate: Mon Jun 15 18:15:22 2020 -0400\n\n Merge pull request #45 from user/branch\n \n user/branch\n'))
if matches:
self.assertEqual(matches.group(4), None)
self.assertEqual(matches.group(5), "branch")
else:
self.assertTrue(False)
def test_non_merge_message(self):
matches = GET_COMMIT_MESSAGE.search("Example unrelated commit message that should get 0 matches")
self.assertEqual(matches, None)
def test_gitlab_merge_with_double_quotes(self):
matches = GET_COMMIT_MESSAGE.search("Merge branch 'branch' into 'master'\n\n\"Message in quotes!\"")
if matches:
self.assertEqual(matches.group(4), "master")
self.assertEqual(matches.group(2), "branch")
else:
self.assertTrue(False)
class TestVersionBumping(unittest.TestCase):
def test_patch_bump(self):
self.assertEqual("0.0.1", bump.bump_version("0.0.0", semver.VersionType.PATCH, False))
self.assertEqual("0.0.2", bump.bump_version("0.0.1", semver.VersionType.PATCH, False))
self.assertEqual("0.1.1", bump.bump_version("0.1.0", semver.VersionType.PATCH, False))
self.assertEqual("1.0.1", bump.bump_version("1.0.0", semver.VersionType.PATCH, False))
self.assertEqual("1.2.4", bump.bump_version("1.2.3", semver.VersionType.PATCH, False))
self.assertEqual("0.0.11", bump.bump_version("0.0.10", semver.VersionType.PATCH, False))
self.assertEqual("0.10.1", bump.bump_version("0.10.0", semver.VersionType.PATCH, False))
self.assertEqual("10.0.1", bump.bump_version("10.0.0", semver.VersionType.PATCH, False))
def test_minor_bump(self):
self.assertEqual("0.1.0", bump.bump_version("0.0.0", semver.VersionType.MINOR, False))
self.assertEqual("0.1.0", bump.bump_version("0.0.1", semver.VersionType.MINOR, False))
self.assertEqual("0.2.0", bump.bump_version("0.1.0", semver.VersionType.MINOR, False))
self.assertEqual("1.1.0", bump.bump_version("1.0.0", semver.VersionType.MINOR, False))
self.assertEqual("1.3.0", bump.bump_version("1.2.3", semver.VersionType.MINOR, False))
self.assertEqual("0.1.0", bump.bump_version("0.0.10", semver.VersionType.MINOR, False))
self.assertEqual("0.11.0", bump.bump_version("0.10.0", semver.VersionType.MINOR, False))
self.assertEqual("10.1.0", bump.bump_version("10.0.0", semver.VersionType.MINOR, False))
def test_major_bump(self):
self.assertEqual("1.0.0", bump.bump_version("0.0.0", semver.VersionType.MAJOR, False))
self.assertEqual("1.0.0", bump.bump_version("0.0.1", semver.VersionType.MAJOR, False))
self.assertEqual("1.0.0", bump.bump_version("0.1.0", semver.VersionType.MAJOR, False))
self.assertEqual("2.0.0", bump.bump_version("1.0.0", semver.VersionType.MAJOR, False))
self.assertEqual("2.0.0", bump.bump_version("1.2.3", semver.VersionType.MAJOR, False))
self.assertEqual("1.0.0", bump.bump_version("0.0.10", semver.VersionType.MAJOR, False))
self.assertEqual("1.0.0", bump.bump_version("0.10.0", semver.VersionType.MAJOR, False))
self.assertEqual("11.0.0", bump.bump_version("10.0.0", semver.VersionType.MAJOR, False))
class TestFileVersioning(unittest.TestCase):
def test_file_bump(self):
with open('file.txt', 'w') as f:
f.write("0.0.0")
bump.update_file_version("12.34.56")
file_data = ""
with open('file.txt', 'r') as f:
file_data = f.read()
self.assertEqual("12.34.56", file_data)
def test_file_bump_with_text(self):
with open('file.txt', 'w') as f:
f.write("version = 0.0.0")
bump.update_file_version("12.34.56")
file_data = ""
with open('file.txt', 'r') as f:
file_data = f.read()
self.assertEqual("version = 12.34.56", file_data)
def test_file_bump_with_multiline(self):
with open('file.txt', 'w') as f:
f.write("version = 0.0.0\n#An example second line\nThird line!")
bump.update_file_version("12.34.56")
file_data = ""
with open('file.txt', 'r') as f:
file_data = f.read()
self.assertEqual("version = 12.34.56", file_data.split('\n')[0])
def create_git_environment():
subprocess.call(['rm', '-rf', './.git'])
subprocess.call(['git', 'init'])
subprocess.call(['touch', 'file.txt'])
subprocess.call(['git', 'add', 'file.txt'])
subprocess.call(['git', 'commit', '-m', 'file.txt'])
subprocess.call(['git', 'remote', 'add', 'origin', os.getcwd()+'/.git'])
if __name__ == "__main__":
console_logger.setLevel(logging.DEBUG)
subprocess.call(['rm', '-rf', test_directory])
subprocess.call(['mkdir', test_directory])
os.chdir(test_directory)
with open('.bumpversion.cfg', "w") as config:
config.write(config_data)
unittest.main()
os.chdir("..")

0
semver/tests/__init__.py Normal file
View File

193
semver/tests/test_semver.py Normal file
View File

@ -0,0 +1,193 @@
import unittest
from unittest import mock
from semver.version_type import VersionType
from semver.scm import SCM
from semver.scm.mock import MockSCM
from semver.semver import SemVer
from semver.exceptions import (
NoMergeFoundException,
NoGitFlowException,
NotMainBranchException,
)
class TestSemVer(unittest.TestCase):
def setUp(self):
scm = mock.MagicMock(MockSCM())
self.semver: SemVer = SemVer(scm=scm)
@mock.patch("semver.semver.SemVer._bump_version")
def test_version_repo(self, mock_bump_version: mock.Mock):
self.semver._scm.get_tag_version.return_value = "1.0.0"
self.semver._version_type = VersionType.PATCH
expected_version = "1.0.1"
mock_bump_version.return_value = expected_version
version = self.semver._version_repo()
self.assertEqual(version, expected_version)
@mock.patch("semver.semver.SemVer._bump_version")
def test_version_repo_no_tag(self, mock_bump_version: mock.Mock):
self.semver._scm.get_tag_version.return_value = "1.0.0"
self.semver._version_type = None
with self.assertRaises(NoMergeFoundException):
self.semver._version_repo()
def test_process_config_string(self):
expected_version = "v1.0.0"
version = self.semver._process_config_string("v{new_version}", "1.0.0", "1.0.1")
self.assertEqual(version, expected_version)
expected_version = "v1.0.1"
version = self.semver._process_config_string(
"v{current_version}", "1.0.0", "1.0.1"
)
self.assertEqual(version, expected_version)
@mock.patch("semver.semver.SemVer._update_file_version")
def test_bump_version_major(self, mock_update_file_version: mock.Mock):
expected_version = "2.0.0"
version = self.semver._bump_version("1.0.0", VersionType.MAJOR)
self.assertEqual(version, expected_version)
@mock.patch("semver.semver.SemVer._update_file_version")
def test_bump_version_minor(self, mock_update_file_version: mock.Mock):
expected_version = "1.1.0"
version = self.semver._bump_version("1.0.0", VersionType.MINOR)
self.assertEqual(version, expected_version)
@mock.patch("semver.semver.SemVer._update_file_version")
def test_bump_version_patch(self, mock_update_file_version: mock.Mock):
expected_version = "1.0.1"
version = self.semver._bump_version("1.0.0", VersionType.PATCH)
self.assertEqual(version, expected_version)
@mock.patch("toml.load")
@mock.patch("pathlib.Path.is_file")
@mock.patch("builtins.open", mock.mock_open())
@mock.patch("semver.logger.warning")
def test_update_file_version(
self,
mock_logger: mock.Mock,
mock_path_is_file: mock.Mock,
mock_toml_load: mock.Mock,
):
mock_toml_load.return_value = {
"bumpversion": {"current_version": "1.0.0"},
"bumpversion:file:VERSION": {
"search": "0.0.0",
"replace": "{new_version}",
},
}
mock_path_is_file.return_value = True
self.semver._update_file_version("1.0.1", "1.0.0")
mock_logger.assert_not_called()
mock_path_is_file.return_value = False
self.semver._update_file_version("1.0.1", "1.0.0")
mock_logger.assert_called_once()
@mock.patch("semver.semver.SemVer._version_repo", mock.MagicMock())
def test_run_ok(self):
self.semver._version_repo = mock.MagicMock()
self.semver._version_repo.return_value = "1.0.1"
self.semver._scm.get_branch.return_value = "main"
self.semver._scm.get_merge_branch.return_value = "main"
self.semver._scm.get_version_type.return_value = VersionType.MINOR
self.semver._scm.commit_and_push.return_value = None
self.semver._main_branches = ["main"]
self.semver.run()
@mock.patch("semver.semver.SemVer._version_repo", mock.MagicMock())
def test_run_not_merge(self):
self.semver._version_repo = mock.MagicMock()
self.semver._version_repo.return_value = "1.0.1"
self.semver._scm.get_branch.return_value = "main"
self.semver._scm.get_merge_branch.return_value = None
self.semver._scm.get_version_type.return_value = VersionType.MINOR
self.semver._scm.commit_and_push.return_value = None
self.semver._main_branches = ["main"]
with self.assertRaises(NoMergeFoundException):
self.semver.run()
@mock.patch("semver.semver.SemVer._version_repo", mock.MagicMock())
def test_run_not_version_type(self):
self.semver._version_repo = mock.MagicMock()
self.semver._version_repo.return_value = "1.0.1"
self.semver._scm.get_branch.return_value = "feature/example"
self.semver._scm.get_merge_branch.return_value = "main"
self.semver._scm.get_version_type.return_value = VersionType.MINOR
self.semver._scm.commit_and_push.return_value = None
self.semver._main_branches = ["main"]
with self.assertRaises(NotMainBranchException):
self.semver.run()
@mock.patch("semver.semver.SemVer._version_repo", mock.MagicMock())
def test_run_not_main_branch(self):
self.semver._version_repo = mock.MagicMock()
self.semver._version_repo.return_value = "1.0.1"
self.semver._scm.get_branch.return_value = "main"
self.semver._scm.get_merge_branch.return_value = "main"
self.semver._scm.get_version_type.return_value = None
self.semver._scm.commit_and_push.return_value = None
self.semver._main_branches = ["main"]
with self.assertRaises(NoGitFlowException):
self.semver.run()
@mock.patch("semver.semver.SemVer._bump_version")
def test_get_version(self, mock_bump_version: mock.Mock):
self.semver._scm.get_branch.return_value = "feature/example"
self.semver._scm.get_tag_version.return_value = "1.0.0"
self.semver._scm.get_version_hash.return_value = "HASH"
self.semver._scm.get_hash.return_value = "ALT_HASH"
mock_bump_version.return_value = "1.0.1"
expected_version = "1.0.0+HASH"
version = self.semver.get_version(dot=True)
self.assertEqual(version, "feature.example")
@mock.patch("semver.semver.SemVer._bump_version")
def test_get_version_docker(self, mock_bump_version: mock.Mock):
self.semver._scm.get_branch.return_value = "feature/example"
self.semver._scm.get_tag_version.return_value = "1.0.0"
self.semver._scm.get_version_hash.return_value = "HASH"
self.semver._scm.get_hash.return_value = "ALT_HASH"
mock_bump_version.return_value = "1.0.1"
expected_version = "1.0.0+HASH"
version = self.semver.get_version(version_format="docker")
self.assertEqual(version, "1.0.1-feature-example.0")
@mock.patch("semver.semver.SemVer._bump_version")
def test_get_version_maven(self, mock_bump_version: mock.Mock):
self.semver._scm.get_branch.return_value = "feature/example"
self.semver._scm.get_tag_version.return_value = "1.0.0"
self.semver._scm.get_version_hash.return_value = "HASH"
self.semver._scm.get_hash.return_value = "ALT_HASH"
mock_bump_version.return_value = "1.0.1"
expected_version = "1.0.1-feature-example-SNAPSHOT"
version = self.semver.get_version(version_format="maven")
self.assertEqual(version, expected_version)
def test_get_version_no_hash(self):
self.semver._scm.get_branch.return_value = "main"
self.semver._scm.get_tag_version.return_value = "1.0.0"
self.semver._scm.get_version_hash.return_value = "HASH"
self.semver._scm.get_hash.return_value = "HASH"
expected_version = "1.0.0"
version = self.semver.get_version()
self.assertEqual(version, expected_version)

View File

@ -0,0 +1,59 @@
import unittest
from unittest import mock
from semver.utils import get_settings, setting_to_array
from semver.exceptions import SemverException
class TestUtils(unittest.TestCase):
@mock.patch("toml.load")
@mock.patch("pathlib.Path.is_file")
def test_get_settings_toml(self, mock_is_file: mock.Mock, mock_toml: mock.Mock):
get_settings.cache_clear()
mock_is_file.side_effect = [True, False]
mock_toml.return_value = {"1": {"a": "alpha", "fruit": "apple"}}
settings = get_settings()
self.assertEqual(settings, {"1": {"a": "alpha", "fruit": "apple"}})
@mock.patch("configparser.ConfigParser")
@mock.patch("pathlib.Path.is_file")
def test_get_settings_cfg(
self, mock_is_file: mock.Mock, mock_config_parser: mock.Mock
):
get_settings.cache_clear()
mock_is_file.side_effect = [False, True]
mock_config_parser.return_value.read.return_value = ["./.bumpversion.cfg"]
mock_config_parser.return_value.sections.return_value = ["1", "2", "3"]
mock_config_parser.return_value.items.side_effect = [
[("a", "alpha"), ("fruit", "apple")],
[("b", "bravo"), ("fruit", "banana")],
[("c", "charlie"), ("fruit", "cherry")],
]
settings = get_settings()
self.assertEqual(
settings,
{
"1": {"a": "alpha", "fruit": "apple"},
"2": {"b": "bravo", "fruit": "banana"},
"3": {"c": "charlie", "fruit": "cherry"},
},
)
@mock.patch("pathlib.Path.is_file")
def test_get_settings_no_file(self, mock_is_file: mock.Mock):
get_settings.cache_clear()
mock_is_file.side_effect = [False, False]
with self.assertRaises(SemverException):
get_settings()
@mock.patch("semver.utils.get_settings")
def test_setting_to_array(self, mock_get_settings: mock.Mock):
mock_get_settings.return_value = {"semver": {"test": "test1, test2"}}
settings = setting_to_array("test")
self.assertEqual(settings, ["test1", "test2"])

38
semver/utils.py Normal file
View File

@ -0,0 +1,38 @@
from typing import List
from pathlib import Path
from functools import cache
import configparser
import toml
from semver.exceptions import SemverException
@cache
def get_settings() -> dict:
"""
Get the settings from the config file
:return: The settings from the config file
"""
if Path("./.bumpversion.toml").is_file():
return toml.load("./.bumpversion.toml")
if Path("./.bumpversion.cfg").is_file():
config = configparser.ConfigParser()
config.read("./.bumpversion.cfg")
return {section: dict(config.items(section)) for section in config.sections()}
raise SemverException("No config file found")
def setting_to_array(setting) -> List[str]:
"""
Get a setting from the config file and return it as a list
:param setting: The setting to get from the config file
:return: The setting as a list
"""
config: dict = get_settings()
semver: dict = config.get("semver", {})
value: str = semver.get(setting, "")
return [v.strip() for v in value.split(",") if v.strip()]