docker-autotag/dockerautotag/cli.py

133 lines
3.7 KiB
Python
Raw Normal View History

2020-05-03 21:42:52 +00:00
"""Main program."""
import argparse
import copy
import os
import sys
2020-05-03 21:42:52 +00:00
from collections import defaultdict
import semantic_version
from dockerautotag import __version__
2021-01-03 13:49:48 +00:00
from dockerautotag.logging import SingleLog
from dockerautotag.utils import normalize_path, to_bool, to_prerelease, trim_prefix
2020-05-03 21:42:52 +00:00
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=f"%(prog)s {__version__}")
2020-05-03 21:42:52 +00:00
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["suffix_strict"] = to_bool(os.environ.get("DOCKER_AUTOTAG_SUFFIX_STRICT", False))
2020-05-03 21:42:52 +00:00
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):
2020-05-04 17:50:13 +00:00
e = []
if extra:
e = [x.strip() for x in extra.split(",")]
2020-05-04 17:50:13 +00:00
return tags + e
2020-05-03 21:42:52 +00:00
@staticmethod
def _tag_suffix(tags, suffix, suffix_strict):
2020-05-03 21:42:52 +00:00
if not suffix:
return tags
res = []
if not suffix_strict:
res = copy.deepcopy(tags)
2020-05-03 21:42:52 +00:00
for t in tags:
if t == "latest":
res.append(suffix)
else:
res.append(f"{t}-{suffix}")
2020-05-03 21:42:52 +00:00
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: # noqa: BLE001
2020-05-03 21:42:52 +00:00
return default
except Exception: # noqa: BLE001
2020-05-03 21:42:52 +00:00
return default
if version.prerelease:
tags.append(
f"{version.major}.{version.minor}.{version.patch}-{to_prerelease(version.prerelease)}"
2020-05-03 21:42:52 +00:00
)
if not ignore_pre:
return tags
tags.append(f"{version.major}.{version.minor}")
tags.append(f"{version.major}.{version.minor}.{version.patch}")
2020-05-03 21:42:52 +00:00
if version.major > 0:
tags.append(f"{version.major}")
2020-05-03 21:42:52 +00:00
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"], config["suffix_strict"])
v = self._tag_extra(v, config["extra"])
2020-05-03 21:42:52 +00:00
try:
if config["file"]:
2020-05-03 21:42:52 +00:00
with open(config["file"], "w") as f:
f.write(",".join(v))
else:
sys.stdout.write(",".join(v))
sys.stdout.write("\n")
except OSError as e:
self.logger.error(f"Unable to write file: {e!s}")
2021-01-03 13:49:48 +00:00
def main():
Autotag()