diff --git a/src/main/python/ddadevops/release-mixin/.gitignore b/src/main/python/ddadevops/release-mixin/.gitignore new file mode 100644 index 0000000..58f5cd3 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/.gitignore @@ -0,0 +1,31 @@ +# ---> Go +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work + +__pycache__ + +.clj-kondo/ +.lsp/ +target/ + +# vs code settings +.vscode \ No newline at end of file diff --git a/src/main/python/ddadevops/release-mixin/LICENSE b/src/main/python/ddadevops/release-mixin/LICENSE new file mode 100644 index 0000000..2071b23 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/main/python/ddadevops/release-mixin/README.md b/src/main/python/ddadevops/release-mixin/README.md new file mode 100644 index 0000000..e8c70ca --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/README.md @@ -0,0 +1,2 @@ +# terraformDummyRepo + diff --git a/src/main/python/ddadevops/release-mixin/build.py b/src/main/python/ddadevops/release-mixin/build.py new file mode 100644 index 0000000..cfedec4 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/build.py @@ -0,0 +1,47 @@ +import sys +import os +from pathlib import Path +from ddadevops import * + +# getting the name of the directory +# where the this file is present. +current = os.path.dirname(os.path.realpath(__file__)) + +# adding the current directory to +# the sys.path. +sys.path.append(current) + +# now we can import the module in the current +# directory. + +from pybuilder.core import task, init +from ddadevops import * +from release_mixin import ReleaseMixin, create_release_mixin_config + +CONFIG_FILE = Path('config.json') +MAIN_BRANCH = 'main' +STAGE = 'test' +PROJECT_ROOT_PATH = '.' +MODULE = 'test' +BUILD_DIR_NAME = "build_dir" + +class MyBuild(ReleaseMixin): + pass + +@init +def initialize(project): + project.build_depends_on('ddadevops>=3.1.2') + config = create_release_mixin_config(CONFIG_FILE, MAIN_BRANCH) + config.update({'stage': STAGE, + 'module': MODULE, + 'project_root_path': PROJECT_ROOT_PATH, + 'build_dir_name': BUILD_DIR_NAME}) + build = MyBuild(project, config) + build.initialize_build_dir() + +@task +def release(project): + build = get_devops_build(project) + + build.prepare_release() + build.tag_and_push_release() diff --git a/src/main/python/ddadevops/release-mixin/config.json b/src/main/python/ddadevops/release-mixin/config.json new file mode 100644 index 0000000..6068f8d --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/config.json @@ -0,0 +1,3 @@ +{ + "version": "123.125.1-SNAPSHOT" +} \ No newline at end of file diff --git a/src/main/python/ddadevops/release-mixin/doc/arch.md b/src/main/python/ddadevops/release-mixin/doc/arch.md new file mode 100644 index 0000000..201223d --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/doc/arch.md @@ -0,0 +1 @@ +[![](https://mermaid.ink/img/pako:eNrtV99vmzAQ_lcsPzUSrUjIj8JDpUqb9jSpaqs9TJGQg6_UGxhmTNes6v8-E0MCGIem6-MiBYnz3Xd3vu8ulxccZRRwgAv4VQKP4BMjsSApUp81r54CIolEvDmbup6D6sdEn21KllB0fnWFbiEBUsBX9sx4gMKQcSbD8CwX2Q9l76Ao4w8sDh9YArUtiSR7IhI6pge3HWnl4QuT1zlrYU8sirXgfpvDLeRZwWQmti07DVRb50RIFrGccNk2tEB_A1GwjA_Cmhm2sWvL4yEP4ho-neEMHZQSxsONIDx6tGenD4BTo7oO8tV3NVLaXIBChVBoaVOFPc7MrfixcNDCtRXoRkPU8jsQTyyCVsbGbfQZMwigdQaPbHccg-zn0WflQb2TzEF8jHIt_FCqM5uTrl3HUfeo0wgVeqJQChlGWZoyacBrTS2kMCi2u2mdBOjQly2c8eh7kAPtUyXxpMVG-Ia6PjfENuwkI3TXjw3ymy0VhVTJ3mza4m5l46A6ozBhhZwY92bJ6yi1zPaort1psNSALYUALrv9v29zs2p972Pn4wgfMAJ-CyYhJJzWjO5352h3B6jpNxupOmOwfunWMhKgFEMD6FgPjIVnHXlGxo27OpzJO8baiS2oQ9iRveFtIQXj8ajvZhIRSs_erNydVeYP0QeyZ1Om-QnUqdSHyn06d2xI_4nzYcRpXeWRdWBPr4GFpyLaym3xzLbySBLvLjovi8fDRDqyqt6T-JrTG6Vu3XE6S-g-E5vhu3wNh61hrI7GIU9BakqnQ-GZVEnSf4zh5HSaICrDAfbYbG0du7v6HqmqJ3ZwCkLt4FT9m3qpJGssHyGFNVadhSkRP9d4zV-VHilldrflEQ4eSFKAg8ucKg_1X6-e9DOt2m0vVLv89yxTSlKU-hUHL_gZB-fT6cWlt_Td5dzz1ACdL30Hb5Xcny4uZjN_7k2ni5k39y5fHfxnBzG7cD135fnzxdJfrObu6vUveFPSvA?type=png)](https://mermaid.live/edit#pako:eNrtV99vmzAQ_lcsPzUSrUjIj8JDpUqb9jSpaqs9TJGQg6_UGxhmTNes6v8-E0MCGIem6-MiBYnz3Xd3vu8ulxccZRRwgAv4VQKP4BMjsSApUp81r54CIolEvDmbup6D6sdEn21KllB0fnWFbiEBUsBX9sx4gMKQcSbD8CwX2Q9l76Ao4w8sDh9YArUtiSR7IhI6pge3HWnl4QuT1zlrYU8sirXgfpvDLeRZwWQmti07DVRb50RIFrGccNk2tEB_A1GwjA_Cmhm2sWvL4yEP4ho-neEMHZQSxsONIDx6tGenD4BTo7oO8tV3NVLaXIBChVBoaVOFPc7MrfixcNDCtRXoRkPU8jsQTyyCVsbGbfQZMwigdQaPbHccg-zn0WflQb2TzEF8jHIt_FCqM5uTrl3HUfeo0wgVeqJQChlGWZoyacBrTS2kMCi2u2mdBOjQly2c8eh7kAPtUyXxpMVG-Ia6PjfENuwkI3TXjw3ymy0VhVTJ3mza4m5l46A6ozBhhZwY92bJ6yi1zPaort1psNSALYUALrv9v29zs2p972Pn4wgfMAJ-CyYhJJzWjO5352h3B6jpNxupOmOwfunWMhKgFEMD6FgPjIVnHXlGxo27OpzJO8baiS2oQ9iRveFtIQXj8ajvZhIRSs_erNydVeYP0QeyZ1Om-QnUqdSHyn06d2xI_4nzYcRpXeWRdWBPr4GFpyLaym3xzLbySBLvLjovi8fDRDqyqt6T-JrTG6Vu3XE6S-g-E5vhu3wNh61hrI7GIU9BakqnQ-GZVEnSf4zh5HSaICrDAfbYbG0du7v6HqmqJ3ZwCkLt4FT9m3qpJGssHyGFNVadhSkRP9d4zV-VHilldrflEQ4eSFKAg8ucKg_1X6-e9DOt2m0vVLv89yxTSlKU-hUHL_gZB-fT6cWlt_Td5dzz1ACdL30Hb5Xcny4uZjN_7k2ni5k39y5fHfxnBzG7cD135fnzxdJfrObu6vUveFPSvA) \ No newline at end of file diff --git a/src/main/python/ddadevops/release-mixin/doc/architecture.png.png b/src/main/python/ddadevops/release-mixin/doc/architecture.png.png new file mode 100644 index 0000000..cef9e94 Binary files /dev/null and b/src/main/python/ddadevops/release-mixin/doc/architecture.png.png differ diff --git a/src/main/python/ddadevops/release-mixin/domain.py b/src/main/python/ddadevops/release-mixin/domain.py new file mode 100644 index 0000000..a95e847 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/domain.py @@ -0,0 +1,76 @@ +from enum import Enum +from pathlib import Path + +class ReleaseType(Enum): + MAJOR = 0 + MINOR = 1 + PATCH = 2 + SNAPSHOT = 3 + BUMP = None + +class Version(): + + def __init__(self, id: Path, version_list: list): + self.id = id + self.version_list = version_list + self.version_string = None + self.is_snapshot = None + + def increment(self, release_type: ReleaseType): + self.is_snapshot = False + match release_type: + case ReleaseType.BUMP: + self.is_snapshot = True + self.version_list[ReleaseType.PATCH.value] += 1 + case ReleaseType.SNAPSHOT: + self.is_snapshot = True + case ReleaseType.PATCH: + self.version_list[ReleaseType.PATCH.value] += 1 + case ReleaseType.MINOR: + self.version_list[ReleaseType.PATCH.value] = 0 + self.version_list[ReleaseType.MINOR.value] += 1 + case ReleaseType.MAJOR: + self.version_list[ReleaseType.PATCH.value] = 0 + self.version_list[ReleaseType.MINOR.value] = 0 + self.version_list[ReleaseType.MAJOR.value] += 1 + case None: + raise Exception("Release Type was not set!") + + def get_version_string(self) -> str: + self.version_string = ".".join([str(x) for x in self.version_list]) + if self.is_snapshot: + self.version_string += "-SNAPSHOT" + return self.version_string + + def create_release_version(self, release_type: ReleaseType): + release_version = Version(self.id, self.version_list.copy()) + release_version.is_snapshot = self.is_snapshot + release_version.increment(release_type) + return release_version + + def create_bump_version(self): + bump_version = Version(self.id, self.version_list.copy()) + bump_version.is_snapshot = self.is_snapshot + bump_version.increment(ReleaseType.BUMP) + return bump_version + +class Release(): + def __init__(self, release_type: ReleaseType, version: Version, current_branch: str): + self.release_type = release_type + self.version = version + self.current_branch = current_branch + + def release_version(self): + return self.version.create_release_version(self.release_type) + + def bump_version(self): + return self.release_version().create_bump_version() + + def validate(self, main_branch): + result = [] + if self.release_type is not None and main_branch != self.current_branch: + result.append(f"Releases are allowed only on {main_branch}") + return result + + def is_valid(self, main_branch): + return self.validate(main_branch).count < 1 diff --git a/src/main/python/ddadevops/release-mixin/infrastructure.py b/src/main/python/ddadevops/release-mixin/infrastructure.py new file mode 100644 index 0000000..b367c74 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/infrastructure.py @@ -0,0 +1,58 @@ +from domain import Release, Version, ReleaseType +from infrastructure_api import FileHandler + +class VersionRepository(): + + def __init__(self, file): + self.file = file + self.file_handler = None + + def load_file(self): + self.file_handler = FileHandler.from_file_path(self.file) + return self.file_handler + + def write_file(self, version_string): + if self.file_handler is None: + raise Exception('Version was not created by load_file method.') + else: + self.file_handler.write(version_string) + + def parse_file(self): + version_list, is_snapshot = self.file_handler.parse() + return version_list, is_snapshot + + def get_version(self) -> Version: + + self.file_handler = self.load_file() + version_list, is_snapshot = self.parse_file() + version = Version(self.file, version_list) + version.is_snapshot = is_snapshot + + return version + +class ReleaseTypeRepository(): + def __init__(self, git_api, environment_api=None): + self.git_api = git_api + + def get_release_type(self): + latest_commit = self.git_api.get_latest_commit() + + if ReleaseType.MAJOR.name in latest_commit.upper(): + return ReleaseType.MAJOR + elif ReleaseType.MINOR.name in latest_commit.upper(): + return ReleaseType.MINOR + elif ReleaseType.PATCH.name in latest_commit.upper(): + return ReleaseType.PATCH + elif ReleaseType.SNAPSHOT.name in latest_commit.upper(): + return ReleaseType.SNAPSHOT + else: + return None + +class ReleaseRepository(): + def __init__(self, version_repository: VersionRepository, release_type_repository: ReleaseTypeRepository, main_branch: str): + self.version_repository = version_repository + self.release_type_repository = release_type_repository + self.main_branch = main_branch + + def get_release(self) -> Release: + return Release(self.release_type_repository.get_release_type(), self.version_repository.get_version(), self.main_branch) diff --git a/src/main/python/ddadevops/release-mixin/infrastructure_api.py b/src/main/python/ddadevops/release-mixin/infrastructure_api.py new file mode 100644 index 0000000..bd86de5 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/infrastructure_api.py @@ -0,0 +1,237 @@ +from abc import ABC, abstractmethod +from pathlib import Path +import json +import re +import subprocess as sub + + +class FileHandler(ABC): + + @classmethod + def from_file_path(cls, file_path): + config_file_type = file_path.suffix + match config_file_type: + case '.json': + file_handler = JsonFileHandler() + case '.gradle': + file_handler = GradleFileHandler() + case '.clj': + file_handler = ClojureFileHandler() + case '.py': + file_handler = PythonFileHandler() + case _: + raise Exception( + f'The file type "{config_file_type}" is not implemented') + + file_handler.config_file_path = file_path + file_handler.config_file_type = config_file_type + return file_handler + + @abstractmethod + def parse(self) -> tuple[list[int], bool]: + pass + + @abstractmethod + def write(self, version_string): + pass + + +class JsonFileHandler(FileHandler): + + def parse(self) -> tuple[list[int], bool]: + with open(self.config_file_path, 'r') as json_file: + json_version = json.load(json_file)['version'] + is_snapshot = False + if '-SNAPSHOT' in json_version: + is_snapshot = True + json_version = json_version.replace('-SNAPSHOT', '') + version = [int(x) for x in json_version.split('.')] + return version, is_snapshot + + def write(self, version_string): + with open(self.config_file_path, 'r+') as json_file: + json_data = json.load(json_file) + json_data['version'] = version_string + json_file.seek(0) + json.dump(json_data, json_file, indent=4) + json_file.truncate() + + +class GradleFileHandler(FileHandler): + + def parse(self) -> tuple[list[int], bool]: + with open(self.config_file_path, 'r') as gradle_file: + contents = gradle_file.read() + version_line = re.search("\nversion = .*", contents) + exception = Exception("Version not found in gradle file") + if version_line is None: + raise exception + + version_line = version_line.group() + version_string = re.search( + '[0-9]*\\.[0-9]*\\.[0-9]*(-SNAPSHOT)?', version_line) + if version_string is None: + raise exception + + version_string = version_string.group() + is_snapshot = False + if '-SNAPSHOT' in version_string: + is_snapshot = True + version_string = version_string.replace('-SNAPSHOT', '') + + version = [int(x) for x in version_string.split('.')] + + return version, is_snapshot + + def write(self, version_string): + with open(self.config_file_path, 'r+') as gradle_file: + contents = gradle_file.read() + version_substitute = re.sub( + '\nversion = "[0-9]*\\.[0-9]*\\.[0-9]*(-SNAPSHOT)?"', f'\nversion = "{version_string}"', contents) + gradle_file.seek(0) + gradle_file.write(version_substitute) + gradle_file.truncate() + + +class PythonFileHandler(FileHandler): + + def parse(self) -> tuple[list[int], bool]: + with open(self.config_file_path, 'r') as python_file: + contents = python_file.read() + version_line = re.search("\nversion = .*\n", contents) + exception = Exception("Version not found in gradle file") + if version_line is None: + raise exception + + version_line = version_line.group() + version_string = re.search( + '[0-9]*\\.[0-9]*\\.[0-9]*(-SNAPSHOT)?', version_line) + if version_string is None: + raise exception + + version_string = version_string.group() + is_snapshot = False + if '-SNAPSHOT' in version_string: + is_snapshot = True + version_string = version_string.replace('-SNAPSHOT', '') + + version = [int(x) for x in version_string.split('.')] + + return version, is_snapshot + + def write(self, version_string): + with open(self.config_file_path, 'r+') as python_file: + contents = python_file.read() + version_substitute = re.sub( + '\nversion = "[0-9]*\\.[0-9]*\\.[0-9]*(-SNAPSHOT)?"', f'\nversion = "{version_string}"', contents) + python_file.seek(0) + python_file.write(version_substitute) + python_file.truncate() + + +class ClojureFileHandler(FileHandler): + + def parse(self) -> tuple[list[int], bool]: + with open(self.config_file_path, 'r') as clj_file: + contents = clj_file.read() + version_line = re.search("^\\(defproject .*\n", contents) + exception = Exception("Version not found in clj file") + if version_line is None: + raise exception + + version_line = version_line.group() + version_string = re.search( + '[0-9]*\\.[0-9]*\\.[0-9]*(-SNAPSHOT)?', version_line) + if version_string is None: + raise exception + + version_string = version_string.group() + is_snapshot = False + if '-SNAPSHOT' in version_string: + is_snapshot = True + version_string = version_string.replace('-SNAPSHOT', '') + + version = [int(x) for x in version_string.split('.')] + + return version, is_snapshot + + def write(self, version_string): + with open(self.config_file_path, 'r+') as clj_file: + clj_first = clj_file.readline() + clj_rest = clj_file.read() + version_substitute = re.sub( + '[0-9]*\\.[0-9]*\\.[0-9]*(-SNAPSHOT)?', f'"{version_string}"\n', clj_first) + clj_file.seek(0) + clj_file.write(version_substitute) + clj_file.write(clj_rest) + clj_file.truncate() + + +class SystemAPI(): + + def __init__(self): + self.stdout = [""] + self.stderr = [""] + + def run(self, args): + stream = sub.Popen(args, + stdout=sub.PIPE, + stderr=sub.PIPE, + text=True, + encoding="UTF-8") + self.stdout = stream.stdout.readlines() + self.stderr = stream.stderr.readlines() + + def run_checked(self, *args): + self.run(args) + + if len(self.stderr) > 0: + raise Exception(f"Command failed with: {self.stderr}") + + +class GitApi(): + + def __init__(self): + self.system_api = SystemAPI() + + def get_latest_n_commits(self, n: int): + self.system_api.run_checked( + 'git', 'log', '--oneline', '--format="%s %b"', f'-n {n}') + return self.system_api.stdout + + def get_latest_commit(self): + output = self.get_latest_n_commits(1) + return " ".join(output) + + def tag_annotated(self, annotation: str, message: str, count: int): + self.system_api.run_checked( + 'git', 'tag', '-a', annotation, '-m', message, f'HEAD~{count}') + return self.system_api.stdout + + def get_latest_tag(self): + self.system_api.run_checked('git', 'describe', '--tags', '--abbrev=0') + return self.system_api.stdout + + def get_current_branch(self): + self.system_api.run_checked('git', 'branch', '--show-current') + return ''.join(self.system_api.stdout).rstrip() + + def init(self): + self.system_api.run_checked('git', 'init') + + def add_file(self, file_path: Path): + self.system_api.run_checked('git', 'add', file_path) + return self.system_api.stdout + + def commit(self, commit_message: str): + self.system_api.run_checked( + 'git', 'commit', '-m', commit_message) + return self.system_api.stdout + + def push(self): + self.system_api.run_checked('git', 'push') + return self.system_api.stdout + + def checkout(self, branch: str): + self.system_api.run_checked('git', 'checkout', branch) + return self.system_api.stdout diff --git a/src/main/python/ddadevops/release-mixin/release_mixin.py b/src/main/python/ddadevops/release-mixin/release_mixin.py new file mode 100644 index 0000000..03f3c99 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/release_mixin.py @@ -0,0 +1,43 @@ +import copy +from ddadevops import DevopsBuild +from ddadevops import execute +from ddadevops import gopass_field_from_path, gopass_password_from_path +from infrastructure import ReleaseRepository, ReleaseTypeRepository, VersionRepository +from infrastructure_api import GitApi +from services import PrepareReleaseService, TagAndPushReleaseService + +def create_release_mixin_config(config_file, main_branch) -> dict: + config = {} + config.update( + {'ReleaseMixin': + {'main_branch': main_branch, + 'config_file': config_file}}) + return config + +def add_versions(config, release_version, bump_version) -> dict: + config['ReleaseMixin'].update( + {'release_version': release_version, + 'bump_version': bump_version}) + return config + +class ReleaseMixin(DevopsBuild): + + def __init__(self, project, config): # todo: create services in init, dont expose repos etc in api + super().__init__(project, config) + release_mixin_config = config['ReleaseMixin'] + self.config_file = release_mixin_config['config_file'] + self.main_branch = release_mixin_config['main_branch'] + self.git_api = GitApi() + self.release_type_repo = ReleaseTypeRepository(self.git_api) # maybe get from env? + self.version_repo = VersionRepository(self.config_file) + self.release_repo = ReleaseRepository(self.version_repo, self.release_type_repo, self.main_branch) + + def prepare_release(self): + prepare_release_service = PrepareReleaseService(self.release_repo) + prepare_release_service.write_and_commit_release() + prepare_release_service.write_and_commit_bump() + + def tag_and_push_release(self): + tag_and_push_release_service = TagAndPushReleaseService(self.git_api) + tag_and_push_release_service.tag_release(self.release_repo.get_release()) + # tag_and_push_release_service.push_release() diff --git a/src/main/python/ddadevops/release-mixin/services.py b/src/main/python/ddadevops/release-mixin/services.py new file mode 100644 index 0000000..42b8543 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/services.py @@ -0,0 +1,36 @@ +from infrastructure import ReleaseRepository +from infrastructure_api import GitApi +from domain import Version, Release + +class PrepareReleaseService(): + + def __init__(self, release_repo: ReleaseRepository): + self.release_repo = release_repo + self.release = release_repo.get_release() + self.git_api = GitApi() + + def __write_and_commit_version(self, version: Version, commit_message: str): + self.release.validate(self.release_repo.main_branch) + + self.release_repo.version_repository.write_file(version.get_version_string()) + self.git_api.add_file(self.release_repo.version_repository.file) + self.git_api.commit(commit_message) + + def write_and_commit_release(self): + self.__write_and_commit_version(self.release.release_version(), commit_message=f'Release v{self.release.release_version().get_version_string()}') + + def write_and_commit_bump(self): + self.__write_and_commit_version(self.release.bump_version(), commit_message='Version bump') + +class TagAndPushReleaseService(): + + def __init__(self, git_api: GitApi): + self.git_api = git_api + + def tag_release(self, release: Release): + annotation = 'v' + release.version.get_version_string() + message = 'Release ' + annotation + self.git_api.tag_annotated(annotation, message, 1) + + def push_release(self): + self.git_api.push() diff --git a/src/main/python/ddadevops/release-mixin/test/resources/config.clj b/src/main/python/ddadevops/release-mixin/test/resources/config.clj new file mode 100644 index 0000000..c329c34 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/resources/config.clj @@ -0,0 +1,5 @@ +(defproject org.domaindrivenarchitecture/c4k-website "1.1.3" + :description "website c4k-installation package" + :url "https://domaindrivenarchitecture.org" + :license {:name "Apache License, Version 2.0" + :url "https://www.apache.org/licenses/LICENSE-2.0.html"}) \ No newline at end of file diff --git a/src/main/python/ddadevops/release-mixin/test/resources/config.gradle b/src/main/python/ddadevops/release-mixin/test/resources/config.gradle new file mode 100644 index 0000000..5c6a467 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/resources/config.gradle @@ -0,0 +1,2 @@ + +version = "12.4.678" diff --git a/src/main/python/ddadevops/release-mixin/test/resources/config.json b/src/main/python/ddadevops/release-mixin/test/resources/config.json new file mode 100644 index 0000000..f407ec1 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/resources/config.json @@ -0,0 +1,3 @@ +{ + "version": "123.123.456" +} \ No newline at end of file diff --git a/src/main/python/ddadevops/release-mixin/test/resources/config.py b/src/main/python/ddadevops/release-mixin/test/resources/config.py new file mode 100644 index 0000000..bb47bcd --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/resources/config.py @@ -0,0 +1,78 @@ +# dda_devops_build +# Copyright 2019 meissa GmbH. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from pybuilder.core import init, use_plugin, Author + +use_plugin("python.core") +use_plugin("copy_resources") +use_plugin("filter_resources") +#use_plugin("python.unittest") +#use_plugin("python.coverage") +use_plugin("python.distutils") + +#use_plugin("python.install_dependencies") + +default_task = "publish" + +name = "ddadevops" +version = "3.1.3" +summary = "tools to support builds combining gopass, terraform, dda-pallet, aws & hetzner-cloud" +description = __doc__ +authors = [Author("meissa GmbH", "buero@meissa-gmbh.de")] +url = "https://github.com/DomainDrivenArchitecture/dda-devops-build" +requires_python = ">=2.7,!=3.0,!=3.1,!=3.2,!=3.3,!=3.4" # CHECK IF NEW VERSION EXISTS +license = "Apache Software License" + +@init +def initialize(project): + #project.build_depends_on('mockito') + #project.build_depends_on('unittest-xml-reporting') + + project.set_property("verbose", True) + project.get_property("filter_resources_glob").append("main/python/ddadevops/__init__.py") + #project.set_property("dir_source_unittest_python", "src/unittest/python") + + project.set_property("copy_resources_target", "$dir_dist/ddadevops") + project.get_property("copy_resources_glob").append("LICENSE") + project.get_property("copy_resources_glob").append("src/main/resources/terraform/*") + project.get_property("copy_resources_glob").append("src/main/resources/docker/image/resources/*") + project.include_file("ddadevops", "LICENSE") + project.include_file("ddadevops", "src/main/resources/terraform/*") + project.include_file("ddadevops", "src/main/resources/docker/image/resources/*") + + #project.set_property('distutils_upload_sign', True) + #project.set_property('distutils_upload_sign_identity', '') + project.set_property("distutils_readme_description", True) + project.set_property("distutils_description_overwrite", True) + project.set_property("distutils_classifiers", [ + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Operating System :: POSIX :: Linux', + 'Operating System :: OS Independent', + 'Development Status :: 5 - Production/Stable', + 'Environment :: Console', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Apache Software License', + 'Topic :: Software Development :: Build Tools', + 'Topic :: Software Development :: Quality Assurance', + 'Topic :: Software Development :: Testing' + ]) diff --git a/src/main/python/ddadevops/release-mixin/test/test_domain.py b/src/main/python/ddadevops/release-mixin/test/test_domain.py new file mode 100644 index 0000000..abef6d1 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/test_domain.py @@ -0,0 +1,61 @@ +from pathlib import Path +import sys +import os + +# getting the name of the directory +# where the this file is present. +current = os.path.dirname(os.path.realpath(__file__)) + +# Getting the parent directory name +# where the current directory is present. +parent = os.path.dirname(current) + +# adding the parent directory to +# the sys.path. +sys.path.append(parent) + +# now we can import the module in the parent +# directory. + +from domain import Version, ReleaseType, Release + +def test_version(tmp_path: Path): + version = Version(tmp_path, [1, 2, 3]) + version.increment(ReleaseType.SNAPSHOT) + assert version.get_version_string() == "1.2.3-SNAPSHOT" + assert version.version_list == [1, 2, 3] + assert version.is_snapshot + + version = Version(tmp_path, [1, 2, 3]) + version.increment(ReleaseType.BUMP) + assert version.get_version_string() == "1.2.4-SNAPSHOT" + assert version.version_list == [1, 2, 4] + assert version.is_snapshot + + version = Version(tmp_path, [1, 2, 3]) + version.increment(ReleaseType.PATCH) + assert version.get_version_string() == "1.2.4" + assert version.version_list == [1, 2, 4] + assert not version.is_snapshot + + version = Version(tmp_path, [1, 2, 3]) + version.increment(ReleaseType.MINOR) + assert version.get_version_string() == "1.3.0" + assert version.version_list == [1, 3, 0] + assert not version.is_snapshot + + version = Version(tmp_path, [1, 2, 3]) + version.increment(ReleaseType.MAJOR) + assert version.get_version_string() == "2.0.0" + assert version.version_list == [2, 0, 0] + assert not version.is_snapshot + +def test_release(tmp_path): + version = Version(tmp_path, [1, 2, 3]) + release = Release(ReleaseType.MINOR, version, "main") + + release_version = release.release_version() + assert release_version.get_version_string() in '1.3.0' + + bump_version = release.bump_version() + assert bump_version.get_version_string() in "1.3.1-SNAPSHOT" diff --git a/src/main/python/ddadevops/release-mixin/test/test_infrastructure.py b/src/main/python/ddadevops/release-mixin/test/test_infrastructure.py new file mode 100644 index 0000000..3aa05c0 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/test_infrastructure.py @@ -0,0 +1,147 @@ +from pathlib import Path +import sys +import os + +# getting the name of the directory +# where the this file is present. +current = os.path.dirname(os.path.realpath(__file__)) + +# Getting the parent directory name +# where the current directory is present. +parent = os.path.dirname(current) + +# adding the parent directory to +# the sys.path. +sys.path.append(parent) + +# now we can import the module in the parent +# directory. + +from domain import ReleaseType, Release +from infrastructure import ReleaseTypeRepository, VersionRepository, ReleaseRepository +from infrastructure_api import GitApi + +class MyGitApi(GitApi): + def __init__(self, commit_string): + self.commit_string = commit_string + + def get_latest_commit(self): + return self.commit_string + + +def test_gradle(tmp_path): + # init + file_name = 'config.gradle' + with open(f'test/resources/{file_name}', 'r') as gradle_file: + contents = gradle_file.read() + + f = tmp_path / file_name + f.write_text(contents) + + # test + repo = VersionRepository(f) + version = repo.get_version() + version = version.create_release_version(ReleaseType.SNAPSHOT) + repo.write_file(version.get_version_string()) + + # check + assert 'version = "12.4.678-SNAPSHOT"' in f.read_text() + + +def test_json(tmp_path): + # init + file_name = 'config.json' + with open(f'test/resources/{file_name}', 'r') as gradle_file: + contents = gradle_file.read() + + f = tmp_path / file_name + f.write_text(contents) + + # test + repo = VersionRepository(f) + version = repo.get_version() + version = version.create_release_version(ReleaseType.SNAPSHOT) + repo.write_file(version.get_version_string()) + + # check + assert '"version": "123.123.456-SNAPSHOT"' in f.read_text() + + +def test_clojure(tmp_path): + # init + file_name = 'config.clj' + with open(f'test/resources/{file_name}', 'r') as gradle_file: + contents = gradle_file.read() + + f = tmp_path / file_name + f.write_text(contents) + + # test + repo = VersionRepository(f) + version = repo.get_version() + version = version.create_release_version(ReleaseType.SNAPSHOT) + repo.write_file(version.get_version_string()) + + # check + assert '1.1.3-SNAPSHOT' in f.read_text() + + +def test_python(tmp_path): + # init + file_name = 'config.py' + with open(f'test/resources/{file_name}', 'r') as gradle_file: + contents = gradle_file.read() + + f = tmp_path / file_name + f.write_text(contents) + + # test + repo = VersionRepository(f) + version = repo.get_version() + version = version.create_release_version(ReleaseType.SNAPSHOT) + repo.write_file(version.get_version_string()) + + # check + assert '3.1.3-SNAPSHOT' in f.read_text() + + +def test_release_repository(tmp_path): + # init + file_name = 'config.json' + with open(f'test/resources/{file_name}', 'r') as gradle_file: + contents = gradle_file.read() + + f = tmp_path / file_name + f.write_text(contents) + + # test + sut = ReleaseRepository(VersionRepository(f), ReleaseTypeRepository(MyGitApi('MINOR test')), 'main') + release = sut.get_release() + + assert release is not None + + +def test_release_type_repository(): + sut = ReleaseTypeRepository(MyGitApi('MINOR test')) + release_type = sut.get_release_type() + assert release_type is ReleaseType.MINOR + + sut = ReleaseTypeRepository(MyGitApi('MINOR bla')) + release_type = sut.get_release_type() + assert release_type is ReleaseType.MINOR + + sut = ReleaseTypeRepository(MyGitApi('Major bla')) + release_type = sut.get_release_type() + assert release_type == ReleaseType.MAJOR + + sut = ReleaseTypeRepository(MyGitApi('PATCH bla')) + release_type = sut.get_release_type() + assert release_type == ReleaseType.PATCH + + sut = ReleaseTypeRepository(MyGitApi('SNAPSHOT bla')) + release_type = sut.get_release_type() + assert release_type == ReleaseType.SNAPSHOT + + sut = ReleaseTypeRepository(MyGitApi('bla')) + release_type = sut.get_release_type() + assert release_type == None diff --git a/src/main/python/ddadevops/release-mixin/test/test_infrastructure_api.py b/src/main/python/ddadevops/release-mixin/test/test_infrastructure_api.py new file mode 100644 index 0000000..d914d32 --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/test_infrastructure_api.py @@ -0,0 +1,20 @@ +from pathlib import Path +import sys +import os + +# getting the name of the directory +# where the this file is present. +current = os.path.dirname(os.path.realpath(__file__)) + +# Getting the parent directory name +# where the current directory is present. +parent = os.path.dirname(current) + +# adding the parent directory to +# the sys.path. +sys.path.append(parent) + +# now we can import the module in the parent +# directory. + +from infrastructure_api import GitApi # todo: implement from services example diff --git a/src/main/python/ddadevops/release-mixin/test/test_release_mixin.py b/src/main/python/ddadevops/release-mixin/test/test_release_mixin.py new file mode 100644 index 0000000..e85360b --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/test_release_mixin.py @@ -0,0 +1,69 @@ +import sys +import os +import pytest as pt +from pathlib import Path +from ddadevops import * + +# getting the name of the directory +# where the this file is present. +current = os.path.dirname(os.path.realpath(__file__)) + +# Getting the parent directory name +# where the current directory is present. +parent = os.path.dirname(current) + +# adding the parent directory to +# the sys.path. +sys.path.append(parent) + +# now we can import the module in the parent +# directory. + +from pybuilder.core import task, init, Project +from release_mixin import ReleaseMixin, create_release_mixin_config + +MAIN_BRANCH = 'main' +STAGE = 'test' +PROJECT_ROOT_PATH = '.' +MODULE = 'test' +BUILD_DIR_NAME = "build_dir" + +class MyBuild(ReleaseMixin): + pass + +def initialize(project, CONFIG_FILE): + project.build_depends_on('ddadevops>=3.1.2') + config = create_release_mixin_config(CONFIG_FILE, MAIN_BRANCH) + config.update({'stage': STAGE, + 'module': MODULE, + 'project_root_path': PROJECT_ROOT_PATH, + 'build_dir_name': BUILD_DIR_NAME}) + build = MyBuild(project, config) + return build + +#def test_release_mixin(tmp_path): +# +# #init +# with open(f'test/resources/config.json', 'r') as json_file: +# contents = json_file.read() +# +# CONFIG_FILE = tmp_path / "config.json" +# CONFIG_FILE.write_text(contents) +# +# base_dir = "." +# project = Project(base_dir) +# +# # init +# build = initialize(project, CONFIG_FILE) +# build.commit_string = "MAJOR bla" +# build.init_release() +# release_version = build.release_version +# +# # test +# assert "124.0.0" in release_version.get_version_string() +# +# # init +# bump_version = build.bump_version +# +# # test +# assert "124.0.1-SNAPSHOT" in bump_version.get_version_string() \ No newline at end of file diff --git a/src/main/python/ddadevops/release-mixin/test/test_services.py b/src/main/python/ddadevops/release-mixin/test/test_services.py new file mode 100644 index 0000000..4b3926c --- /dev/null +++ b/src/main/python/ddadevops/release-mixin/test/test_services.py @@ -0,0 +1,79 @@ +import pytest as pt +from pathlib import Path +import sys +import os + +# getting the name of the directory +# where the this file is present. +current = os.path.dirname(os.path.realpath(__file__)) + +# Getting the parent directory name +# where the current directory is present. +parent = os.path.dirname(current) + +# adding the parent directory to +# the sys.path. +sys.path.append(parent) + +# now we can import the module in the parent +# directory. + +from services import PrepareReleaseService, TagAndPushReleaseService +from infrastructure import VersionRepository, ReleaseRepository, ReleaseTypeRepository +from infrastructure_api import GitApi + +def change_test_dir( tmp_path: Path, monkeypatch: pt.MonkeyPatch): + monkeypatch.chdir(tmp_path) + +def test_prepare_release_service(tmp_path: Path, monkeypatch: pt.MonkeyPatch): # todo: maybe use mocks for service api tests + # init + file_name = 'config.json' + with open(f'test/resources/{file_name}', 'r') as json_file: + contents = json_file.read() + f = tmp_path / file_name + f.write_text(contents) + change_test_dir(tmp_path, monkeypatch) # change the context of the script execution to tmp_path + + git_api = GitApi() + git_api.init() + git_api.add_file(file_name) + git_api.commit("MINOR release") + + repo = ReleaseRepository(VersionRepository(f), ReleaseTypeRepository(GitApi()), 'main') + prepare_release_service = PrepareReleaseService(repo) + prepare_release_service.main_branch = "main" + prepare_release_service.write_and_commit_release() + + latest_commit = git_api.get_latest_commit() + + assert '"Release v123.124.0 "\n' in latest_commit + + prepare_release_service.write_and_commit_bump() + latest_commit = git_api.get_latest_commit() + + assert '"Version bump "\n' in latest_commit + +def test_tag_and_push_release_service(tmp_path: Path, monkeypatch: pt.MonkeyPatch): + # init + file_name = 'config.json' + with open(f'test/resources/{file_name}', 'r') as json_file: + contents = json_file.read() + f = tmp_path / file_name + f.write_text(contents) + change_test_dir(tmp_path, monkeypatch) # change the context of the script execution to tmp_path + + git_api = GitApi() + git_api.init() + git_api.add_file(file_name) + git_api.commit("MINOR release") + + repo = ReleaseRepository(VersionRepository(f), ReleaseTypeRepository(GitApi()), 'main') + + prepare_release_service = PrepareReleaseService(repo) + prepare_release_service.main_branch = "main" + prepare_release_service.write_and_commit_release() + + tag_and_push_release_service = TagAndPushReleaseService(git_api) + tag_and_push_release_service.tag_release(repo.get_release()) + + assert 'v123.124.0\n' in git_api.get_latest_tag()