#!/usr/bin/env python3 # Eryn Wells import argparse import datetime import subprocess from typing import List from .scripting import Command DATE_FORMAT = "%Y-%m-%d" class DeploymentCommand(Command): @property def help(self) -> str: return 'Deployment tools' def add_arguments(self, parser: argparse.ArgumentParser): commands = parser.add_subparsers(title="Deployment", required=True) deployment_command = commands.add_parser( 'next-tag', help='Calculate the next deployment tag for a given date, examining all other tags for that day' ) deployment_command.add_argument( '--date', '-d', type=self.__class__.parse_date_argument, default=datetime.date.today(), help="date to calculate a new deployment tag for (default: today)" ) deployment_command.set_defaults(handler=self.handle_next_deployment_tag_command) @staticmethod def parse_date_argument(date_string: str) -> datetime.date: return datetime.datetime.strptime(date_string, DATE_FORMAT).date() def handle_next_deployment_tag_command(self, args: argparse.Namespace): next_deployment_tag = deployment_tag_for_date(args.date) print(next_deployment_tag) def deployment_tag_for_date(date: datetime.date) -> str: formatted_date = date.strftime(DATE_FORMAT) def deploy_tag_filter(tag): return tag.startswith("deploy-") and formatted_date in tag filtered_tags = sorted(filter(deploy_tag_filter, git_tags())) if len(filtered_tags) == 0: return f"deploy-{formatted_date}-01" else: last_tag = filtered_tags[-1] components = last_tag.split("-") if len(components) == 5: # A previous numbered deployment. Add one to the last deployment # number. deployment_number = int(components[-1]) + 1 return f"deploy-{formatted_date}-{deployment_number:02}" else: # An old style deployment tag that doesn't have a number. There # should only ever be one of these. assert len(filtered_tags) == 1 return f"deploy-{formatted_date}-02" def git_tags() -> List[str]: return subprocess.check_output( "git tag -l", shell=True, encoding="utf-8" ).splitlines()