diff options
author | 2022-05-30 23:31:12 -0700 | |
---|---|---|
committer | 2022-05-31 00:01:33 -0700 | |
commit | 67edafa0062582e4eec47c59d05a7b4b2429f435 (patch) | |
tree | 94297eba9752bdb517e745cc19f1398ac0a93e77 /scripts | |
parent | Add __all__ to all modules (diff) |
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.
Diffstat (limited to 'scripts')
-rw-r--r-- | scripts/version.py | 34 |
1 files changed, 34 insertions, 0 deletions
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") |