|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Create and verify the tagged release source that declares its own version. |
| 3 | +
|
| 4 | +Each release tag points to a commit whose only parent is the main commit being |
| 5 | +released and whose only change appends the release version and Android |
| 6 | +versionCode to gradle.properties. The commit is deterministic: rebuilding it |
| 7 | +from the same parent, version and code yields the same SHA, so the build and |
| 8 | +publish jobs agree without sharing Git objects. It is pushed only as a tag, |
| 9 | +never to a branch, so main's first-parent numbering is unaffected. |
| 10 | +""" |
| 11 | + |
| 12 | +import argparse |
| 13 | +import os |
| 14 | +from pathlib import Path |
| 15 | +import re |
| 16 | +import subprocess |
| 17 | +import sys |
| 18 | +import tempfile |
| 19 | + |
| 20 | + |
| 21 | +PROPERTIES = "gradle.properties" |
| 22 | +VERSION_KEY = "projectmReleaseVersion" |
| 23 | +CODE_KEY = "projectmReleaseVersionCode" |
| 24 | +# Fixed identity and parent-derived date keep the commit SHA reproducible. |
| 25 | +AUTHOR = ("ProjectM release", "41898282+github-actions[bot]@users.noreply.github.com") |
| 26 | +VERSION_PATTERN = r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)" |
| 27 | +CODE_LIMIT = 2100000000 |
| 28 | +SHA_PATTERN = r"[0-9a-f]{40}" |
| 29 | +KEY_LINE = re.compile(rf"^[ \t]*({VERSION_KEY}|{CODE_KEY})[ \t]*[=:\s]", re.MULTILINE) |
| 30 | + |
| 31 | + |
| 32 | +def validate(version: str, code: int) -> None: |
| 33 | + if not re.fullmatch(VERSION_PATTERN, version): |
| 34 | + raise ValueError(f"Invalid release version: {version!r}; expected X.Y.Z") |
| 35 | + if type(code) is not int or not 1 <= code <= CODE_LIMIT: |
| 36 | + raise ValueError(f"Android versionCode must be an integer from 1 to {CODE_LIMIT}") |
| 37 | + |
| 38 | + |
| 39 | +def release_properties(original: str, version: str, code: int) -> str: |
| 40 | + """Append the release identity; main itself must never declare one.""" |
| 41 | + validate(version, code) |
| 42 | + if KEY_LINE.search(original): |
| 43 | + raise ValueError(f"{PROPERTIES} on main must not declare {VERSION_KEY} or {CODE_KEY}") |
| 44 | + base = original if not original or original.endswith("\n") else original + "\n" |
| 45 | + return (base + f"\n# Release identity of tag v{version}; written by the release workflow.\n" |
| 46 | + f"{VERSION_KEY}={version}\n{CODE_KEY}={code}\n") |
| 47 | + |
| 48 | + |
| 49 | +def declared_release(text: str) -> tuple[str, int] | None: |
| 50 | + """Return the (version, code) a tagged gradle.properties declares, if any.""" |
| 51 | + values = {} |
| 52 | + for key, value in re.findall(rf"^({VERSION_KEY}|{CODE_KEY})=(.*)$", text, re.MULTILINE): |
| 53 | + if key in values: |
| 54 | + raise ValueError(f"{PROPERTIES} declares {key} more than once") |
| 55 | + values[key] = value |
| 56 | + if not values: |
| 57 | + return None |
| 58 | + version, code = values.get(VERSION_KEY, ""), values.get(CODE_KEY, "") |
| 59 | + if not re.fullmatch(r"[1-9][0-9]{0,9}", code): |
| 60 | + raise ValueError(f"{PROPERTIES} declares an invalid {CODE_KEY}") |
| 61 | + validate(version, int(code)) |
| 62 | + return version, int(code) |
| 63 | + |
| 64 | + |
| 65 | +def message(version: str, code: int, source: str) -> str: |
| 66 | + return f"Release v{version}\n\nVersion-Code: {code}\nSource-Commit: {source}\n" |
| 67 | + |
| 68 | + |
| 69 | +def git(repo: Path, *args: str, stdin: str | None = None, env: dict | None = None, raw: bool = False) -> str: |
| 70 | + result = subprocess.run(["git", "-C", str(repo), *args], input=stdin, capture_output=True, |
| 71 | + text=True, env={**os.environ, **(env or {})}) |
| 72 | + if result.returncode: |
| 73 | + raise ValueError(f"Git command failed: {result.stderr.strip()}") |
| 74 | + return result.stdout if raw else result.stdout.strip() |
| 75 | + |
| 76 | + |
| 77 | +def resolve(repo: Path, revision: str) -> str: |
| 78 | + return git(repo, "rev-parse", "--verify", "--end-of-options", revision + "^{commit}") |
| 79 | + |
| 80 | + |
| 81 | +def create(repo: Path, source: str, version: str, code: int) -> str: |
| 82 | + """Write the release commit object (no ref, no working-tree change) and return its SHA.""" |
| 83 | + source = resolve(repo, source) |
| 84 | + entry = git(repo, "ls-tree", source, "--", PROPERTIES).split() |
| 85 | + if len(entry) != 4 or entry[:2] != ["100644", "blob"]: |
| 86 | + raise ValueError(f"{PROPERTIES} must be a regular file in the released source") |
| 87 | + text = release_properties(git(repo, "cat-file", "blob", entry[2], raw=True), version, code) |
| 88 | + blob = git(repo, "hash-object", "-w", "--stdin", stdin=text) |
| 89 | + with tempfile.TemporaryDirectory() as directory: |
| 90 | + index = {"GIT_INDEX_FILE": str(Path(directory) / "index")} |
| 91 | + git(repo, "read-tree", source, env=index) |
| 92 | + git(repo, "update-index", "--add", "--cacheinfo", f"100644,{blob},{PROPERTIES}", env=index) |
| 93 | + tree = git(repo, "write-tree", env=index) |
| 94 | + date = git(repo, "show", "-s", "--format=%ct", source) + " +0000" |
| 95 | + identity = {"GIT_AUTHOR_NAME": AUTHOR[0], "GIT_AUTHOR_EMAIL": AUTHOR[1], "GIT_AUTHOR_DATE": date, |
| 96 | + "GIT_COMMITTER_NAME": AUTHOR[0], "GIT_COMMITTER_EMAIL": AUTHOR[1], "GIT_COMMITTER_DATE": date} |
| 97 | + return git(repo, "-c", "i18n.commitEncoding=UTF-8", "commit-tree", "--no-gpg-sign", tree, |
| 98 | + "-p", source, "-F", "-", stdin=message(version, code, source), env=identity) |
| 99 | + |
| 100 | + |
| 101 | +def inspect(repo: Path, commit: str) -> dict | None: |
| 102 | + """Describe a release commit, None for an ordinary commit; reject malformed release commits.""" |
| 103 | + commit = resolve(repo, commit) |
| 104 | + subject, _, body = git(repo, "show", "-s", "--format=%B", commit).partition("\n") |
| 105 | + match = re.fullmatch(rf"Release v({VERSION_PATTERN})", subject) |
| 106 | + if not match: |
| 107 | + return None |
| 108 | + parents = git(repo, "show", "-s", "--format=%P", commit).split() |
| 109 | + trailers = dict(re.findall(r"^(Version-Code|Source-Commit): (\S+)$", body, re.MULTILINE)) |
| 110 | + version = match.group(1) |
| 111 | + if (len(parents) != 1 or trailers.get("Source-Commit") != parents[0] or |
| 112 | + not re.fullmatch(r"[1-9][0-9]{0,9}", trailers.get("Version-Code", ""))): |
| 113 | + raise ValueError(f"Release commit {commit} does not name its single source parent and code") |
| 114 | + code = int(trailers["Version-Code"]) |
| 115 | + changed = git(repo, "diff-tree", "--no-commit-id", "--name-only", "-r", parents[0], commit).splitlines() |
| 116 | + expected = release_properties(git(repo, "show", f"{parents[0]}:{PROPERTIES}", raw=True), version, code) |
| 117 | + if changed != [PROPERTIES] or git(repo, "show", f"{commit}:{PROPERTIES}", raw=True) != expected: |
| 118 | + raise ValueError(f"Release commit {commit} changes more than its declared release identity") |
| 119 | + return {"commit": commit, "source": parents[0], "version": version, "version_code": code} |
| 120 | + |
| 121 | + |
| 122 | +def source_of(repo: Path, commit: str) -> str: |
| 123 | + """Map a tag target to the main commit it releases (older tags point at it directly).""" |
| 124 | + details = inspect(repo, commit) |
| 125 | + return details["source"] if details else resolve(repo, commit) |
| 126 | + |
| 127 | + |
| 128 | +def remote_tag(repo: Path, remote: str, tag: str) -> str | None: |
| 129 | + """Return the commit an existing remote tag points to (peeling annotated tags).""" |
| 130 | + refs = {} |
| 131 | + for line in git(repo, "ls-remote", "--tags", remote).splitlines(): |
| 132 | + sha, _, name = line.partition("\t") |
| 133 | + refs[name] = sha |
| 134 | + return refs.get(f"refs/tags/{tag}^{{}}") or refs.get(f"refs/tags/{tag}") |
| 135 | + |
| 136 | + |
| 137 | +def publish_tag(repo: Path, remote: str, source: str, version: str, code: int, expected: str) -> str: |
| 138 | + """Push the build's release commit as v<version>; an identical existing tag is reused.""" |
| 139 | + commit = create(repo, source, version, code) |
| 140 | + if commit != expected: |
| 141 | + raise ValueError(f"Rebuilt release commit {commit} differs from the built source {expected}") |
| 142 | + tag = "v" + version |
| 143 | + existing = remote_tag(repo, remote, tag) |
| 144 | + if existing == commit: |
| 145 | + return "existing" |
| 146 | + if existing: |
| 147 | + raise ValueError(f"Tag {tag} already belongs to {existing}; refusing to move a release tag") |
| 148 | + git(repo, "push", "--quiet", remote, f"{commit}:refs/tags/{tag}") |
| 149 | + return "created" |
| 150 | + |
| 151 | + |
| 152 | +def main() -> int: |
| 153 | + parser = argparse.ArgumentParser(description=__doc__) |
| 154 | + commands = parser.add_subparsers(dest="command", required=True) |
| 155 | + for name in ("create", "tag"): |
| 156 | + command = commands.add_parser(name) |
| 157 | + command.add_argument("--repo", type=Path, default=Path(".")) |
| 158 | + command.add_argument("--source", required=True) |
| 159 | + command.add_argument("--version", required=True) |
| 160 | + command.add_argument("--version-code", type=int, required=True) |
| 161 | + commands.choices["create"].add_argument("--checkout", action="store_true", |
| 162 | + help="Detach the working tree onto the release commit") |
| 163 | + commands.choices["create"].add_argument("--output", type=Path, help="Append GitHub Actions outputs") |
| 164 | + commands.choices["tag"].add_argument("--expected", required=True) |
| 165 | + commands.choices["tag"].add_argument("--remote", default="origin") |
| 166 | + args = parser.parse_args() |
| 167 | + try: |
| 168 | + if args.command == "create": |
| 169 | + source = resolve(args.repo, args.source) |
| 170 | + commit = create(args.repo, source, args.version, args.version_code) |
| 171 | + if args.checkout: |
| 172 | + git(args.repo, "checkout", "--quiet", "--detach", commit) |
| 173 | + if args.output: |
| 174 | + with args.output.open("a", encoding="utf-8") as stream: |
| 175 | + stream.write(f"release_sha={commit}\nsource_sha={source}\n") |
| 176 | + print(commit) |
| 177 | + else: |
| 178 | + if not re.fullmatch(SHA_PATTERN, args.expected): |
| 179 | + raise ValueError("--expected must be a full commit SHA") |
| 180 | + state = publish_tag(args.repo, args.remote, args.source, args.version, args.version_code, args.expected) |
| 181 | + print(f"v{args.version} {state} at {args.expected}") |
| 182 | + except (ValueError, OSError) as error: |
| 183 | + print(f"release_commit: {error}", file=sys.stderr) |
| 184 | + return 1 |
| 185 | + return 0 |
| 186 | + |
| 187 | + |
| 188 | +if __name__ == "__main__": |
| 189 | + sys.exit(main()) |
0 commit comments