#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Publish the built Pages site to this repository's gh-pages branch. publish-pages.py SITE_DIR Served at https://blueflare.gitea.bluefla.re/alkane-toolkit/ by the Pages server, which serves the gh-pages branch of public repositories. Each publish is one orphan commit (force-pushed), so the branch never accumulates history. Only main may publish, and a run for a superseded main commit skips. """ import json import os from pathlib import Path import shutil import subprocess import sys import tempfile from urllib.request import Request, urlopen BRANCH = "gh-pages" MAX_BYTES = 20 * 1024 * 1024 def current_main_sha(api: str, repo: str, token: str) -> str: request = Request(f"{api}/repos/{repo}/branches/main", headers={"Authorization": f"token {token}"}) with urlopen(request, timeout=20) as response: return json.load(response)["commit"]["id"] def git(*args: str, cwd: Path, env: dict | None = None) -> None: subprocess.run(("git", *args), cwd=cwd, env=env, check=True) def main() -> None: if len(sys.argv) != 2: sys.exit(__doc__) site = Path(sys.argv[1]) if not (site / "index.html").is_file(): sys.exit(f"{site} has no index.html") size = sum(p.stat().st_size for p in site.rglob("*") if p.is_file()) if size > MAX_BYTES: sys.exit(f"site is {size} bytes, over the {MAX_BYTES} byte limit") for path in site.rglob("*"): if path.is_file() and path.suffix not in {".html", ".css", ".svg", ".png", ".json"}: sys.exit(f"unexpected file type on the site: {path}") api = os.environ["GITHUB_API_URL"].rstrip("/") repo = os.environ["GITHUB_REPOSITORY"] sha = os.environ["GITHUB_SHA"] token = os.environ["GITEA_TOKEN"] if os.environ.get("GITHUB_REF") != "refs/heads/main": sys.exit("Pages publication requires main") if current_main_sha(api, repo, token) != sha: print("Skipping Pages for a superseded main commit") return server = api.removesuffix("/api/v1") with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory: work = Path(directory) shutil.copytree(site, work, dirs_exist_ok=True) env = dict(os.environ, GIT_TERMINAL_PROMPT="0") git("init", "-q", "-b", BRANCH, cwd=work) git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re", "add", "-A", cwd=work) git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re", "commit", "-q", "-m", f"Publish site for {sha[:10]} [skip ci]", cwd=work) # The token is read from the environment by the credential helper at # push time; it never appears on a command line or in the remote URL. helper = '!f() { echo username=alkane-ci; echo "password=$GITEA_TOKEN"; }; f' git("-c", f"credential.helper={helper}", "push", "-q", "--force", f"{server}/{repo}.git", f"HEAD:refs/heads/{BRANCH}", cwd=work, env=env) print(f"Published Pages for {sha[:10]} to {BRANCH}") if __name__ == "__main__": main()