commit 29b0d27f20075e94ec481287c3e5dd4cec816ad6 Author: Robert Kaussow Date: Sun May 3 23:42:52 2020 +0200 initial commit diff --git a/.drone.jsonnet b/.drone.jsonnet new file mode 100644 index 0000000..6050539 --- /dev/null +++ b/.drone.jsonnet @@ -0,0 +1,275 @@ +local PythonVersion(pyversion='3.5') = { + name: 'python' + std.strReplace(pyversion, '.', '') + '-pytest', + image: 'python:' + pyversion, + pull: 'always', + environment: { + PY_COLORS: 1, + }, + commands: [ + 'pip install -r dev-requirements.txt -qq', + 'pip install -qq .', + 'docker-autotag --help', + 'docker-autotag --version', + ], + depends_on: [ + 'clone', + ], +}; + +local PipelineLint = { + kind: 'pipeline', + name: 'lint', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + { + name: 'flake8', + image: 'python:3.8', + pull: 'always', + environment: { + PY_COLORS: 1, + }, + commands: [ + 'pip install -r dev-requirements.txt -qq', + 'pip install -qq .', + 'flake8 ./dockerautotag', + ], + }, + ], + trigger: { + ref: ['refs/heads/master', 'refs/tags/**', 'refs/pull/**'], + }, +}; + +local PipelineTest = { + kind: 'pipeline', + name: 'test', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + PythonVersion(pyversion='3.5'), + PythonVersion(pyversion='3.6'), + PythonVersion(pyversion='3.7'), + PythonVersion(pyversion='3.8'), + ], + trigger: { + ref: ['refs/heads/master', 'refs/tags/**', 'refs/pull/**'], + }, + depends_on: [ + 'lint', + ], +}; + +local PipelineSecurity = { + kind: 'pipeline', + name: 'security', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + { + name: 'bandit', + image: 'python:3.8', + pull: 'always', + environment: { + PY_COLORS: 1, + }, + commands: [ + 'pip install -r dev-requirements.txt -qq', + 'pip install -qq .', + 'bandit -r ./dockerautotag -x ./dockerautotag/tests', + ], + }, + ], + depends_on: [ + 'test', + ], + trigger: { + ref: ['refs/heads/master', 'refs/tags/**', 'refs/pull/**'], + }, +}; + +local PipelineBuildPackage = { + kind: 'pipeline', + name: 'build-package', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + { + name: 'build', + image: 'python:3.8', + commands: [ + 'python setup.py sdist bdist_wheel', + ], + }, + { + name: 'checksum', + image: 'alpine', + commands: [ + 'cd dist/ && sha256sum * > ../sha256sum.txt', + ], + }, + { + name: 'publish-github', + image: 'plugins/github-release', + settings: { + overwrite: true, + api_key: { from_secret: 'github_token' }, + files: ['dist/*', 'sha256sum.txt'], + title: '${DRONE_TAG}', + note: 'CHANGELOG.md', + }, + when: { + ref: ['refs/tags/**'], + }, + }, + { + name: 'publish-pypi', + image: 'plugins/pypi', + settings: { + username: { from_secret: 'pypi_username' }, + password: { from_secret: 'pypi_password' }, + repository: 'https://upload.pypi.org/legacy/', + skip_build: true, + }, + when: { + ref: ['refs/tags/**'], + }, + }, + ], + depends_on: [ + 'security', + ], + trigger: { + ref: ['refs/heads/master', 'refs/tags/**', 'refs/pull/**'], + }, +}; + +local PipelineBuildContainer(arch='amd64') = { + kind: 'pipeline', + name: 'build-container-' + arch, + platform: { + os: 'linux', + arch: arch, + }, + steps: [ + { + name: 'build', + image: 'python:3.8', + pull: 'always', + commands: [ + 'python setup.py bdist_wheel', + ], + }, + { + name: 'dryrun', + image: 'plugins/docker:18-linux-' + arch, + pull: 'always', + settings: { + dry_run: true, + dockerfile: 'Dockerfile', + repo: 'xoxys/docker-autotag', + username: { from_secret: 'docker_username' }, + password: { from_secret: 'docker_password' }, + }, + when: { + ref: ['refs/pull/**'], + }, + }, + { + name: 'publish', + image: 'plugins/docker:18-linux-' + arch, + pull: 'always', + settings: { + auto_tag: true, + auto_tag_suffix: arch, + dockerfile: 'Dockerfile', + repo: 'xoxys/docker-autotag', + username: { from_secret: 'docker_username' }, + password: { from_secret: 'docker_password' }, + }, + when: { + ref: ['refs/heads/master', 'refs/tags/**'], + }, + }, + ], + depends_on: [ + 'security', + ], + trigger: { + ref: ['refs/heads/master', 'refs/tags/**', 'refs/pull/**'], + }, +}; + +local PipelineNotifications = { + kind: 'pipeline', + name: 'notifications', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + { + image: 'plugins/manifest', + name: 'manifest', + settings: { + ignore_missing: true, + auto_tag: true, + username: { from_secret: 'docker_username' }, + password: { from_secret: 'docker_password' }, + spec: 'manifest.tmpl', + }, + }, + { + name: 'readme', + image: 'sheogorath/readme-to-dockerhub', + environment: { + DOCKERHUB_USERNAME: { from_secret: 'docker_username' }, + DOCKERHUB_PASSWORD: { from_secret: 'docker_password' }, + DOCKERHUB_REPO_PREFIX: 'xoxys', + DOCKERHUB_REPO_NAME: 'docker-autotag', + README_PATH: 'README.md', + SHORT_DESCRIPTION: 'docker-autotag - Automate cloning a single branch from a repo list', + }, + }, + { + name: 'matrix', + image: 'plugins/matrix', + settings: { + homeserver: { from_secret: 'matrix_homeserver' }, + roomid: { from_secret: 'matrix_roomid' }, + template: 'Status: **{{ build.status }}**
Build: [{{ repo.Owner }}/{{ repo.Name }}]({{ build.link }}) ({{ build.branch }}) by {{ build.author }}
Message: {{ build.message }}', + username: { from_secret: 'matrix_username' }, + password: { from_secret: 'matrix_password' }, + }, + }, + ], + depends_on: [ + 'build-package', + 'build-container-amd64', + 'build-container-arm64', + 'build-container-arm', + ], + trigger: { + ref: ['refs/heads/master', 'refs/tags/**'], + status: ['success', 'failure'], + }, +}; + +[ + PipelineLint, + PipelineTest, + PipelineSecurity, + PipelineBuildPackage, + PipelineBuildContainer(arch='amd64'), + PipelineBuildContainer(arch='arm64'), + PipelineBuildContainer(arch='arm'), + PipelineNotifications, +] diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..89bdff0 --- /dev/null +++ b/.drone.yml @@ -0,0 +1,411 @@ +--- +kind: pipeline +name: lint + +platform: + os: linux + arch: amd64 + +steps: +- name: flake8 + pull: always + image: python:3.8 + commands: + - pip install -r dev-requirements.txt -qq + - pip install -qq . + - flake8 ./dockerautotag + environment: + PY_COLORS: 1 + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +--- +kind: pipeline +name: test + +platform: + os: linux + arch: amd64 + +steps: +- name: python35-pytest + pull: always + image: python:3.5 + commands: + - pip install -r dev-requirements.txt -qq + - pip install -qq . + - docker-autotag --help + - docker-autotag --version + environment: + PY_COLORS: 1 + depends_on: + - clone + +- name: python36-pytest + pull: always + image: python:3.6 + commands: + - pip install -r dev-requirements.txt -qq + - pip install -qq . + - docker-autotag --help + - docker-autotag --version + environment: + PY_COLORS: 1 + depends_on: + - clone + +- name: python37-pytest + pull: always + image: python:3.7 + commands: + - pip install -r dev-requirements.txt -qq + - pip install -qq . + - docker-autotag --help + - docker-autotag --version + environment: + PY_COLORS: 1 + depends_on: + - clone + +- name: python38-pytest + pull: always + image: python:3.8 + commands: + - pip install -r dev-requirements.txt -qq + - pip install -qq . + - docker-autotag --help + - docker-autotag --version + environment: + PY_COLORS: 1 + depends_on: + - clone + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- lint + +--- +kind: pipeline +name: security + +platform: + os: linux + arch: amd64 + +steps: +- name: bandit + pull: always + image: python:3.8 + commands: + - pip install -r dev-requirements.txt -qq + - pip install -qq . + - bandit -r ./dockerautotag -x ./dockerautotag/tests + environment: + PY_COLORS: 1 + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- test + +--- +kind: pipeline +name: build-package + +platform: + os: linux + arch: amd64 + +steps: +- name: build + image: python:3.8 + commands: + - python setup.py sdist bdist_wheel + +- name: checksum + image: alpine + commands: + - cd dist/ && sha256sum * > ../sha256sum.txt + +- name: publish-github + image: plugins/github-release + settings: + api_key: + from_secret: github_token + files: + - dist/* + - sha256sum.txt + note: CHANGELOG.md + overwrite: true + title: ${DRONE_TAG} + when: + ref: + - refs/tags/** + +- name: publish-pypi + image: plugins/pypi + settings: + password: + from_secret: pypi_password + repository: https://upload.pypi.org/legacy/ + skip_build: true + username: + from_secret: pypi_username + when: + ref: + - refs/tags/** + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- security + +--- +kind: pipeline +name: build-container-amd64 + +platform: + os: linux + arch: amd64 + +steps: +- name: build + pull: always + image: python:3.8 + commands: + - python setup.py bdist_wheel + +- name: dryrun + pull: always + image: plugins/docker:18-linux-amd64 + settings: + dockerfile: Dockerfile + dry_run: true + password: + from_secret: docker_password + repo: xoxys/docker-autotag + username: + from_secret: docker_username + when: + ref: + - refs/pull/** + +- name: publish + pull: always + image: plugins/docker:18-linux-amd64 + settings: + auto_tag: true + auto_tag_suffix: amd64 + dockerfile: Dockerfile + password: + from_secret: docker_password + repo: xoxys/docker-autotag + username: + from_secret: docker_username + when: + ref: + - refs/heads/master + - refs/tags/** + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- security + +--- +kind: pipeline +name: build-container-arm64 + +platform: + os: linux + arch: arm64 + +steps: +- name: build + pull: always + image: python:3.8 + commands: + - python setup.py bdist_wheel + +- name: dryrun + pull: always + image: plugins/docker:18-linux-arm64 + settings: + dockerfile: Dockerfile + dry_run: true + password: + from_secret: docker_password + repo: xoxys/docker-autotag + username: + from_secret: docker_username + when: + ref: + - refs/pull/** + +- name: publish + pull: always + image: plugins/docker:18-linux-arm64 + settings: + auto_tag: true + auto_tag_suffix: arm64 + dockerfile: Dockerfile + password: + from_secret: docker_password + repo: xoxys/docker-autotag + username: + from_secret: docker_username + when: + ref: + - refs/heads/master + - refs/tags/** + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- security + +--- +kind: pipeline +name: build-container-arm + +platform: + os: linux + arch: arm + +steps: +- name: build + pull: always + image: python:3.8 + commands: + - python setup.py bdist_wheel + +- name: dryrun + pull: always + image: plugins/docker:18-linux-arm + settings: + dockerfile: Dockerfile + dry_run: true + password: + from_secret: docker_password + repo: xoxys/docker-autotag + username: + from_secret: docker_username + when: + ref: + - refs/pull/** + +- name: publish + pull: always + image: plugins/docker:18-linux-arm + settings: + auto_tag: true + auto_tag_suffix: arm + dockerfile: Dockerfile + password: + from_secret: docker_password + repo: xoxys/docker-autotag + username: + from_secret: docker_username + when: + ref: + - refs/heads/master + - refs/tags/** + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- security + +--- +kind: pipeline +name: notifications + +platform: + os: linux + arch: amd64 + +steps: +- name: manifest + image: plugins/manifest + settings: + auto_tag: true + ignore_missing: true + password: + from_secret: docker_password + spec: manifest.tmpl + username: + from_secret: docker_username + +- name: readme + image: sheogorath/readme-to-dockerhub + environment: + DOCKERHUB_PASSWORD: + from_secret: docker_password + DOCKERHUB_REPO_NAME: docker-autotag + DOCKERHUB_REPO_PREFIX: xoxys + DOCKERHUB_USERNAME: + from_secret: docker_username + README_PATH: README.md + SHORT_DESCRIPTION: docker-autotag - Automate cloning a single branch from a repo list + +- name: matrix + image: plugins/matrix + settings: + homeserver: + from_secret: matrix_homeserver + password: + from_secret: matrix_password + roomid: + from_secret: matrix_roomid + template: "Status: **{{ build.status }}**
Build: [{{ repo.Owner }}/{{ repo.Name }}]({{ build.link }}) ({{ build.branch }}) by {{ build.author }}
Message: {{ build.message }}" + username: + from_secret: matrix_username + +trigger: + ref: + - refs/heads/master + - refs/tags/** + status: + - success + - failure + +depends_on: +- build-package +- build-container-amd64 +- build-container-arm64 +- build-container-arm + +--- +kind: signature +hmac: a58be4e73614e614db6ea5d8e7a9aed43595c39a6af432ff2b666abeda695a12 + +... diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..83ef6c0 --- /dev/null +++ b/.flake8 @@ -0,0 +1,18 @@ +[flake8] +ignore = D102, D103, D107, D202, W503 +max-line-length = 99 +inline-quotes = double +exclude = + .git + .tox + __pycache__ + build + dist + tests + *.pyc + *.egg-info + .cache + .eggs + env* +application-import-names = ansiblelater +format = ${cyan}%(path)s:%(row)d:%(col)d${reset}: ${red_bold}%(code)s${reset} %(text)s diff --git a/.github/settings.yml b/.github/settings.yml new file mode 100644 index 0000000..d4ed039 --- /dev/null +++ b/.github/settings.yml @@ -0,0 +1,57 @@ +--- +repository: + name: docker-autotag + description: Simple tool to create a list of docker tags from a given version string + topics: docker, ci, automation, versioning, python + + private: false + has_issues: true + has_projects: false + has_wiki: false + has_downloads: false + + default_branch: master + + allow_squash_merge: true + allow_merge_commit: true + allow_rebase_merge: true + +labels: + - name: bug + color: d73a4a + description: Something isn't working + - name: documentation + color: 0075ca + description: Improvements or additions to documentation + - name: duplicate + color: cfd3d7 + description: This issue or pull request already exists + - name: enhancement + color: a2eeef + description: New feature or request + - name: good first issue + color: 7057ff + description: Good for newcomers + - name: help wanted + color: 008672 + description: Extra attention is needed + - name: invalid + color: e4e669 + description: This doesn't seem right + - name: question + color: d876e3 + description: Further information is requested + - name: wontfix + color: ffffff + description: This will not be worked on + +branches: + - name: master + protection: + required_pull_request_reviews: null + required_status_checks: + strict: true + contexts: + - continuous-integration/drone/pr + enforce_admins: null + restrictions: null diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..620329a --- /dev/null +++ b/.gitignore @@ -0,0 +1,103 @@ +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ +env/ +env*/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject + +# Ignore ide addons +.server-script +.on-save.json +.vscode +.pytest_cache + +pip-wheel-metadata diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..de4f062 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1 @@ +* initial release diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c2d2cd6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM python:3.7-alpine + +LABEL maintainer="Robert Kaussow " \ + org.label-schema.name="docker-autotag" \ + org.label-schema.vcs-url="https://github.com/xoxys/docker-autotag" \ + org.label-schema.vendor="Robert Kaussow" \ + org.label-schema.schema-version="1.0" + +ENV PY_COLORS=1 + +ADD dist/docker_autotag-*.whl / + +RUN apk --update add --virtual .build-deps build-base libffi-dev libressl-dev && \ + apk --update add git && \ + pip install --upgrade --no-cache-dir pip && \ + pip install --no-cache-dir docker_autotag-*.whl && \ + apk del .build-deps && \ + rm -f docker_autotag-*.whl && \ + rm -rf /var/cache/apk/* && \ + rm -rf /root/.cache/ + +USER root +CMD [] +ENTRYPOINT ["/usr/local/bin/docker-autotag"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1475a9a --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2019 Robert Kaussow + +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/README.md b/README.md new file mode 100644 index 0000000..e8e535a --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# docker-autotag + +[![Build Status](https://img.shields.io/drone/build/xoxys/docker-autotag?logo=drone)](https://cloud.drone.io/xoxys/docker-autotag) +[![Docker Hub](https://img.shields.io/badge/docker-latest-blue.svg?logo=docker&logoColor=white)](https://hub.docker.com/r/xoxys/docker-autotag) +[![Python Version](https://img.shields.io/pypi/pyversions/docker-autotag.svg)](https://pypi.org/project/docker-autotag/) +[![PyPi Status](https://img.shields.io/pypi/status/docker-autotag.svg)](https://pypi.org/project/docker-autotag/) +[![PyPi Release](https://img.shields.io/pypi/v/docker-autotag.svg)](https://pypi.org/project/docker-autotag/) +[![License: MIT](https://img.shields.io/github/license/xoxys/docker-autotag)](LICENSE) + +Simple tool to create a list of docker tags from a given version string. + +## Environment variables + +```Shell +DOCKER_AUTOTAG_OUTPUT_FILE= +DOCKER_AUTOTAG_SUFFIX= +DOCKER_AUTOTAG_VERSION= +DOCKER_AUTOTAG_EXTRA_TAGS= +DOCKER_AUTOTAG_FORCE_LATEST=False +DOCKER_AUTOTAG_IGNORE_PRERELEASE=False +``` + +## License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. + +## Maintainers and Contributors + +[Robert Kaussow](https://github.com/xoxys) diff --git a/bin/docker-autotag b/bin/docker-autotag new file mode 100755 index 0000000..3d542e3 --- /dev/null +++ b/bin/docker-autotag @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 + +import sys + +import dockerautotag.__main__ + +sys.exit(dockerautotag.__main__.main()) diff --git a/dev-requirements.txt b/dev-requirements.txt new file mode 100644 index 0000000..1d053e7 --- /dev/null +++ b/dev-requirements.txt @@ -0,0 +1,19 @@ +pydocstyle<4.0.0 +flake8 +flake8-colors +flake8-blind-except +flake8-builtins +flake8-docstrings<=3.0.0 +flake8-isort +flake8-logging-format +flake8-polyfill +flake8-quotes +flake8-pep3101 +flake8-eradicate; python_version >= "3.6" +pep8-naming +wheel +pytest +pytest-mock +pytest-cov +bandit +yapf diff --git a/dockerautotag/Cli.py b/dockerautotag/Cli.py new file mode 100644 index 0000000..e2f11ce --- /dev/null +++ b/dockerautotag/Cli.py @@ -0,0 +1,124 @@ +"""Main program.""" + +import argparse +import copy +import os +from collections import defaultdict + +import semantic_version + +from dockerautotag import __version__ +from dockerautotag.Logging import SingleLog +from dockerautotag.Utils import normalize_path +from dockerautotag.Utils import to_bool +from dockerautotag.Utils import to_prerelease +from dockerautotag.Utils import trim_prefix + + +class Autotag: + """Handles tag operations.""" + + def __init__(self): + self.log = SingleLog() + self.logger = self.log.logger + self.args = self._cli_args() + self.config = self._config() + self.run() + + def _cli_args(self): + parser = argparse.ArgumentParser( + description=("Creates a list of docker tags from a given version string.") + ) + parser.add_argument( + "--version", action="version", version="%(prog)s {}".format(__version__) + ) + + return parser.parse_args() + + def _config(self): + config = defaultdict(dict) + + output_raw = os.environ.get("DOCKER_AUTOTAG_OUTPUT_FILE", None) + config["file"] = normalize_path(output_raw) + + config["suffix"] = os.environ.get("DOCKER_AUTOTAG_SUFFIX", None) + config["version"] = os.environ.get("DOCKER_AUTOTAG_VERSION", None) + config["extra"] = os.environ.get("DOCKER_AUTOTAG_EXTRA_TAGS", None) + config["force_latest"] = to_bool(os.environ.get("DOCKER_AUTOTAG_FORCE_LATEST", False)) + config["ignore_pre"] = to_bool(os.environ.get("DOCKER_AUTOTAG_IGNORE_PRERELEASE", False)) + + return config + + @staticmethod + def _tag_extra(tags, extra): + pass + + @staticmethod + def _tag_suffix(tags, suffix): + if not suffix: + return tags + + res = copy.deepcopy(tags) + for t in tags: + if t == "latest": + res.append(suffix) + else: + res.append("{}-{}".format(t, suffix)) + + return res + + @staticmethod + def _default_tags(ref, ignore_pre, force_latest): + default = ["latest"] + tags = [] + + if force_latest: + tags.append("latest") + + if not ref: + return default + + ref = trim_prefix(ref, "refs/tags/") + ref = trim_prefix(ref, "v") + + try: + version = semantic_version.Version(ref) + except ValueError: + try: + version = semantic_version.Version.coerce(ref) + except Exception: + return default + except Exception: + return default + + if version.prerelease: + tags.append( + "{}.{}.{}-{}".format( + version.major, version.minor, version.patch, to_prerelease(version.prerelease) + ) + ) + if not ignore_pre: + return tags + + tags.append("{}.{}".format(version.major, version.minor)) + tags.append("{}.{}.{}".format(version.major, version.minor, version.patch)) + + if version.major > 0: + tags.append("{}".format(version.major)) + + return tags + + def run(self): + config = self.config + + v = self._default_tags(config["version"], config["ignore_pre"], config["force_latest"]) + v = self._tag_suffix(v, config["suffix"]) + + if config["file"]: + try: + with open(config["file"], "w") as f: + f.write(",".join(v)) + except IOError as e: + self.logger.error("Unable to write file: {}".format(str(e))) + else: + print(",".join(v)) diff --git a/dockerautotag/Logging.py b/dockerautotag/Logging.py new file mode 100644 index 0000000..383531f --- /dev/null +++ b/dockerautotag/Logging.py @@ -0,0 +1,195 @@ +"""Global utility methods and classes.""" + +import logging +import os +import sys + +import colorama +from pythonjsonlogger import jsonlogger + +from dockerautotag.Utils import Singleton +from dockerautotag.Utils import to_bool + +CONSOLE_FORMAT = "{}[%(levelname)s]{} %(message)s" +JSON_FORMAT = "(asctime) (levelname) (message)" + + +def _should_do_markup(): + py_colors = os.environ.get("PY_COLORS", None) + if py_colors is not None: + return to_bool(py_colors) + + return sys.stdout.isatty() and os.environ.get("TERM") != "dumb" + + +colorama.init(autoreset=True, strip=not _should_do_markup()) + + +class LogFilter(object): + """A custom log filter which excludes log messages above the logged level.""" + + def __init__(self, level): + """ + Initialize a new custom log filter. + + :param level: Log level limit + :returns: None + + """ + self.__level = level + + def filter(self, logRecord): # noqa + # https://docs.python.org/3/library/logging.html#logrecord-attributes + return logRecord.levelno <= self.__level + + +class MultilineFormatter(logging.Formatter): + """Logging Formatter to reset color after newline characters.""" + + def format(self, record): # noqa + record.msg = record.msg.replace("\n", "\n{}... ".format(colorama.Style.RESET_ALL)) + return logging.Formatter.format(self, record) + + +class MultilineJsonFormatter(jsonlogger.JsonFormatter): + """Logging Formatter to remove newline characters.""" + + def format(self, record): # noqa + record.msg = record.msg.replace("\n", " ") + return jsonlogger.JsonFormatter.format(self, record) + + +class Log: + """Base logging object.""" + + def __init__(self, level=logging.WARN, name="ansibledoctor", json=False): + self.logger = logging.getLogger(name) + self.logger.setLevel(level) + self.logger.addHandler(self._get_error_handler(json=json)) + self.logger.addHandler(self._get_warn_handler(json=json)) + self.logger.addHandler(self._get_info_handler(json=json)) + self.logger.addHandler(self._get_critical_handler(json=json)) + self.logger.addHandler(self._get_debug_handler(json=json)) + self.logger.propagate = False + + def _get_error_handler(self, json=False): + handler = logging.StreamHandler(sys.stderr) + handler.setLevel(logging.ERROR) + handler.addFilter(LogFilter(logging.ERROR)) + handler.setFormatter( + MultilineFormatter( + self.error(CONSOLE_FORMAT.format(colorama.Fore.RED, colorama.Style.RESET_ALL)) + ) + ) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_warn_handler(self, json=False): + handler = logging.StreamHandler(sys.stdout) + handler.setLevel(logging.WARN) + handler.addFilter(LogFilter(logging.WARN)) + handler.setFormatter( + MultilineFormatter( + self.warn(CONSOLE_FORMAT.format(colorama.Fore.YELLOW, colorama.Style.RESET_ALL)) + ) + ) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_info_handler(self, json=False): + handler = logging.StreamHandler(sys.stdout) + handler.setLevel(logging.INFO) + handler.addFilter(LogFilter(logging.INFO)) + handler.setFormatter( + MultilineFormatter( + self.info(CONSOLE_FORMAT.format(colorama.Fore.CYAN, colorama.Style.RESET_ALL)) + ) + ) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_critical_handler(self, json=False): + handler = logging.StreamHandler(sys.stderr) + handler.setLevel(logging.CRITICAL) + handler.addFilter(LogFilter(logging.CRITICAL)) + handler.setFormatter( + MultilineFormatter( + self.critical(CONSOLE_FORMAT.format(colorama.Fore.RED, colorama.Style.RESET_ALL)) + ) + ) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_debug_handler(self, json=False): + handler = logging.StreamHandler(sys.stderr) + handler.setLevel(logging.DEBUG) + handler.addFilter(LogFilter(logging.DEBUG)) + handler.setFormatter( + MultilineFormatter( + self.critical(CONSOLE_FORMAT.format(colorama.Fore.BLUE, colorama.Style.RESET_ALL)) + ) + ) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def set_level(self, s): + self.logger.setLevel(s) + + def debug(self, msg): + """Format info messages and return string.""" + return msg + + def critical(self, msg): + """Format critical messages and return string.""" + return msg + + def error(self, msg): + """Format error messages and return string.""" + return msg + + def warn(self, msg): + """Format warn messages and return string.""" + return msg + + def info(self, msg): + """Format info messages and return string.""" + return msg + + def _color_text(self, color, msg): + """ + Colorize strings. + + :param color: colorama color settings + :param msg: string to colorize + :returns: string + + """ + return "{}{}{}".format(color, msg, colorama.Style.RESET_ALL) + + def sysexit(self, code=1): + sys.exit(code) + + def sysexit_with_message(self, msg, code=1): + self.logger.critical(str(msg)) + self.sysexit(code) + + +class SingleLog(Log, metaclass=Singleton): + """Singleton logger object.""" + + pass diff --git a/dockerautotag/Utils.py b/dockerautotag/Utils.py new file mode 100644 index 0000000..d9fd706 --- /dev/null +++ b/dockerautotag/Utils.py @@ -0,0 +1,35 @@ +"""Global utility methods and classes.""" + +import os +from distutils.util import strtobool + + +def normalize_path(path): + if path: + return os.path.abspath(os.path.expanduser(os.path.expandvars(path))) + + +def to_bool(string): + return bool(strtobool(str(string))) + + +def trim_prefix(text, prefix): + if text.startswith(prefix): + return text[len(prefix):] + return text + + +def to_prerelease(tup): + res = "".join(tup) + return res + + +class Singleton(type): + """Meta singleton class.""" + + _instances = {} + + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] diff --git a/dockerautotag/__init__.py b/dockerautotag/__init__.py new file mode 100644 index 0000000..e5d2a2f --- /dev/null +++ b/dockerautotag/__init__.py @@ -0,0 +1,9 @@ +"""Default package.""" + +__author__ = "Robert Kaussow" +__project__ = "docker-autotag" +__version__ = "0.1.0" +__license__ = "MIT" +__maintainer__ = "Robert Kaussow" +__email__ = "mail@geeklabor.de" +__url__ = "https://github.com/xoxys/docker-autotag" diff --git a/dockerautotag/__main__.py b/dockerautotag/__main__.py new file mode 100644 index 0000000..58abddc --- /dev/null +++ b/dockerautotag/__main__.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +"""Main program.""" + +from dockerautotag.Cli import Autotag + + +def main(): + Autotag() + + +if __name__ == "__main__": + main() diff --git a/manifest.tmpl b/manifest.tmpl new file mode 100644 index 0000000..8c9076e --- /dev/null +++ b/manifest.tmpl @@ -0,0 +1,24 @@ +image: xoxys/docker-autotag:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}latest{{/if}} +{{#if build.tags}} +tags: +{{#each build.tags}} + - {{this}} +{{/each}} +{{/if}} +manifests: + - image: xoxys/docker-autotag:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}amd64 + platform: + architecture: amd64 + os: linux + + - image: xoxys/docker-autotag:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}arm64 + platform: + architecture: arm64 + os: linux + variant: v8 + + - image: xoxys/docker-autotag:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}arm + platform: + architecture: arm + os: linux + variant: v7 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..3512169 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,30 @@ +[metadata] +description-file = README.md +license_file = LICENSE + +[bdist_wheel] +universal = 1 + +[isort] +default_section = THIRDPARTY +known_first_party = dockerautotag +sections = FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER +force_single_line = true +line_length = 99 +skip_glob = **/.env*,**/env/*,**/docs/* + +[yapf] +based_on_style = google +column_limit = 99 +dedent_closing_brackets = true +coalesce_brackets = true +split_before_logical_operator = true + +[tool:pytest] +filterwarnings = + ignore::FutureWarning + ignore:.*collections.*:DeprecationWarning + ignore:.*pep8.*:FutureWarning + +[coverage:run] +omit = **/test/* diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..68819b0 --- /dev/null +++ b/setup.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Setup script for the package.""" + +import io +import os +import re + +from setuptools import find_packages +from setuptools import setup + +PACKAGE_NAME = "dockerautotag" + + +def get_property(prop, project): + current_dir = os.path.dirname(os.path.realpath(__file__)) + result = re.search( + r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop), + open(os.path.join(current_dir, project, "__init__.py")).read()) + return result.group(1) + + +def get_readme(filename="README.md"): + this = os.path.abspath(os.path.dirname(__file__)) + with io.open(os.path.join(this, filename), encoding="utf-8") as f: + long_description = f.read() + return long_description + + +setup( + name=get_property("__project__", PACKAGE_NAME), + version=get_property("__version__", PACKAGE_NAME), + description="Creates a list of docker tags from a given version string.", + keywords="docker, versioning, automation, ci", + author=get_property("__author__", PACKAGE_NAME), + author_email=get_property("__email__", PACKAGE_NAME), + url=get_property("__url__", PACKAGE_NAME), + license=get_property("__license__", PACKAGE_NAME), + long_description=get_readme(), + long_description_content_type="text/markdown", + packages=find_packages(exclude=["*.test", "test", "test.*"]), + include_package_data=True, + zip_safe=False, + python_requires=">=3.5,<4", + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "License :: OSI Approved :: MIT License", + "Intended Audience :: Developers", + "Intended Audience :: Information Technology", + "Intended Audience :: System Administrators", + "Natural Language :: English", + "Operating System :: POSIX", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Topic :: Utilities", + "Topic :: Software Development", + ], + install_requires=[ + "semantic-version", + "colorama", + "python-json-logger", + ], + entry_points={ + "console_scripts": [ + "docker-autotag = dockerautotag.__main__:main" + ] + }, +)