|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +"""Create version information JSON file |
| 4 | +
|
| 5 | +This file is created at build time and copied into the backend container so |
| 6 | +that we can include information that's not available at runtime. |
| 7 | +""" |
| 8 | +from datetime import datetime, timezone |
| 9 | +import json |
| 10 | +from pathlib import Path |
| 11 | +import sys |
| 12 | +import subprocess |
| 13 | +from typing import Optional |
| 14 | + |
| 15 | + |
| 16 | +def do(cmd: list[str]) -> list[str]: |
| 17 | + result = subprocess.run(cmd, text=True, capture_output=True) |
| 18 | + if result.returncode != 0: |
| 19 | + raise Exception(f"Command {' '.join(cmd)!r} failed: {result.stderr}") |
| 20 | + return [line.strip() for line in result.stdout.split("\n") if line.strip()] |
| 21 | + |
| 22 | + |
| 23 | +def getone(cmd: list[str], if_none: Optional[str] = None) -> str: |
| 24 | + res = do(cmd) |
| 25 | + if if_none is not None and len(res) == 0: |
| 26 | + return if_none |
| 27 | + if len(res) != 1: |
| 28 | + raise Exception(f"Command {' '.join(cmd)!r} returned {len(res)} lines: {res}") |
| 29 | + return res[0] |
| 30 | + |
| 31 | + |
| 32 | +def main(): |
| 33 | + top = Path(getone(["git", "rev-parse", "--show-toplevel"])) |
| 34 | + backend = top / "backend" |
| 35 | + version = (backend / "VERSION").read_text().strip() |
| 36 | + sha = getone(["git", "rev-parse", "--short", "HEAD"]) |
| 37 | + branch = getone(["git", "branch", "--show-current"], if_none="HEAD") |
| 38 | + display = f"v{version}-{sha} ({branch})" |
| 39 | + print(f"VERSION: {display}") |
| 40 | + log = do(["git", "log", "-n10", "--format=%h###%aN###%aE###%aI###%s"]) |
| 41 | + fields = ("sha", "author", "email", "date", "title") |
| 42 | + vj = { |
| 43 | + "version": version, |
| 44 | + "sha": sha, |
| 45 | + "branch": branch, |
| 46 | + "display_version": display, |
| 47 | + "date": datetime.now(tz=timezone.utc).isoformat(), |
| 48 | + "changes": [{f: v for f, v in zip(fields, l.split("###"))} for l in log], |
| 49 | + } |
| 50 | + with (backend / "version.json").open("w") as verfile: |
| 51 | + json.dump(vj, fp=verfile) |
| 52 | + return 0 |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + try: |
| 57 | + sys.exit(main()) |
| 58 | + except Exception as exc: |
| 59 | + print(f"Failed with {str(exc)!r}", file=sys.stderr) |
| 60 | + sys.exit(1) |
0 commit comments