From 67edafa0062582e4eec47c59d05a7b4b2429f435 Mon Sep 17 00:00:00 2001 From: MarkKoz <1515135+MarkKoz@users.noreply.github.com> Date: Mon, 30 May 2022 23:31:12 -0700 Subject: Automatically determine the package version Use the HEAD commit's date as the package's version. Append the number of commits made on the same date as HEAD to ensure multiple releases on the same date still have unique versions. --- scripts/version.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 scripts/version.py (limited to 'scripts/version.py') diff --git a/scripts/version.py b/scripts/version.py new file mode 100644 index 0000000..9076b93 --- /dev/null +++ b/scripts/version.py @@ -0,0 +1,34 @@ +import datetime +import subprocess + +__all__ = ("get_version",) + + +def get_version() -> str: + """ + Return a version based on the HEAD commit's date. + + The format is 'year.month.day.commits' and is compliant with PEP 440. 'commits' is the amount of + commits made on the same date as HEAD, excluding HEAD. This ensures versions are unique if + multiple release occur on the same date. + """ + args = ["git", "show", "-s", "--format=%ct", "HEAD"] + stdout = subprocess.check_output(args, text=True) + timestamp = float(stdout.strip()) + date = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc) + + commits = count_commits_on_date(date) - 1 # Exclude HEAD. + + # Don't use strftime because it includes leading zeros, which are against PEP 440. + return f"{date.year}.{date.month}.{date.day}.{commits}" + + +def count_commits_on_date(dt: datetime.datetime) -> int: + """Return the amount of commits made on the given UTC aware datetime.""" + dt = dt.combine(dt - datetime.timedelta(days=1), dt.max.time(), dt.tzinfo) + + # git log uses the committer date for this, not the author date. + args = ["git", "log", "--oneline", "--after", str(dt.timestamp())] + stdout = subprocess.check_output(args, text=True) + + return stdout.strip().count("\n") -- cgit v1.2.3