From fc2eabd71d3934846052f5abbd4e27ea0cc297df Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:48:07 +0800 Subject: [PATCH 1/5] feat: publish a package template from its producers' releases scripts/publish-template.py reads the template composition that a declaration repository's MAINTENANCE.md declares, clones each producer's highest vMAJOR.MINOR.PATCH release, runs its generators into empty directories and writes the declared template paths. When files change, it commits them signed on one branch, opens one pull request listing each release, and requests auto-merge where the template allows it. The unit suite runs it against local producer, template and declaration repositories. No workflow calls it yet; a maintainer runs it after each producer release until an App credential can open pull requests. --- README.md | 40 ++++- scripts/publish-template.py | 318 +++++++++++++++++++++++++++++++++ tests/test_publish_template.py | 296 ++++++++++++++++++++++++++++++ 3 files changed, 651 insertions(+), 3 deletions(-) create mode 100755 scripts/publish-template.py create mode 100644 tests/test_publish_template.py diff --git a/README.md b/README.md index 73fd4bc..5aa7c47 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Shared GitHub workflows Reusable validation, source policy, release publication and organization checks -for Swift packages. Required member checks are exactly **`policy / policy`** and +for Swift packages, and publication of a package template. Required member checks are exactly **`policy / policy`** and **`validate / result`**. ## Job catalog @@ -175,6 +175,40 @@ read access to the selected repositories. The caller's ordinary `GITHUB_TOKEN` is sufficient for public observations, but cannot read all administrative settings across an organization. The optional secret is used only by the check. +## Package template publication + +`scripts/publish-template.py` publishes a template repository's generated files +from their producers' releases. The declaration repository's `MAINTENANCE.md` +declares them in one `template-composition` JSON block: `schema` 1, the +`template` repository as `owner/name`, and `generators`, each with a producer +`repository`, a `command` and a `files` map from template path to generated path. + +```sh +python3 scripts/publish-template.py --declaration --template +``` + +For each producer the script clones the highest `vMAJOR.MINOR.PATCH` tag, ignoring +pre-releases; every generator from one repository runs from that one release. +Each command runs from the release checkout's root, with `{template}`, `{output}` +and `{declaration}` replaced by the template checkout, an empty output directory +and the declaration checkout. The generated files must be exactly the declared +`files` values. The script writes only declared template paths, and writes +nothing unless every generator succeeds. + +Both checkouts must be clean, and the template's origin must be the declared +template. Unless `--write-only` is given, both must also be at their origin's +default branch head. When files change, the script commits them with a signature +on `chore/publish-`, pushes that branch and opens one pull request that +lists each producer's release, commit and changed files. When the template +allows auto-merge, it requests a squash merge of the pushed head. `--write-only` +writes the files without a commit or pull request. Runs need `git`, `gh` +authenticated to push to the template and open pull requests, signing +configured in the template checkout, and each generator's own tools. + +No workflow calls the script: opening a pull request in another repository +needs an App credential, so a maintainer runs it with their own credentials +after each producer release. + ## Pins and implementation revision Pin reusable workflows by full commit SHA; add a version comment at the family @@ -231,8 +265,8 @@ python3 scripts/test-fixtures.py demo --toolchain .build/presentation-toolchain macOS runs require Xcode/Swift; Linux fixture runs require Docker. The unit suite validates every package fixture against the schema, exercises compiler -matrices, version/tag trust, policy, organization API responses and aggregate -failure behavior. The command harness requires passing fixtures to succeed and +matrices, version/tag trust, policy, organization API responses, aggregate +failure behavior and template publication against local repositories. The command harness requires passing fixtures to succeed and negative fixtures to fail for their intended reason. Builds and logs live under ignored `.build/`. The macOS fixtures include documented library and executable targets with diff --git a/scripts/publish-template.py b/scripts/publish-template.py new file mode 100755 index 0000000..f7e58ef --- /dev/null +++ b/scripts/publish-template.py @@ -0,0 +1,318 @@ +#!/usr/bin/env python3 +"""Publish a template repository's generated files from its producers' latest releases.""" + +import argparse +import hashlib +import json +from pathlib import Path +import re +import shlex +import subprocess +import sys +import tempfile + + +BLOCK = re.compile(r"\s*```json\n(.*?)\n```", re.S) +REPOSITORY = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") +RELEASE = re.compile(r"v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)") +PLACEHOLDER = re.compile(r"\{([a-z]+)\}") +PLACEHOLDERS = frozenset({"template", "output", "declaration"}) + + +class PublishError(Exception): + pass + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise PublishError(f"template composition: duplicate key {key!r}") + result[key] = value + return result + + +def relative_path(value, label): + if not isinstance(value, str) or not value: + raise PublishError(f"{label}: expected a relative path") + path = Path(value) + if path.is_absolute() or ".." in path.parts or ".git" in path.parts or path.as_posix() != value: + raise PublishError(f"{label}: {value!r} must be a normalized path inside the repository") + return path + + +def validate_composition(value): + if not isinstance(value, dict) or set(value) != {"schema", "template", "generators"} or value["schema"] != 1: + raise PublishError("template composition: expected schema 1 with template and generators") + if not isinstance(value["template"], str) or not REPOSITORY.fullmatch(value["template"]): + raise PublishError("template composition: template must be owner/name") + generators = value["generators"] + if not isinstance(generators, list) or not generators: + raise PublishError("template composition: generators must be a nonempty list") + targets = set() + for index, generator in enumerate(generators): + label = f"generators[{index}]" + if not isinstance(generator, dict) or set(generator) != {"repository", "command", "files"}: + raise PublishError(f"{label}: expected repository, command and files") + if not isinstance(generator["repository"], str) or not REPOSITORY.fullmatch(generator["repository"]): + raise PublishError(f"{label}.repository: expected owner/name") + command = generator["command"] + if not isinstance(command, list) or not command or not all(isinstance(arg, str) and arg for arg in command): + raise PublishError(f"{label}.command: expected a nonempty list of arguments") + unknown = {name for arg in command for name in PLACEHOLDER.findall(arg)} - PLACEHOLDERS + if unknown: + raise PublishError(f"{label}.command: unknown placeholders {sorted(unknown)}") + files = generator["files"] + if not isinstance(files, dict) or not files: + raise PublishError(f"{label}.files: expected a nonempty map of template path to generated path") + for target, produced in files.items(): + relative_path(target, f"{label}.files") + relative_path(produced, f"{label}.files[{target!r}]") + if target in targets: + raise PublishError(f"{label}.files: {target!r} is declared by more than one generator") + targets.add(target) + + +def load_composition(root): + try: + text = (root / "MAINTENANCE.md").read_text(encoding="utf-8") + except OSError as error: + raise PublishError(f"{root}: cannot read MAINTENANCE.md: {error}") from error + blocks = BLOCK.findall(text) + if len(blocks) != 1: + raise PublishError("MAINTENANCE.md must contain one template-composition JSON block") + try: + value = json.loads(blocks[0], object_pairs_hook=unique_object) + except ValueError as error: + raise PublishError(f"template composition: {error}") from error + validate_composition(value) + return value + + +def run(arguments, *, cwd=None): + result = subprocess.run(arguments, cwd=cwd, capture_output=True, text=True, stdin=subprocess.DEVNULL) + if result.returncode: + raise PublishError(f"{shlex.join(map(str, arguments))} exited {result.returncode}: {result.stderr.strip()}") + return result.stdout + + +def git(*arguments, cwd=None): + return run(["git", *arguments], cwd=cwd) + + +def source_url(repository): + return f"https://github.com/{repository}.git" + + +def latest_release(url): + """Return the highest vMAJOR.MINOR.PATCH tag and the commit it names.""" + commits = {} + for line in git("ls-remote", "--tags", url, "refs/tags/v*").splitlines(): + commit, _, ref = line.partition("\t") + name = ref.removeprefix("refs/tags/") + peeled = name.endswith("^{}") + name = name.removesuffix("^{}") + # An annotated tag lists its tag object first and then the peeled commit. + if RELEASE.fullmatch(name) and (peeled or name not in commits): + commits[name] = commit + if not commits: + raise PublishError(f"{url}: no vMAJOR.MINOR.PATCH release tag") + tag = max(commits, key=lambda name: tuple(map(int, RELEASE.fullmatch(name).groups()))) + return tag, commits[tag] + + +def fetch_release(url, tag, commit, destination): + git("-c", "advice.detachedHead=false", "clone", "--quiet", "--depth", "1", "--branch", tag, url, str(destination)) + head = git("rev-parse", "HEAD", cwd=destination).strip() + if head != commit: + raise PublishError(f"{url} {tag}: checked out {head}, expected {commit}") + + +def generate(generator, source, values, output): + arguments = [ + PLACEHOLDER.sub(lambda match: str(values[match.group(1)]), argument) + for argument in generator["command"] + ] + run(arguments, cwd=source) + produced = { + path.relative_to(output).as_posix() + for path in output.rglob("*") if path.is_file() or path.is_symlink() + } + expected = set(generator["files"].values()) + if produced != expected: + missing = ", ".join(sorted(expected - produced)) or "none" + undeclared = ", ".join(sorted(produced - expected)) or "none" + raise PublishError( + f"{generator['repository']}: generated files differ from the declaration " + f"(missing: {missing}; undeclared: {undeclared})" + ) + for produced_path in expected: + if (output / produced_path).is_symlink(): + raise PublishError(f"{generator['repository']}: {produced_path} is a symbolic link") + + +def check_destinations(template, targets): + root = template.resolve() + for target in targets: + destination = template / target + for relative in (Path(target), *Path(target).parents): + if (template / relative).is_symlink(): + raise PublishError(f"{destination}: path crosses a symbolic link") + if not destination.resolve().is_relative_to(root): + raise PublishError(f"{destination}: must stay inside {template}") + if destination.exists() and not destination.is_file(): + raise PublishError(f"{destination}: must be a regular file") + + +def apply(template, files, output): + changed = [] + for target, produced in sorted(files.items()): + destination = template / target + content = (output / produced).read_bytes() + if destination.is_file() and destination.read_bytes() == content: + continue + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(content) + changed.append(target) + return changed + + +def require_clean(checkout): + if git("status", "--porcelain", "--untracked-files=all", cwd=checkout): + raise PublishError(f"{checkout}: working tree has uncommitted changes") + + +def remote_default(checkout): + branch = commit = None + for line in git("ls-remote", "--symref", "origin", "HEAD", cwd=checkout).splitlines(): + value, _, ref = line.partition("\t") + if ref != "HEAD": + continue + if value.startswith("ref: refs/heads/"): + branch = value.removeprefix("ref: refs/heads/") + else: + commit = value + if not branch or not commit: + raise PublishError(f"{checkout}: cannot read the default branch of origin") + return branch, commit + + +def require_current(checkout): + branch, commit = remote_default(checkout) + head = git("rev-parse", "HEAD", cwd=checkout).strip() + if head != commit: + raise PublishError(f"{checkout}: HEAD {head} is not origin's {branch} head {commit}") + return branch + + +def require_origin(checkout, repository): + url = git("remote", "get-url", "origin", cwd=checkout).strip().rstrip("/").removesuffix(".git") + if not (url.endswith("/" + repository) or url.endswith(":" + repository)): + raise PublishError(f"{checkout}: origin {url} is not {repository}") + + +def gh(*arguments): + return run(["gh", *arguments]) + + +def pull_request(template, repository, base, sources, declaration_commit, changed): + titles = [f"{name} {sources[name][0]}" for name in sources if changed[name]] + title = "chore: publish " + ", ".join(titles) + rows = "\n".join( + f"| {name} | {tag} | `{commit}` | " + + (", ".join(f"`{path}`" for path in changed[name]) or "none") + + " |" + for name, (tag, commit) in sources.items() + ) + body = ( + f"Generated files from each producer's latest release, as declared at `{declaration_commit}`.\n\n" + "| Producer | Release | Commit | Changed files |\n| --- | --- | --- | --- |\n" + f"{rows}\n\n" + "Generated paths are changed in their producer and arrive through its next release.\n" + ) + digest = hashlib.sha256( + "\n".join([declaration_commit, *(f"{name} {commit}" for name, (_, commit) in sorted(sources.items()))]).encode() + ).hexdigest() + branch = "chore/publish-" + digest[:12] + paths = [path for name in sources for path in changed[name]] + git("switch", "--quiet", "-c", branch, cwd=template) + git("add", "--", *paths, cwd=template) + git("commit", "--quiet", "-S", "-m", title, "-m", + "\n".join(f"{name} {tag} {commit}" for name, (tag, commit) in sources.items()), cwd=template) + head = git("rev-parse", "HEAD", cwd=template).strip() + git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=template) + url = gh("pr", "create", "-R", repository, "--base", base, "--head", branch, + "--title", title, "--body", body).strip() + print(url) + if gh("api", f"repos/{repository}", "--jq", ".allow_auto_merge").strip() == "true": + gh("pr", "merge", url, "--auto", "--squash", "--body", "", "--match-head-commit", head) + print("auto-merge requested") + else: + print(f"auto-merge is disabled for {repository}; merge after the required checks pass") + + +def publish(declaration, template, *, write_only=False): + composition = load_composition(declaration) + repository = composition["template"] + require_clean(declaration) + require_clean(template) + require_origin(template, repository) + if not write_only: + require_current(declaration) + base = require_current(template) + declaration_commit = git("rev-parse", "HEAD", cwd=declaration).strip() + generators = composition["generators"] + check_destinations(template, [target for generator in generators for target in generator["files"]]) + sources = {} + with tempfile.TemporaryDirectory(prefix="publish-template-") as temporary: + root = Path(temporary) + outputs = [] + for index, generator in enumerate(generators): + name = generator["repository"] + # Every generator from one repository runs from that repository's single release. + if name not in sources: + url = source_url(name) + sources[name] = latest_release(url) + fetch_release(url, *sources[name], root / f"source-{len(sources)}") + source = root / f"source-{list(sources).index(name) + 1}" + output = root / f"output-{index}" + output.mkdir() + generate(generator, source, { + "template": template.resolve(), "output": output, "declaration": declaration.resolve(), + }, output) + outputs.append(output) + changed = {name: [] for name in sources} + for generator, output in zip(generators, outputs): + changed[generator["repository"]] += apply(template, generator["files"], output) + changed = {name: sorted(paths) for name, paths in changed.items()} + for name, (tag, commit) in sources.items(): + print(f"{name} {tag} {commit}: " + (", ".join(changed[name]) or "current")) + if not any(changed.values()): + print(f"{repository} is current") + return 0 + if not write_only: + pull_request(template, repository, base, sources, declaration_commit, changed) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--declaration", type=Path, required=True, + help="checkout of the repository whose MAINTENANCE.md declares the template composition", + ) + parser.add_argument("--template", type=Path, required=True, help="checkout of the template repository") + parser.add_argument( + "--write-only", action="store_true", + help="write the generated files into the template checkout without a commit or pull request", + ) + args = parser.parse_args(argv) + try: + return publish(args.declaration, args.template, write_only=args.write_only) + except PublishError as error: + print(f"publish-template: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_publish_template.py b/tests/test_publish_template.py new file mode 100644 index 0000000..37412ec --- /dev/null +++ b/tests/test_publish_template.py @@ -0,0 +1,296 @@ +import importlib.machinery +import importlib.util +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + + +# Keep test imports from creating unignored bytecode beside repository sources. +sys.dont_write_bytecode = True +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts/publish-template.py" + + +def load_script(): + loader = importlib.machinery.SourceFileLoader("publish_template", str(SCRIPT)) + spec = importlib.util.spec_from_loader("publish_template", loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +publisher = load_script() + +GENERATOR = """\ +import sys +from pathlib import Path + +version = Path("VERSION").read_text().strip() +template, output, mode = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3] +name = (template / "Package.swift").read_text().splitlines()[0] +if mode in ("guide", "extra"): + (output / "Guide.md").write_text(f"guide {version} for {name}\\n") +if mode in ("mark", "extra"): + (output / "logo").mkdir() + design = Path(sys.argv[4]).joinpath("DESIGN.md").read_text().strip() + (output / "logo/mark.txt").write_text(f"mark {version} from {design}\\n") +""" + +GH = """\ +import json +import os +import sys + +with open(os.environ["GH_LOG"], "a") as log: + log.write(json.dumps(sys.argv[1:]) + "\\n") +if sys.argv[1:3] == ["pr", "create"]: + print("https://github.com/example/template/pull/1") +elif sys.argv[1] == "api": + print(os.environ.get("AUTO_MERGE", "false")) +""" + + +def composition(*generators, template="example/template"): + return {"schema": 1, "template": template, "generators": list(generators)} + + +def generator(mode, files, repository="example/generators"): + command = ["python3", "generate.py", "{template}", "{output}", mode, "{declaration}"] + return {"repository": repository, "command": command, "files": files} + + +GUIDE = generator("guide", {"Docs/Guide.md": "Guide.md"}) +MARK = generator("mark", {"Assets/Mark.txt": "logo/mark.txt"}) + + +class PublishTemplateTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.root = Path(self.temporary.name).resolve() + self.remotes = self.root / "remotes" + self.gh_log = self.root / "gh.log" + key = self.root / "signing-key" + subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)], check=True) + config = self.root / "gitconfig" + config.write_text( + "[user]\n\tname = Example\n\temail = example@example.com\n" + f"\tsigningkey = {key}\n[gpg]\n\tformat = ssh\n[init]\n\tdefaultBranch = master\n" + f'[url "file://{self.remotes}/"]\n\tinsteadOf = https://github.com/\n' + ) + bin_directory = self.root / "bin" + bin_directory.mkdir() + stub = bin_directory / "gh" + stub.write_text(f"#!{sys.executable}\n{GH}") + stub.chmod(0o755) + self.env = { + **os.environ, "HOME": str(self.root), "GIT_CONFIG_GLOBAL": str(config), + "GIT_CONFIG_NOSYSTEM": "1", "GH_LOG": str(self.gh_log), + "PATH": f"{bin_directory}{os.pathsep}{os.environ['PATH']}", + } + self.producer = self.repository("example/generators", {"generate.py": GENERATOR, "VERSION": "0.1.0\n"}) + self.release(self.producer, "v0.1.0", annotated=True) + self.commit(self.producer, {"VERSION": "0.2.0\n"}) + self.release(self.producer, "v0.2.0") + self.commit(self.producer, {"VERSION": "0.10.0\n"}) + self.release(self.producer, "v0.10.0", annotated=True) + self.commit(self.producer, {"VERSION": "1.0.0-rc.1\n"}) + self.release(self.producer, "v1.0.0-rc.1", annotated=True) + self.commit(self.producer, {"VERSION": "unreleased\n"}) + self.template = self.repository("example/template", { + "Package.swift": "// example-template\n", "Docs/Guide.md": "old guide\n", "Keep.md": "kept\n", + }) + self.declare(composition(GUIDE, MARK)) + + def tearDown(self): + self.temporary.cleanup() + + def git(self, *arguments, cwd): + return subprocess.run( + ["git", *arguments], cwd=cwd, env=self.env, check=True, capture_output=True, text=True, + ).stdout + + def commit(self, checkout, files): + for name, text in files.items(): + path = checkout / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + self.git("add", "-A", cwd=checkout) + self.git("commit", "-q", "-m", "chore: update", cwd=checkout) + self.git("push", "-q", "origin", "HEAD:master", cwd=checkout) + + def repository(self, name, files): + bare = self.remotes / f"{name}.git" + self.git("init", "-q", "--bare", str(bare), cwd=self.root) + checkout = self.root / "checkouts" / name + checkout.parent.mkdir(parents=True, exist_ok=True) + self.git("clone", "-q", f"https://github.com/{name}.git", str(checkout), cwd=self.root) + self.commit(checkout, files) + return checkout + + def release(self, checkout, tag, *, annotated=False): + self.git("tag", *(["-a", "-m", tag] if annotated else []), tag, cwd=checkout) + self.git("push", "-q", "origin", tag, cwd=checkout) + + def declare(self, value, *, design="design 1"): + files = { + "MAINTENANCE.md": "# Maintenance\n\n\n```json\n" + + json.dumps(value, indent=2) + "\n```\n", + "DESIGN.md": design + "\n", + } + if hasattr(self, "declaration"): + self.commit(self.declaration, files) + else: + self.declaration = self.repository("example/.github", files) + + def publish(self, *arguments, expected=0, env=None): + result = subprocess.run( + [sys.executable, "-B", str(SCRIPT), "--declaration", str(self.declaration), + "--template", str(self.template), *arguments], + env={**self.env, **(env or {})}, capture_output=True, text=True, + ) + self.assertEqual(result.returncode, expected, result.stdout + result.stderr) + return result + + def gh_calls(self): + if not self.gh_log.exists(): + return [] + return [json.loads(line) for line in self.gh_log.read_text().splitlines()] + + def test_latest_release_is_the_highest_stable_version(self): + with mock.patch.dict(os.environ, self.env, clear=True): + tag, commit = publisher.latest_release("https://github.com/example/generators.git") + self.assertEqual(tag, "v0.10.0") + self.assertEqual(commit, self.git("rev-parse", "v0.10.0^{commit}", cwd=self.producer).strip()) + + def test_write_only_regenerates_declared_files_from_one_release(self): + head = self.git("rev-parse", "HEAD", cwd=self.template) + result = self.publish("--write-only") + self.assertEqual( + (self.template / "Docs/Guide.md").read_text(), "guide 0.10.0 for // example-template\n", + ) + self.assertEqual((self.template / "Assets/Mark.txt").read_text(), "mark 0.10.0 from design 1\n") + self.assertEqual((self.template / "Keep.md").read_text(), "kept\n") + self.assertEqual((self.template / "Package.swift").read_text(), "// example-template\n") + self.assertEqual(result.stdout.count("example/generators v0.10.0"), 1) + self.assertIn("Assets/Mark.txt, Docs/Guide.md", result.stdout) + self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.template), head) + self.assertEqual(self.gh_calls(), []) + + def test_current_template_needs_no_pull_request(self): + self.publish("--write-only") + self.git("add", "-A", cwd=self.template) + self.git("commit", "-q", "-m", "chore: publish", cwd=self.template) + self.git("push", "-q", "origin", "HEAD:master", cwd=self.template) + result = self.publish() + self.assertIn("example/template is current", result.stdout) + self.assertEqual(self.gh_calls(), []) + + def test_publish_opens_one_signed_pull_request(self): + result = self.publish() + calls = self.gh_calls() + self.assertEqual(len(calls), 2, calls) + create, api = calls + branch = create[7] + self.assertEqual(create, [ + "pr", "create", "-R", "example/template", "--base", "master", "--head", branch, + "--title", "chore: publish example/generators v0.10.0", "--body", create[11], + ]) + self.assertRegex(branch, r"^chore/publish-[0-9a-f]{12}$") + self.assertIn("| example/generators | v0.10.0 |", create[11]) + self.assertEqual(api, ["api", "repos/example/template", "--jq", ".allow_auto_merge"]) + self.assertIn("auto-merge is disabled for example/template", result.stdout) + bare = self.remotes / "example/template.git" + published = self.git("rev-parse", f"refs/heads/{branch}", cwd=bare).strip() + self.assertIn("gpgsig", self.git("cat-file", "commit", published, cwd=bare)) + changed = self.git("diff", "--name-only", "master", published, cwd=bare).split() + self.assertEqual(changed, ["Assets/Mark.txt", "Docs/Guide.md"]) + + def test_publish_requests_auto_merge_when_the_template_allows_it(self): + self.publish(env={"AUTO_MERGE": "true"}) + merge = self.gh_calls()[2] + head = self.git("rev-parse", "HEAD", cwd=self.template).strip() + self.assertEqual(merge, [ + "pr", "merge", "https://github.com/example/template/pull/1", "--auto", "--squash", + "--body", "", "--match-head-commit", head, + ]) + + def test_undeclared_generated_file_fails_before_writing(self): + self.declare(composition(generator("extra", {"Docs/Guide.md": "Guide.md"}))) + result = self.publish("--write-only", expected=1) + self.assertIn("undeclared: logo/mark.txt", result.stderr) + self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") + + def test_missing_generated_file_fails_before_writing(self): + self.declare(composition(GUIDE, generator("none", {"Assets/Mark.txt": "logo/mark.txt"}))) + result = self.publish("--write-only", expected=1) + self.assertIn("missing: logo/mark.txt", result.stderr) + self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") + + def test_dirty_template_fails_before_generating(self): + (self.template / "Keep.md").write_text("local edit\n") + result = self.publish("--write-only", expected=1) + self.assertIn("uncommitted changes", result.stderr) + self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") + + def test_stale_template_fails_before_publishing(self): + other = self.root / "other" + self.git("clone", "-q", "https://github.com/example/template.git", str(other), cwd=self.root) + self.commit(other, {"Keep.md": "newer\n"}) + result = self.publish(expected=1) + self.assertIn("is not origin's master head", result.stderr) + self.assertEqual(self.gh_calls(), []) + + def test_template_origin_must_match_the_declaration(self): + self.declare(composition(GUIDE, template="example/other")) + result = self.publish("--write-only", expected=1) + self.assertIn("is not example/other", result.stderr) + + def test_producer_without_release_tag_fails(self): + self.repository("example/untagged", {"generate.py": GENERATOR, "VERSION": "0\n"}) + self.declare(composition(generator("guide", {"Docs/Guide.md": "Guide.md"}, "example/untagged"))) + result = self.publish("--write-only", expected=1) + self.assertIn("no vMAJOR.MINOR.PATCH release tag", result.stderr) + + def test_symlinked_destination_fails_before_writing(self): + (self.template / "Docs/Guide.md").unlink() + (self.template / "Docs/Guide.md").symlink_to(self.root / "outside.md") + self.git("add", "-A", cwd=self.template) + self.git("commit", "-q", "-m", "chore: link", cwd=self.template) + result = self.publish("--write-only", expected=1) + self.assertIn("symbolic link", result.stderr) + self.assertFalse((self.root / "outside.md").exists()) + + def test_composition_must_be_well_formed(self): + cases = { + "unknown placeholder": composition({**GUIDE, "command": ["python3", "{source}"]}), + "parent path": composition({**GUIDE, "files": {"../Guide.md": "Guide.md"}}), + "unnormalized path": composition({**GUIDE, "files": {"./Guide.md": "Guide.md"}}), + "git path": composition({**GUIDE, "files": {".git/config": "Guide.md"}}), + "duplicate target": composition(GUIDE, {**MARK, "files": {"Docs/Guide.md": "logo/mark.txt"}}), + "missing key": {"schema": 1, "template": "example/template"}, + "extra key": composition({**GUIDE, "path": "x"}), + "bad repository": composition({**GUIDE, "repository": "generators"}), + "empty command": composition({**GUIDE, "command": []}), + "unknown schema": {**composition(GUIDE), "schema": 2}, + } + for name, value in cases.items(): + with self.subTest(name): + with self.assertRaises(publisher.PublishError): + publisher.validate_composition(value) + publisher.validate_composition(composition(GUIDE, MARK)) + + def test_duplicate_json_key_is_rejected(self): + maintenance = self.declaration / "MAINTENANCE.md" + maintenance.write_text(maintenance.read_text().replace('"schema": 1,', '"schema": 1,\n "schema": 1,')) + with self.assertRaisesRegex(publisher.PublishError, "duplicate key 'schema'"): + publisher.load_composition(self.declaration) + + +if __name__ == "__main__": + unittest.main() From 85dfec171c97c3eb78919ee90f066dd6fb65dfd8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:01:30 +0800 Subject: [PATCH 2/5] fix: guard the template publisher's destinations and recovery The publisher requires origin to name the declared template on GitHub and to push where it fetches, rejects Git metadata paths in any letter case, nested declared files and file ancestors before writing, and stops before writing when the publication branch already exists. A failed push, pull request or auto-merge request reports the command that completes it. --- README.md | 23 ++++---- scripts/publish-template.py | 99 +++++++++++++++++++++++++++------- tests/test_publish_template.py | 55 ++++++++++++++++++- 3 files changed, 149 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 5aa7c47..0e33587 100644 --- a/README.md +++ b/README.md @@ -195,15 +195,20 @@ and the declaration checkout. The generated files must be exactly the declared `files` values. The script writes only declared template paths, and writes nothing unless every generator succeeds. -Both checkouts must be clean, and the template's origin must be the declared -template. Unless `--write-only` is given, both must also be at their origin's -default branch head. When files change, the script commits them with a signature -on `chore/publish-`, pushes that branch and opens one pull request that -lists each producer's release, commit and changed files. When the template -allows auto-merge, it requests a squash merge of the pushed head. `--write-only` -writes the files without a commit or pull request. Runs need `git`, `gh` -authenticated to push to the template and open pull requests, signing -configured in the template checkout, and each generator's own tools. +Both checkouts must be clean. The template's origin must name the declared +template on GitHub, and must push where it fetches. Unless `--write-only` is +given, both checkouts must also be at their origin's default branch head. When +files change, the script commits them with a signature on +`chore/publish-`, where the digest covers the declaration and producer +commits. It pushes that branch, opens one pull request that lists each +producer's release, commit and changed files, and leaves the template checkout +on that branch. When the template allows auto-merge, it requests a squash merge +of the pushed head. If the branch already exists, locally or on origin, the run +stops before writing anything. A failed push, pull request or auto-merge request +reports the command that completes it. `--write-only` writes the files without a +commit or pull request. Runs need `git`, `gh` authenticated to push to the +template and open pull requests, signing configured in the template checkout, +and each generator's own tools. No workflow calls the script: opening a pull request in another repository needs an App credential, so a maintainer runs it with their own credentials diff --git a/scripts/publish-template.py b/scripts/publish-template.py index f7e58ef..8e6e040 100755 --- a/scripts/publish-template.py +++ b/scripts/publish-template.py @@ -17,6 +17,10 @@ RELEASE = re.compile(r"v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)") PLACEHOLDER = re.compile(r"\{([a-z]+)\}") PLACEHOLDERS = frozenset({"template", "output", "declaration"}) +GITHUB_URL = re.compile( + r"(?:https://github\.com/|ssh://git@github\.com/|git@github\.com:)" + r"(?P[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?)(?:\.git)?/?" +) class PublishError(Exception): @@ -36,7 +40,9 @@ def relative_path(value, label): if not isinstance(value, str) or not value: raise PublishError(f"{label}: expected a relative path") path = Path(value) - if path.is_absolute() or ".." in path.parts or ".git" in path.parts or path.as_posix() != value: + # Case-insensitive file systems resolve .GIT to the repository metadata too. + if (path.is_absolute() or ".." in path.parts or path.as_posix() != value + or any(part.casefold() == ".git" for part in path.parts)): raise PublishError(f"{label}: {value!r} must be a normalized path inside the repository") return path @@ -71,6 +77,10 @@ def validate_composition(value): if target in targets: raise PublishError(f"{label}.files: {target!r} is declared by more than one generator") targets.add(target) + for target in targets: + for parent in Path(target).parents: + if parent.as_posix() in targets: + raise PublishError(f"template composition: {target!r} is inside the declared file {parent.as_posix()!r}") def load_composition(root): @@ -158,6 +168,9 @@ def check_destinations(template, targets): for relative in (Path(target), *Path(target).parents): if (template / relative).is_symlink(): raise PublishError(f"{destination}: path crosses a symbolic link") + for parent in Path(target).parents: + if (template / parent).exists() and not (template / parent).is_dir(): + raise PublishError(f"{destination}: {template / parent} must be a directory") if not destination.resolve().is_relative_to(root): raise PublishError(f"{destination}: must stay inside {template}") if destination.exists() and not destination.is_file(): @@ -206,16 +219,51 @@ def require_current(checkout): def require_origin(checkout, repository): - url = git("remote", "get-url", "origin", cwd=checkout).strip().rstrip("/").removesuffix(".git") - if not (url.endswith("/" + repository) or url.endswith(":" + repository)): - raise PublishError(f"{checkout}: origin {url} is not {repository}") + """Require origin to be the template on GitHub, and pushes to go where fetches do.""" + result = subprocess.run( + ["git", "config", "--get-all", "remote.origin.url"], cwd=checkout, + capture_output=True, text=True, stdin=subprocess.DEVNULL, + ) + urls = result.stdout.splitlines() + if result.returncode or not urls: + raise PublishError(f"{checkout}: has no origin remote") + for url in urls: + match = GITHUB_URL.fullmatch(url) + if match is None or match["repository"].lower() != repository.lower(): + raise PublishError(f"{checkout}: origin {url} is not github.com/{repository}") + fetch = git("remote", "get-url", "--all", "origin", cwd=checkout).splitlines() + push = git("remote", "get-url", "--push", "--all", "origin", cwd=checkout).splitlines() + if push != fetch: + raise PublishError(f"{checkout}: origin pushes to {', '.join(push)}, not to {', '.join(fetch)}") def gh(*arguments): return run(["gh", *arguments]) -def pull_request(template, repository, base, sources, declaration_commit, changed): +def publication_branch(declaration_commit, sources): + digest = hashlib.sha256( + "\n".join([declaration_commit, *(f"{name} {commit}" for name, (_, commit) in sorted(sources.items()))]).encode() + ).hexdigest() + return "chore/publish-" + digest[:12] + + +def require_unpublished(template, repository, branch): + local = subprocess.run( + ["git", "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], cwd=template, + capture_output=True, stdin=subprocess.DEVNULL, + ).returncode == 0 + remote = bool(git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=template).strip()) + if local or remote: + place = "on origin" if remote else "in the template checkout" + raise PublishError( + f"branch {branch} already exists {place}: these releases were published before. " + f"Find its pull request with `gh pr list -R {repository} --head {branch} --state all`, " + "or delete the branch to publish them again" + ) + + +def pull_request(template, repository, base, branch, sources, declaration_commit, changed): titles = [f"{name} {sources[name][0]}" for name in sources if changed[name]] title = "chore: publish " + ", ".join(titles) rows = "\n".join( @@ -230,25 +278,37 @@ def pull_request(template, repository, base, sources, declaration_commit, change f"{rows}\n\n" "Generated paths are changed in their producer and arrive through its next release.\n" ) - digest = hashlib.sha256( - "\n".join([declaration_commit, *(f"{name} {commit}" for name, (_, commit) in sorted(sources.items()))]).encode() - ).hexdigest() - branch = "chore/publish-" + digest[:12] paths = [path for name in sources for path in changed[name]] + create = f"gh pr create -R {repository} --base {base} --head {branch} --fill" git("switch", "--quiet", "-c", branch, cwd=template) git("add", "--", *paths, cwd=template) git("commit", "--quiet", "-S", "-m", title, "-m", "\n".join(f"{name} {tag} {commit}" for name, (tag, commit) in sources.items()), cwd=template) head = git("rev-parse", "HEAD", cwd=template).strip() - git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=template) - url = gh("pr", "create", "-R", repository, "--base", base, "--head", branch, - "--title", title, "--body", body).strip() + try: + git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=template) + except PublishError as error: + raise PublishError( + f"{error}\nThe commit is on local branch {branch}. Push it with " + f"`git push origin {branch}`, then open the pull request with `{create}`" + ) from error + try: + url = gh("pr", "create", "-R", repository, "--base", base, "--head", branch, + "--title", title, "--body", body).strip() + except PublishError as error: + raise PublishError(f"{error}\nBranch {branch} is on origin. Open the pull request with `{create}`") from error print(url) - if gh("api", f"repos/{repository}", "--jq", ".allow_auto_merge").strip() == "true": - gh("pr", "merge", url, "--auto", "--squash", "--body", "", "--match-head-commit", head) - print("auto-merge requested") - else: + if gh("api", f"repos/{repository}", "--jq", ".allow_auto_merge").strip() != "true": print(f"auto-merge is disabled for {repository}; merge after the required checks pass") + return + try: + gh("pr", "merge", url, "--auto", "--squash", "--body", "", "--match-head-commit", head) + except PublishError as error: + raise PublishError( + f"{error}\n{url} is open. Request auto-merge with `gh pr merge {url} --auto --squash " + f"--body '' --match-head-commit {head}`, or merge it after the required checks pass" + ) from error + print("auto-merge requested") def publish(declaration, template, *, write_only=False): @@ -281,6 +341,9 @@ def publish(declaration, template, *, write_only=False): "template": template.resolve(), "output": output, "declaration": declaration.resolve(), }, output) outputs.append(output) + if not write_only: + branch = publication_branch(declaration_commit, sources) + require_unpublished(template, repository, branch) changed = {name: [] for name in sources} for generator, output in zip(generators, outputs): changed[generator["repository"]] += apply(template, generator["files"], output) @@ -291,7 +354,7 @@ def publish(declaration, template, *, write_only=False): print(f"{repository} is current") return 0 if not write_only: - pull_request(template, repository, base, sources, declaration_commit, changed) + pull_request(template, repository, base, branch, sources, declaration_commit, changed) return 0 @@ -309,7 +372,7 @@ def main(argv=None): args = parser.parse_args(argv) try: return publish(args.declaration, args.template, write_only=args.write_only) - except PublishError as error: + except (PublishError, OSError) as error: print(f"publish-template: {error}", file=sys.stderr) return 1 diff --git a/tests/test_publish_template.py b/tests/test_publish_template.py index 37412ec..740ba42 100644 --- a/tests/test_publish_template.py +++ b/tests/test_publish_template.py @@ -49,6 +49,8 @@ def load_script(): with open(os.environ["GH_LOG"], "a") as log: log.write(json.dumps(sys.argv[1:]) + "\\n") +if sys.argv[1] == "pr" and os.environ.get("GH_FAIL") == sys.argv[2]: + sys.exit("gh: request failed") if sys.argv[1:3] == ["pr", "create"]: print("https://github.com/example/template/pull/1") elif sys.argv[1] == "api": @@ -249,7 +251,20 @@ def test_stale_template_fails_before_publishing(self): def test_template_origin_must_match_the_declaration(self): self.declare(composition(GUIDE, template="example/other")) result = self.publish("--write-only", expected=1) - self.assertIn("is not example/other", result.stderr) + self.assertIn("is not github.com/example/other", result.stderr) + + def test_origin_must_be_the_template_on_github(self): + self.git("remote", "set-url", "origin", "https://example.com/example/template.git", cwd=self.template) + result = self.publish("--write-only", expected=1) + self.assertIn("is not github.com/example/template", result.stderr) + self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") + + def test_origin_must_push_where_it_fetches(self): + self.git("remote", "set-url", "--push", "origin", "https://github.com/example/generators.git", + cwd=self.template) + result = self.publish("--write-only", expected=1) + self.assertIn("origin pushes to", result.stderr) + self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") def test_producer_without_release_tag_fails(self): self.repository("example/untagged", {"generate.py": GENERATOR, "VERSION": "0\n"}) @@ -257,6 +272,41 @@ def test_producer_without_release_tag_fails(self): result = self.publish("--write-only", expected=1) self.assertIn("no vMAJOR.MINOR.PATCH release tag", result.stderr) + def test_file_ancestor_fails_before_writing(self): + self.declare(composition(GUIDE, {**MARK, "files": {"Keep.md/Mark.txt": "logo/mark.txt"}})) + result = self.publish("--write-only", expected=1) + self.assertIn("must be a directory", result.stderr) + self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") + self.assertEqual((self.template / "Keep.md").read_text(), "kept\n") + + def test_existing_publication_stops_before_writing(self): + self.publish() + self.git("switch", "-q", "master", cwd=self.template) + calls = len(self.gh_calls()) + result = self.publish(expected=1) + self.assertIn("already exists on origin", result.stderr) + self.assertIn("gh pr list -R example/template --head chore/publish-", result.stderr) + self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") + self.assertEqual(len(self.gh_calls()), calls) + + def test_failed_push_names_the_recovery(self): + hook = self.remotes / "example/template.git/hooks/pre-receive" + hook.write_text("#!/bin/sh\nexit 1\n") + hook.chmod(0o755) + result = self.publish(expected=1) + self.assertRegex(result.stderr, r"Push it with `git push origin chore/publish-[0-9a-f]{12}`") + self.assertIn("gh pr create -R example/template --base master", result.stderr) + self.assertEqual(self.gh_calls(), []) + + def test_failed_pull_request_names_the_recovery(self): + result = self.publish(expected=1, env={"GH_FAIL": "create"}) + self.assertIn("is on origin. Open the pull request with `gh pr create -R example/template", result.stderr) + + def test_failed_auto_merge_names_the_recovery(self): + result = self.publish(expected=1, env={"AUTO_MERGE": "true", "GH_FAIL": "merge"}) + self.assertIn("https://github.com/example/template/pull/1 is open. Request auto-merge with " + "`gh pr merge https://github.com/example/template/pull/1 --auto", result.stderr) + def test_symlinked_destination_fails_before_writing(self): (self.template / "Docs/Guide.md").unlink() (self.template / "Docs/Guide.md").symlink_to(self.root / "outside.md") @@ -272,6 +322,9 @@ def test_composition_must_be_well_formed(self): "parent path": composition({**GUIDE, "files": {"../Guide.md": "Guide.md"}}), "unnormalized path": composition({**GUIDE, "files": {"./Guide.md": "Guide.md"}}), "git path": composition({**GUIDE, "files": {".git/config": "Guide.md"}}), + "git path in another case": composition({**GUIDE, "files": {".GIT/config": "Guide.md"}}), + "generated git path": composition({**GUIDE, "files": {"Guide.md": "Docs/.Git/x"}}), + "nested targets": composition(GUIDE, {**MARK, "files": {"Docs": "logo/mark.txt"}}), "duplicate target": composition(GUIDE, {**MARK, "files": {"Docs/Guide.md": "logo/mark.txt"}}), "missing key": {"schema": 1, "template": "example/template"}, "extra key": composition({**GUIDE, "path": "x"}), From e472acae587eeb388110aef62dfd6a44f1b0fba6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:15:07 +0800 Subject: [PATCH 3/5] fix: resume interrupted template publications The publisher checks every effective fetch and push URL of the template's origin, after Git's URL rewriting, against the declared repository on GitHub, and rejects declared paths that collide or nest when letter case is ignored. A failed push, pull request or auto-merge request now asks for the same command again: the rerun resumes from the publication branch in the checkout or on origin when that branch builds on the current default head and holds the current releases' output, keeping the pull request's description. --- README.md | 41 ++++--- scripts/publish-template.py | 216 +++++++++++++++++++-------------- tests/test_publish_template.py | 193 +++++++++++++++++++---------- 3 files changed, 273 insertions(+), 177 deletions(-) diff --git a/README.md b/README.md index 0e33587..ca16d86 100644 --- a/README.md +++ b/README.md @@ -192,23 +192,30 @@ pre-releases; every generator from one repository runs from that one release. Each command runs from the release checkout's root, with `{template}`, `{output}` and `{declaration}` replaced by the template checkout, an empty output directory and the declaration checkout. The generated files must be exactly the declared -`files` values. The script writes only declared template paths, and writes -nothing unless every generator succeeds. - -Both checkouts must be clean. The template's origin must name the declared -template on GitHub, and must push where it fetches. Unless `--write-only` is -given, both checkouts must also be at their origin's default branch head. When -files change, the script commits them with a signature on -`chore/publish-`, where the digest covers the declaration and producer -commits. It pushes that branch, opens one pull request that lists each -producer's release, commit and changed files, and leaves the template checkout -on that branch. When the template allows auto-merge, it requests a squash merge -of the pushed head. If the branch already exists, locally or on origin, the run -stops before writing anything. A failed push, pull request or auto-merge request -reports the command that completes it. `--write-only` writes the files without a -commit or pull request. Runs need `git`, `gh` authenticated to push to the -template and open pull requests, signing configured in the template checkout, -and each generator's own tools. +`files` values. Declared paths must be distinct and must not contain one another, +ignoring letter case, and must not name Git metadata. The script writes only +declared template paths, and writes nothing unless every generator succeeds and +every destination is absent or a regular file whose parents are directories, +with no symbolic link on the way. + +Both checkouts must be clean. Every URL the template's origin fetches from or +pushes to, after Git's URL rewriting, must name the declared template on GitHub. +Unless `--write-only` is given, the declaration checkout must be at its origin's +default branch head. When files change, the script commits them with a signature +on `chore/publish-`, where the digest covers the declaration and producer +commits. It pushes that branch, opens one pull request that lists each producer's +release, commit and changed files, and leaves the template checkout on that +branch. When the template allows auto-merge, it requests a squash merge of the +pushed head. `--write-only` writes the files without a commit or pull request. + +A run that fails after committing asks for the same command again. The rerun +resumes the publication from the branch, in the template checkout or on origin, +when the branch builds on origin's current default branch head and holds the +current releases' output. It pushes the branch if needed, opens the pull request +if none is open and requests auto-merge if it is allowed and not yet requested. +Otherwise the template checkout must be at origin's default branch head. Runs +need `git`, `gh` authenticated to push to the template and open pull requests, +signing configured in the template checkout, and each generator's own tools. No workflow calls the script: opening a pull request in another repository needs an App credential, so a maintainer runs it with their own credentials diff --git a/scripts/publish-template.py b/scripts/publish-template.py index 8e6e040..6f86d82 100755 --- a/scripts/publish-template.py +++ b/scripts/publish-template.py @@ -21,6 +21,7 @@ r"(?:https://github\.com/|ssh://git@github\.com/|git@github\.com:)" r"(?P[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?)(?:\.git)?/?" ) +RESUME = "Run the same command again to resume the publication." class PublishError(Exception): @@ -55,7 +56,8 @@ def validate_composition(value): generators = value["generators"] if not isinstance(generators, list) or not generators: raise PublishError("template composition: generators must be a nonempty list") - targets = set() + # Keyed by case-folded path so that declarations stay distinct on case-insensitive file systems. + targets = {} for index, generator in enumerate(generators): label = f"generators[{index}]" if not isinstance(generator, dict) or set(generator) != {"repository", "command", "files"}: @@ -74,13 +76,15 @@ def validate_composition(value): for target, produced in files.items(): relative_path(target, f"{label}.files") relative_path(produced, f"{label}.files[{target!r}]") - if target in targets: - raise PublishError(f"{label}.files: {target!r} is declared by more than one generator") - targets.add(target) - for target in targets: - for parent in Path(target).parents: + if target.casefold() in targets: + raise PublishError(f"{label}.files: {target!r} is declared more than once, ignoring case") + targets[target.casefold()] = target + for folded, target in targets.items(): + for parent in Path(folded).parents: if parent.as_posix() in targets: - raise PublishError(f"template composition: {target!r} is inside the declared file {parent.as_posix()!r}") + raise PublishError( + f"template composition: {target!r} is inside the declared file {targets[parent.as_posix()]!r}" + ) def load_composition(root): @@ -110,6 +114,10 @@ def git(*arguments, cwd=None): return run(["git", *arguments], cwd=cwd) +def gh(*arguments): + return run(["gh", *arguments]) + + def source_url(repository): return f"https://github.com/{repository}.git" @@ -177,17 +185,19 @@ def check_destinations(template, targets): raise PublishError(f"{destination}: must be a regular file") -def apply(template, files, output): - changed = [] - for target, produced in sorted(files.items()): +def differences(template, files, output): + return sorted( + target for target, produced in files.items() + if not (template / target).is_file() + or (template / target).read_bytes() != (output / produced).read_bytes() + ) + + +def write(template, files, output, targets): + for target in targets: destination = template / target - content = (output / produced).read_bytes() - if destination.is_file() and destination.read_bytes() == content: - continue destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_bytes(content) - changed.append(target) - return changed + destination.write_bytes((output / files[target]).read_bytes()) def require_clean(checkout): @@ -215,30 +225,16 @@ def require_current(checkout): head = git("rev-parse", "HEAD", cwd=checkout).strip() if head != commit: raise PublishError(f"{checkout}: HEAD {head} is not origin's {branch} head {commit}") - return branch def require_origin(checkout, repository): - """Require origin to be the template on GitHub, and pushes to go where fetches do.""" - result = subprocess.run( - ["git", "config", "--get-all", "remote.origin.url"], cwd=checkout, - capture_output=True, text=True, stdin=subprocess.DEVNULL, - ) - urls = result.stdout.splitlines() - if result.returncode or not urls: - raise PublishError(f"{checkout}: has no origin remote") + """Require every URL origin fetches from or pushes to, after rewriting, to be the template on GitHub.""" + urls = (git("remote", "get-url", "--all", "origin", cwd=checkout).splitlines() + + git("remote", "get-url", "--push", "--all", "origin", cwd=checkout).splitlines()) for url in urls: match = GITHUB_URL.fullmatch(url) if match is None or match["repository"].lower() != repository.lower(): - raise PublishError(f"{checkout}: origin {url} is not github.com/{repository}") - fetch = git("remote", "get-url", "--all", "origin", cwd=checkout).splitlines() - push = git("remote", "get-url", "--push", "--all", "origin", cwd=checkout).splitlines() - if push != fetch: - raise PublishError(f"{checkout}: origin pushes to {', '.join(push)}, not to {', '.join(fetch)}") - - -def gh(*arguments): - return run(["gh", *arguments]) + raise PublishError(f"{checkout}: origin uses {url}, which is not github.com/{repository}") def publication_branch(declaration_commit, sources): @@ -248,24 +244,42 @@ def publication_branch(declaration_commit, sources): return "chore/publish-" + digest[:12] -def require_unpublished(template, repository, branch): +def prepare_checkout(template, branch): + """Return origin's default branch, its head, and whether the checkout holds an earlier publication commit.""" + base, base_commit = remote_default(template) + head = git("rev-parse", "HEAD", cwd=template).strip() + current = subprocess.run( + ["git", "symbolic-ref", "--quiet", "--short", "HEAD"], cwd=template, + capture_output=True, text=True, stdin=subprocess.DEVNULL, + ).stdout.strip() local = subprocess.run( ["git", "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], cwd=template, - capture_output=True, stdin=subprocess.DEVNULL, - ).returncode == 0 - remote = bool(git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=template).strip()) - if local or remote: - place = "on origin" if remote else "in the template checkout" + capture_output=True, text=True, stdin=subprocess.DEVNULL, + ).stdout.strip() + remote = git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=template).partition("\t")[0] + if current != branch: + if head != base_commit: + raise PublishError(f"{template}: HEAD {head} is neither origin's {base} head nor branch {branch}") + if not local and not remote: + return base, base_commit, False + if not local: + git("fetch", "--quiet", "origin", f"refs/heads/{branch}:refs/heads/{branch}", cwd=template) + git("switch", "--quiet", branch, cwd=template) + head = git("rev-parse", "HEAD", cwd=template).strip() + parents = git("rev-list", "--parents", "-n", "1", "HEAD", cwd=template).split()[1:] + if parents != [base_commit]: raise PublishError( - f"branch {branch} already exists {place}: these releases were published before. " - f"Find its pull request with `gh pr list -R {repository} --head {branch} --state all`, " - "or delete the branch to publish them again" + f"branch {branch} does not build on origin's {base} head {base_commit}; " + "delete the branch locally and on origin to publish again" ) + if remote and remote != head: + raise PublishError(f"branch {branch} on origin is {remote}, not the local commit {head}") + print(f"resuming {branch}") + return base, base_commit, True -def pull_request(template, repository, base, branch, sources, declaration_commit, changed): - titles = [f"{name} {sources[name][0]}" for name in sources if changed[name]] - title = "chore: publish " + ", ".join(titles) +def pull_request_text(sources, declaration_commit, changed): + title = "chore: publish " + ", ".join(f"{name} {sources[name][0]}" for name in sources if changed[name]) rows = "\n".join( f"| {name} | {tag} | `{commit}` | " + (", ".join(f"`{path}`" for path in changed[name]) or "none") @@ -278,83 +292,97 @@ def pull_request(template, repository, base, branch, sources, declaration_commit f"{rows}\n\n" "Generated paths are changed in their producer and arrive through its next release.\n" ) - paths = [path for name in sources for path in changed[name]] - create = f"gh pr create -R {repository} --base {base} --head {branch} --fill" - git("switch", "--quiet", "-c", branch, cwd=template) - git("add", "--", *paths, cwd=template) - git("commit", "--quiet", "-S", "-m", title, "-m", - "\n".join(f"{name} {tag} {commit}" for name, (tag, commit) in sources.items()), cwd=template) + return title, body + + +def finish(template, repository, base, branch, title, body): head = git("rev-parse", "HEAD", cwd=template).strip() try: - git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=template) - except PublishError as error: - raise PublishError( - f"{error}\nThe commit is on local branch {branch}. Push it with " - f"`git push origin {branch}`, then open the pull request with `{create}`" - ) from error - try: - url = gh("pr", "create", "-R", repository, "--base", base, "--head", branch, - "--title", title, "--body", body).strip() - except PublishError as error: - raise PublishError(f"{error}\nBranch {branch} is on origin. Open the pull request with `{create}`") from error - print(url) - if gh("api", f"repos/{repository}", "--jq", ".allow_auto_merge").strip() != "true": - print(f"auto-merge is disabled for {repository}; merge after the required checks pass") - return - try: - gh("pr", "merge", url, "--auto", "--squash", "--body", "", "--match-head-commit", head) + remote = git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=template).partition("\t")[0] + if remote != head: + git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=template) + url = gh("pr", "list", "-R", repository, "--head", branch, "--state", "open", + "--json", "url", "--jq", ".[0].url // empty").strip() + if not url: + url = gh("pr", "create", "-R", repository, "--base", base, "--head", branch, + "--title", title, "--body", body).strip() + print(url) + if gh("api", f"repos/{repository}", "--jq", ".allow_auto_merge").strip() != "true": + print(f"auto-merge is disabled for {repository}; merge after the required checks pass") + return + if gh("pr", "view", url, "--json", "autoMergeRequest", "--jq", ".autoMergeRequest != null").strip() != "true": + gh("pr", "merge", url, "--auto", "--squash", "--body", "", "--match-head-commit", head) + print("auto-merge requested") except PublishError as error: - raise PublishError( - f"{error}\n{url} is open. Request auto-merge with `gh pr merge {url} --auto --squash " - f"--body '' --match-head-commit {head}`, or merge it after the required checks pass" - ) from error - print("auto-merge requested") + raise PublishError(f"{error}\n{RESUME}") from error def publish(declaration, template, *, write_only=False): composition = load_composition(declaration) repository = composition["template"] + generators = composition["generators"] require_clean(declaration) require_clean(template) require_origin(template, repository) if not write_only: require_current(declaration) - base = require_current(template) declaration_commit = git("rev-parse", "HEAD", cwd=declaration).strip() - generators = composition["generators"] + # Every generator from one repository runs from that repository's single release. + sources = {name: latest_release(source_url(name)) for name in dict.fromkeys(g["repository"] for g in generators)} + for name, (tag, commit) in sources.items(): + print(f"{name} {tag} {commit}") + resuming = False + if not write_only: + branch = publication_branch(declaration_commit, sources) + base, base_commit, resuming = prepare_checkout(template, branch) check_destinations(template, [target for generator in generators for target in generator["files"]]) - sources = {} with tempfile.TemporaryDirectory(prefix="publish-template-") as temporary: root = Path(temporary) + checkouts = {name: root / f"source-{index}" for index, name in enumerate(sources)} + for name, checkout in checkouts.items(): + fetch_release(source_url(name), *sources[name], checkout) outputs = [] for index, generator in enumerate(generators): - name = generator["repository"] - # Every generator from one repository runs from that repository's single release. - if name not in sources: - url = source_url(name) - sources[name] = latest_release(url) - fetch_release(url, *sources[name], root / f"source-{len(sources)}") - source = root / f"source-{list(sources).index(name) + 1}" output = root / f"output-{index}" output.mkdir() - generate(generator, source, { + generate(generator, checkouts[generator["repository"]], { "template": template.resolve(), "output": output, "declaration": declaration.resolve(), }, output) outputs.append(output) - if not write_only: - branch = publication_branch(declaration_commit, sources) - require_unpublished(template, repository, branch) + pending = [differences(template, generator["files"], output) for generator, output in zip(generators, outputs)] + if resuming and any(pending): + raise PublishError( + f"branch {branch} differs from the current releases' output; " + "delete the branch locally and on origin to publish again" + ) + for generator, output, targets in zip(generators, outputs, pending): + write(template, generator["files"], output, targets) + if resuming: + changed = { + name: git("diff", "--name-only", base_commit, "HEAD", "--", + *[target for g in generators if g["repository"] == name for target in g["files"]], + cwd=template).split() + for name in sources + } + else: changed = {name: [] for name in sources} - for generator, output in zip(generators, outputs): - changed[generator["repository"]] += apply(template, generator["files"], output) + for generator, targets in zip(generators, pending): + changed[generator["repository"]] += targets changed = {name: sorted(paths) for name, paths in changed.items()} - for name, (tag, commit) in sources.items(): - print(f"{name} {tag} {commit}: " + (", ".join(changed[name]) or "current")) + for name in sources: + print(f"{name}: " + (", ".join(changed[name]) or "current")) if not any(changed.values()): print(f"{repository} is current") return 0 - if not write_only: - pull_request(template, repository, base, branch, sources, declaration_commit, changed) + if write_only: + return 0 + title, body = pull_request_text(sources, declaration_commit, changed) + if not resuming: + git("switch", "--quiet", "-c", branch, cwd=template) + git("add", "--", *[path for paths in changed.values() for path in paths], cwd=template) + git("commit", "--quiet", "-S", "-m", title, "-m", + "\n".join(f"{name} {tag} {commit}" for name, (tag, commit) in sources.items()), cwd=template) + finish(template, repository, base, branch, title, body) return 0 diff --git a/tests/test_publish_template.py b/tests/test_publish_template.py index 740ba42..080a966 100644 --- a/tests/test_publish_template.py +++ b/tests/test_publish_template.py @@ -3,7 +3,6 @@ import json import os from pathlib import Path -import shutil import subprocess import sys import tempfile @@ -42,19 +41,44 @@ def load_script(): (output / "logo/mark.txt").write_text(f"mark {version} from {design}\\n") """ +# Serves git@github.com:/.git from the local bare repositories. +SSH = """\ +import os +import shlex +import subprocess +import sys + +program, path = shlex.split(sys.argv[-1]) +service = program.removeprefix("git-") +sys.exit(subprocess.call(["git", service, os.path.join(os.environ["FAKE_GITHUB"], path)])) +""" + GH = """\ import json import os import sys +from pathlib import Path +arguments = sys.argv[1:] with open(os.environ["GH_LOG"], "a") as log: - log.write(json.dumps(sys.argv[1:]) + "\\n") -if sys.argv[1] == "pr" and os.environ.get("GH_FAIL") == sys.argv[2]: + log.write(json.dumps(arguments) + "\\n") +state_path = Path(os.environ["GH_STATE"]) +state = json.loads(state_path.read_text()) if state_path.exists() else {"pulls": {}, "auto": []} +if arguments[0] == "pr" and os.environ.get("GH_FAIL") == arguments[1]: sys.exit("gh: request failed") -if sys.argv[1:3] == ["pr", "create"]: - print("https://github.com/example/template/pull/1") -elif sys.argv[1] == "api": +if arguments[:2] == ["pr", "list"]: + print(state["pulls"].get(arguments[arguments.index("--head") + 1], "")) +elif arguments[:2] == ["pr", "create"]: + url = f"https://github.com/example/template/pull/{len(state['pulls']) + 1}" + state["pulls"][arguments[arguments.index("--head") + 1]] = url + print(url) +elif arguments[:2] == ["pr", "view"]: + print("true" if arguments[2] in state["auto"] else "false") +elif arguments[:2] == ["pr", "merge"]: + state["auto"].append(arguments[2]) +elif arguments[0] == "api": print(os.environ.get("AUTO_MERGE", "false")) +state_path.write_text(json.dumps(state)) """ @@ -83,16 +107,19 @@ def setUp(self): config.write_text( "[user]\n\tname = Example\n\temail = example@example.com\n" f"\tsigningkey = {key}\n[gpg]\n\tformat = ssh\n[init]\n\tdefaultBranch = master\n" - f'[url "file://{self.remotes}/"]\n\tinsteadOf = https://github.com/\n' + '[url "git@github.com:"]\n\tinsteadOf = https://github.com/\n' ) bin_directory = self.root / "bin" bin_directory.mkdir() - stub = bin_directory / "gh" - stub.write_text(f"#!{sys.executable}\n{GH}") - stub.chmod(0o755) + for name, source in (("gh", GH), ("ssh", SSH)): + stub = bin_directory / name + stub.write_text(f"#!{sys.executable}\n{source}") + stub.chmod(0o755) self.env = { **os.environ, "HOME": str(self.root), "GIT_CONFIG_GLOBAL": str(config), - "GIT_CONFIG_NOSYSTEM": "1", "GH_LOG": str(self.gh_log), + "GIT_CONFIG_NOSYSTEM": "1", "GIT_SSH_COMMAND": str(bin_directory / "ssh"), + "GIT_SSH_VARIANT": "ssh", "FAKE_GITHUB": str(self.remotes), + "GH_LOG": str(self.gh_log), "GH_STATE": str(self.root / "gh-state.json"), "PATH": f"{bin_directory}{os.pathsep}{os.environ['PATH']}", } self.producer = self.repository("example/generators", {"generate.py": GENERATOR, "VERSION": "0.1.0\n"}) @@ -151,18 +178,27 @@ def declare(self, value, *, design="design 1"): self.declaration = self.repository("example/.github", files) def publish(self, *arguments, expected=0, env=None): + elsewhere = self.root / "elsewhere" + elsewhere.mkdir(exist_ok=True) result = subprocess.run( [sys.executable, "-B", str(SCRIPT), "--declaration", str(self.declaration), "--template", str(self.template), *arguments], - env={**self.env, **(env or {})}, capture_output=True, text=True, + cwd=elsewhere, env={**self.env, **(env or {})}, capture_output=True, text=True, ) self.assertEqual(result.returncode, expected, result.stdout + result.stderr) return result - def gh_calls(self): + def gh_calls(self, command=None): if not self.gh_log.exists(): return [] - return [json.loads(line) for line in self.gh_log.read_text().splitlines()] + calls = [json.loads(line) for line in self.gh_log.read_text().splitlines()] + return [call for call in calls if command is None or call[:2] == command] + + def published_branch(self): + bare = self.remotes / "example/template.git" + branches = self.git("for-each-ref", "--format=%(refname:short)", "refs/heads/chore", cwd=bare).split() + self.assertEqual(len(branches), 1, branches) + return branches[0], bare def test_latest_release_is_the_highest_stable_version(self): with mock.patch.dict(os.environ, self.env, clear=True): @@ -180,7 +216,7 @@ def test_write_only_regenerates_declared_files_from_one_release(self): self.assertEqual((self.template / "Keep.md").read_text(), "kept\n") self.assertEqual((self.template / "Package.swift").read_text(), "// example-template\n") self.assertEqual(result.stdout.count("example/generators v0.10.0"), 1) - self.assertIn("Assets/Mark.txt, Docs/Guide.md", result.stdout) + self.assertIn("example/generators: Assets/Mark.txt, Docs/Guide.md", result.stdout) self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.template), head) self.assertEqual(self.gh_calls(), []) @@ -195,19 +231,17 @@ def test_current_template_needs_no_pull_request(self): def test_publish_opens_one_signed_pull_request(self): result = self.publish() - calls = self.gh_calls() - self.assertEqual(len(calls), 2, calls) - create, api = calls - branch = create[7] + branch, bare = self.published_branch() + self.assertRegex(branch, r"^chore/publish-[0-9a-f]{12}$") + create, = self.gh_calls(["pr", "create"]) self.assertEqual(create, [ "pr", "create", "-R", "example/template", "--base", "master", "--head", branch, "--title", "chore: publish example/generators v0.10.0", "--body", create[11], ]) - self.assertRegex(branch, r"^chore/publish-[0-9a-f]{12}$") self.assertIn("| example/generators | v0.10.0 |", create[11]) - self.assertEqual(api, ["api", "repos/example/template", "--jq", ".allow_auto_merge"]) + self.assertIn("`Assets/Mark.txt`, `Docs/Guide.md`", create[11]) + self.assertEqual(self.gh_calls(["pr", "merge"]), []) self.assertIn("auto-merge is disabled for example/template", result.stdout) - bare = self.remotes / "example/template.git" published = self.git("rev-parse", f"refs/heads/{branch}", cwd=bare).strip() self.assertIn("gpgsig", self.git("cat-file", "commit", published, cwd=bare)) changed = self.git("diff", "--name-only", "master", published, cwd=bare).split() @@ -215,13 +249,68 @@ def test_publish_opens_one_signed_pull_request(self): def test_publish_requests_auto_merge_when_the_template_allows_it(self): self.publish(env={"AUTO_MERGE": "true"}) - merge = self.gh_calls()[2] + merge, = self.gh_calls(["pr", "merge"]) head = self.git("rev-parse", "HEAD", cwd=self.template).strip() self.assertEqual(merge, [ "pr", "merge", "https://github.com/example/template/pull/1", "--auto", "--squash", "--body", "", "--match-head-commit", head, ]) + def test_rerun_after_a_failed_push_completes_the_publication(self): + hook = self.remotes / "example/template.git/hooks/pre-receive" + hook.write_text("#!/bin/sh\nexit 1\n") + hook.chmod(0o755) + result = self.publish(expected=1) + self.assertIn("Run the same command again to resume the publication.", result.stderr) + self.assertEqual(self.gh_calls(["pr", "create"]), []) + hook.unlink() + result = self.publish() + self.assertIn("resuming chore/publish-", result.stdout) + branch, _ = self.published_branch() + create, = self.gh_calls(["pr", "create"]) + self.assertIn("`Assets/Mark.txt`, `Docs/Guide.md`", create[11]) + self.assertEqual(self.git("rev-parse", "--abbrev-ref", "HEAD", cwd=self.template).strip(), branch) + + def test_rerun_after_a_failed_pull_request_completes_the_publication(self): + self.publish(expected=1, env={"GH_FAIL": "create"}) + self.published_branch() + result = self.publish() + self.assertIn("resuming chore/publish-", result.stdout) + self.assertIn("https://github.com/example/template/pull/1", result.stdout) + self.assertEqual(len(self.gh_calls(["pr", "create"])), 2) + + def test_rerun_after_a_failed_auto_merge_request_completes_the_publication(self): + self.publish(expected=1, env={"AUTO_MERGE": "true", "GH_FAIL": "merge"}) + result = self.publish(env={"AUTO_MERGE": "true"}) + self.assertIn("auto-merge requested", result.stdout) + self.assertEqual(len(self.gh_calls(["pr", "create"])), 1) + self.assertEqual(len(self.gh_calls(["pr", "merge"])), 2) + + def test_published_branch_resumes_from_the_default_branch(self): + self.publish() + branch, _ = self.published_branch() + self.git("switch", "-q", "master", cwd=self.template) + self.git("branch", "-q", "-D", branch, cwd=self.template) + result = self.publish() + self.assertIn(f"resuming {branch}", result.stdout) + self.assertEqual(len(self.gh_calls(["pr", "create"])), 1) + + def test_branch_on_an_older_default_head_is_not_resumed(self): + self.publish(expected=1, env={"GH_FAIL": "create"}) + other = self.root / "other" + self.git("clone", "-q", "https://github.com/example/template.git", str(other), cwd=self.root) + self.commit(other, {"Keep.md": "newer\n"}) + result = self.publish(expected=1) + self.assertIn("does not build on origin's master head", result.stderr) + + def test_stale_template_fails_before_publishing(self): + other = self.root / "other" + self.git("clone", "-q", "https://github.com/example/template.git", str(other), cwd=self.root) + self.commit(other, {"Keep.md": "newer\n"}) + result = self.publish(expected=1) + self.assertIn("is neither origin's master head nor branch", result.stderr) + self.assertEqual(self.gh_calls(), []) + def test_undeclared_generated_file_fails_before_writing(self): self.declare(composition(generator("extra", {"Docs/Guide.md": "Guide.md"}))) result = self.publish("--write-only", expected=1) @@ -240,30 +329,27 @@ def test_dirty_template_fails_before_generating(self): self.assertIn("uncommitted changes", result.stderr) self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") - def test_stale_template_fails_before_publishing(self): - other = self.root / "other" - self.git("clone", "-q", "https://github.com/example/template.git", str(other), cwd=self.root) - self.commit(other, {"Keep.md": "newer\n"}) - result = self.publish(expected=1) - self.assertIn("is not origin's master head", result.stderr) - self.assertEqual(self.gh_calls(), []) - def test_template_origin_must_match_the_declaration(self): self.declare(composition(GUIDE, template="example/other")) result = self.publish("--write-only", expected=1) self.assertIn("is not github.com/example/other", result.stderr) - def test_origin_must_be_the_template_on_github(self): - self.git("remote", "set-url", "origin", "https://example.com/example/template.git", cwd=self.template) + def test_rewritten_origin_must_stay_on_github(self): + self.git("config", "url.https://example.invalid/mirror/example/template.insteadOf", + "https://github.com/example/template", cwd=self.template) result = self.publish("--write-only", expected=1) - self.assertIn("is not github.com/example/template", result.stderr) + self.assertIn("https://example.invalid/mirror/example/template.git, which is not github.com", + result.stderr) self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") - def test_origin_must_push_where_it_fetches(self): - self.git("remote", "set-url", "--push", "origin", "https://github.com/example/generators.git", + def test_every_push_url_must_be_the_template(self): + self.git("remote", "set-url", "--add", "--push", "origin", "https://github.com/example/template.git", + cwd=self.template) + self.git("remote", "set-url", "--add", "--push", "origin", "https://github.com/example/generators.git", cwd=self.template) result = self.publish("--write-only", expected=1) - self.assertIn("origin pushes to", result.stderr) + self.assertIn("git@github.com:example/generators.git, which is not github.com/example/template", + result.stderr) self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") def test_producer_without_release_tag_fails(self): @@ -279,34 +365,6 @@ def test_file_ancestor_fails_before_writing(self): self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") self.assertEqual((self.template / "Keep.md").read_text(), "kept\n") - def test_existing_publication_stops_before_writing(self): - self.publish() - self.git("switch", "-q", "master", cwd=self.template) - calls = len(self.gh_calls()) - result = self.publish(expected=1) - self.assertIn("already exists on origin", result.stderr) - self.assertIn("gh pr list -R example/template --head chore/publish-", result.stderr) - self.assertEqual((self.template / "Docs/Guide.md").read_text(), "old guide\n") - self.assertEqual(len(self.gh_calls()), calls) - - def test_failed_push_names_the_recovery(self): - hook = self.remotes / "example/template.git/hooks/pre-receive" - hook.write_text("#!/bin/sh\nexit 1\n") - hook.chmod(0o755) - result = self.publish(expected=1) - self.assertRegex(result.stderr, r"Push it with `git push origin chore/publish-[0-9a-f]{12}`") - self.assertIn("gh pr create -R example/template --base master", result.stderr) - self.assertEqual(self.gh_calls(), []) - - def test_failed_pull_request_names_the_recovery(self): - result = self.publish(expected=1, env={"GH_FAIL": "create"}) - self.assertIn("is on origin. Open the pull request with `gh pr create -R example/template", result.stderr) - - def test_failed_auto_merge_names_the_recovery(self): - result = self.publish(expected=1, env={"AUTO_MERGE": "true", "GH_FAIL": "merge"}) - self.assertIn("https://github.com/example/template/pull/1 is open. Request auto-merge with " - "`gh pr merge https://github.com/example/template/pull/1 --auto", result.stderr) - def test_symlinked_destination_fails_before_writing(self): (self.template / "Docs/Guide.md").unlink() (self.template / "Docs/Guide.md").symlink_to(self.root / "outside.md") @@ -324,8 +382,11 @@ def test_composition_must_be_well_formed(self): "git path": composition({**GUIDE, "files": {".git/config": "Guide.md"}}), "git path in another case": composition({**GUIDE, "files": {".GIT/config": "Guide.md"}}), "generated git path": composition({**GUIDE, "files": {"Guide.md": "Docs/.Git/x"}}), - "nested targets": composition(GUIDE, {**MARK, "files": {"Docs": "logo/mark.txt"}}), "duplicate target": composition(GUIDE, {**MARK, "files": {"Docs/Guide.md": "logo/mark.txt"}}), + "duplicate target in another case": composition( + GUIDE, {**MARK, "files": {"docs/guide.md": "logo/mark.txt"}}), + "nested targets": composition(GUIDE, {**MARK, "files": {"Docs": "logo/mark.txt"}}), + "nested targets in another case": composition(GUIDE, {**MARK, "files": {"docs": "logo/mark.txt"}}), "missing key": {"schema": 1, "template": "example/template"}, "extra key": composition({**GUIDE, "path": "x"}), "bad repository": composition({**GUIDE, "repository": "generators"}), From 65aec6ade3565fa89e22b532011eaabbd732567b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:38:28 +0800 Subject: [PATCH 4/5] refactor: start template publications over instead of resuming them A publishing run stops before writing when its publication branch exists. A failed push or pull request prints the git -C commands that delete the branch, after which the same command publishes again from the default branch head, so the script only ever pushes the commit it just created. A failed auto-merge request leaves the open pull request. --- README.md | 16 ++--- scripts/publish-template.py | 123 ++++++++++++++------------------- tests/test_publish_template.py | 78 ++++++++++----------- 3 files changed, 96 insertions(+), 121 deletions(-) diff --git a/README.md b/README.md index ca16d86..ac2facb 100644 --- a/README.md +++ b/README.md @@ -208,14 +208,14 @@ release, commit and changed files, and leaves the template checkout on that branch. When the template allows auto-merge, it requests a squash merge of the pushed head. `--write-only` writes the files without a commit or pull request. -A run that fails after committing asks for the same command again. The rerun -resumes the publication from the branch, in the template checkout or on origin, -when the branch builds on origin's current default branch head and holds the -current releases' output. It pushes the branch if needed, opens the pull request -if none is open and requests auto-merge if it is allowed and not yet requested. -Otherwise the template checkout must be at origin's default branch head. Runs -need `git`, `gh` authenticated to push to the template and open pull requests, -signing configured in the template checkout, and each generator's own tools. +A publishing run stops before writing anything if the publication branch +already exists, locally or on origin; otherwise the template checkout must be at +origin's default branch head. When a push or pull request fails after the commit, the +script prints `git -C` commands that delete the publication branch, after which +the same command publishes again; a failed auto-merge request leaves the open +pull request to merge after the required checks pass. Runs need `git`, `gh` +authenticated to push to the template and open pull requests, signing configured +in the template checkout, and each generator's own tools. No workflow calls the script: opening a pull request in another repository needs an App credential, so a maintainer runs it with their own credentials diff --git a/scripts/publish-template.py b/scripts/publish-template.py index 6f86d82..322b3f9 100755 --- a/scripts/publish-template.py +++ b/scripts/publish-template.py @@ -21,7 +21,6 @@ r"(?:https://github\.com/|ssh://git@github\.com/|git@github\.com:)" r"(?P[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?)(?:\.git)?/?" ) -RESUME = "Run the same command again to resume the publication." class PublishError(Exception): @@ -244,38 +243,28 @@ def publication_branch(declaration_commit, sources): return "chore/publish-" + digest[:12] -def prepare_checkout(template, branch): - """Return origin's default branch, its head, and whether the checkout holds an earlier publication commit.""" - base, base_commit = remote_default(template) - head = git("rev-parse", "HEAD", cwd=template).strip() - current = subprocess.run( - ["git", "symbolic-ref", "--quiet", "--short", "HEAD"], cwd=template, - capture_output=True, text=True, stdin=subprocess.DEVNULL, - ).stdout.strip() +def existing_branch(template, branch): + """Return whether the publication branch exists in the template checkout and on origin.""" local = subprocess.run( ["git", "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], cwd=template, - capture_output=True, text=True, stdin=subprocess.DEVNULL, - ).stdout.strip() - remote = git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=template).partition("\t")[0] - if current != branch: - if head != base_commit: - raise PublishError(f"{template}: HEAD {head} is neither origin's {base} head nor branch {branch}") - if not local and not remote: - return base, base_commit, False - if not local: - git("fetch", "--quiet", "origin", f"refs/heads/{branch}:refs/heads/{branch}", cwd=template) - git("switch", "--quiet", branch, cwd=template) - head = git("rev-parse", "HEAD", cwd=template).strip() - parents = git("rev-list", "--parents", "-n", "1", "HEAD", cwd=template).split()[1:] - if parents != [base_commit]: - raise PublishError( - f"branch {branch} does not build on origin's {base} head {base_commit}; " - "delete the branch locally and on origin to publish again" - ) - if remote and remote != head: - raise PublishError(f"branch {branch} on origin is {remote}, not the local commit {head}") - print(f"resuming {branch}") - return base, base_commit, True + capture_output=True, stdin=subprocess.DEVNULL, + ).returncode == 0 + remote = bool(git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=template).strip()) + return local, remote + + +def start_over(template, base, branch): + """Describe how to delete a publication branch so that the same command publishes again.""" + local, remote = existing_branch(template, branch) + checkout = shlex.quote(str(template)) + commands = [] + if local: + commands += [f"git -C {checkout} switch {shlex.quote(base)}", f"git -C {checkout} branch -D {branch}"] + if remote: + commands.append(f"git -C {checkout} push origin --delete {branch}") + return "Delete the publication branch, then run the same command again:\n" + "\n".join( + f" {command}" for command in commands + ) def pull_request_text(sources, declaration_commit, changed): @@ -295,26 +284,23 @@ def pull_request_text(sources, declaration_commit, changed): return title, body -def finish(template, repository, base, branch, title, body): +def pull_request(template, repository, base, branch, title, body): head = git("rev-parse", "HEAD", cwd=template).strip() try: - remote = git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=template).partition("\t")[0] - if remote != head: - git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=template) - url = gh("pr", "list", "-R", repository, "--head", branch, "--state", "open", - "--json", "url", "--jq", ".[0].url // empty").strip() - if not url: - url = gh("pr", "create", "-R", repository, "--base", base, "--head", branch, - "--title", title, "--body", body).strip() - print(url) - if gh("api", f"repos/{repository}", "--jq", ".allow_auto_merge").strip() != "true": - print(f"auto-merge is disabled for {repository}; merge after the required checks pass") - return - if gh("pr", "view", url, "--json", "autoMergeRequest", "--jq", ".autoMergeRequest != null").strip() != "true": - gh("pr", "merge", url, "--auto", "--squash", "--body", "", "--match-head-commit", head) - print("auto-merge requested") + git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=template) + url = gh("pr", "create", "-R", repository, "--base", base, "--head", branch, + "--title", title, "--body", body).strip() + except PublishError as error: + raise PublishError(f"{error}\n{start_over(template, base, branch)}") from error + print(url) + if gh("api", f"repos/{repository}", "--jq", ".allow_auto_merge").strip() != "true": + print(f"auto-merge is disabled for {repository}; merge after the required checks pass") + return + try: + gh("pr", "merge", url, "--auto", "--squash", "--body", "", "--match-head-commit", head) except PublishError as error: - raise PublishError(f"{error}\n{RESUME}") from error + raise PublishError(f"{error}\n{url} is open; merge it after the required checks pass") from error + print("auto-merge requested") def publish(declaration, template, *, write_only=False): @@ -331,10 +317,15 @@ def publish(declaration, template, *, write_only=False): sources = {name: latest_release(source_url(name)) for name in dict.fromkeys(g["repository"] for g in generators)} for name, (tag, commit) in sources.items(): print(f"{name} {tag} {commit}") - resuming = False if not write_only: branch = publication_branch(declaration_commit, sources) - base, base_commit, resuming = prepare_checkout(template, branch) + base, _ = remote_default(template) + if any(existing_branch(template, branch)): + raise PublishError( + f"branch {branch} already exists: these releases were published before. " + + start_over(template, base, branch) + ) + require_current(template) check_destinations(template, [target for generator in generators for target in generator["files"]]) with tempfile.TemporaryDirectory(prefix="publish-template-") as temporary: root = Path(temporary) @@ -350,25 +341,12 @@ def publish(declaration, template, *, write_only=False): }, output) outputs.append(output) pending = [differences(template, generator["files"], output) for generator, output in zip(generators, outputs)] - if resuming and any(pending): - raise PublishError( - f"branch {branch} differs from the current releases' output; " - "delete the branch locally and on origin to publish again" - ) for generator, output, targets in zip(generators, outputs, pending): write(template, generator["files"], output, targets) - if resuming: - changed = { - name: git("diff", "--name-only", base_commit, "HEAD", "--", - *[target for g in generators if g["repository"] == name for target in g["files"]], - cwd=template).split() - for name in sources - } - else: - changed = {name: [] for name in sources} - for generator, targets in zip(generators, pending): - changed[generator["repository"]] += targets - changed = {name: sorted(paths) for name, paths in changed.items()} + changed = {name: [] for name in sources} + for generator, targets in zip(generators, pending): + changed[generator["repository"]] += targets + changed = {name: sorted(paths) for name, paths in changed.items()} for name in sources: print(f"{name}: " + (", ".join(changed[name]) or "current")) if not any(changed.values()): @@ -377,12 +355,11 @@ def publish(declaration, template, *, write_only=False): if write_only: return 0 title, body = pull_request_text(sources, declaration_commit, changed) - if not resuming: - git("switch", "--quiet", "-c", branch, cwd=template) - git("add", "--", *[path for paths in changed.values() for path in paths], cwd=template) - git("commit", "--quiet", "-S", "-m", title, "-m", - "\n".join(f"{name} {tag} {commit}" for name, (tag, commit) in sources.items()), cwd=template) - finish(template, repository, base, branch, title, body) + git("switch", "--quiet", "-c", branch, cwd=template) + git("add", "--", *[path for paths in changed.values() for path in paths], cwd=template) + git("commit", "--quiet", "-S", "-m", title, "-m", + "\n".join(f"{name} {tag} {commit}" for name, (tag, commit) in sources.items()), cwd=template) + pull_request(template, repository, base, branch, title, body) return 0 diff --git a/tests/test_publish_template.py b/tests/test_publish_template.py index 080a966..79c9702 100644 --- a/tests/test_publish_template.py +++ b/tests/test_publish_template.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path +import shlex import subprocess import sys import tempfile @@ -63,19 +64,12 @@ def load_script(): with open(os.environ["GH_LOG"], "a") as log: log.write(json.dumps(arguments) + "\\n") state_path = Path(os.environ["GH_STATE"]) -state = json.loads(state_path.read_text()) if state_path.exists() else {"pulls": {}, "auto": []} +state = json.loads(state_path.read_text()) if state_path.exists() else {"pulls": 0} if arguments[0] == "pr" and os.environ.get("GH_FAIL") == arguments[1]: sys.exit("gh: request failed") -if arguments[:2] == ["pr", "list"]: - print(state["pulls"].get(arguments[arguments.index("--head") + 1], "")) -elif arguments[:2] == ["pr", "create"]: - url = f"https://github.com/example/template/pull/{len(state['pulls']) + 1}" - state["pulls"][arguments[arguments.index("--head") + 1]] = url - print(url) -elif arguments[:2] == ["pr", "view"]: - print("true" if arguments[2] in state["auto"] else "false") -elif arguments[:2] == ["pr", "merge"]: - state["auto"].append(arguments[2]) +if arguments[:2] == ["pr", "create"]: + state["pulls"] += 1 + print(f"https://github.com/example/template/pull/{state['pulls']}") elif arguments[0] == "api": print(os.environ.get("AUTO_MERGE", "false")) state_path.write_text(json.dumps(state)) @@ -256,59 +250,63 @@ def test_publish_requests_auto_merge_when_the_template_allows_it(self): "--body", "", "--match-head-commit", head, ]) - def test_rerun_after_a_failed_push_completes_the_publication(self): + def start_over(self, stderr): + commands = [line.strip() for line in stderr.splitlines() if line.startswith(" git -C ")] + self.assertTrue(commands, stderr) + for command in commands: + subprocess.run(shlex.split(command), cwd=self.root / "elsewhere", env=self.env, check=True, + capture_output=True) + return commands + + def test_failed_push_is_published_again_after_starting_over(self): hook = self.remotes / "example/template.git/hooks/pre-receive" hook.write_text("#!/bin/sh\nexit 1\n") hook.chmod(0o755) result = self.publish(expected=1) - self.assertIn("Run the same command again to resume the publication.", result.stderr) - self.assertEqual(self.gh_calls(["pr", "create"]), []) + self.assertIn("Delete the publication branch, then run the same command again:", result.stderr) + commands = self.start_over(result.stderr) + self.assertEqual(len(commands), 2, commands) hook.unlink() - result = self.publish() - self.assertIn("resuming chore/publish-", result.stdout) + self.publish() branch, _ = self.published_branch() create, = self.gh_calls(["pr", "create"]) self.assertIn("`Assets/Mark.txt`, `Docs/Guide.md`", create[11]) self.assertEqual(self.git("rev-parse", "--abbrev-ref", "HEAD", cwd=self.template).strip(), branch) - def test_rerun_after_a_failed_pull_request_completes_the_publication(self): - self.publish(expected=1, env={"GH_FAIL": "create"}) + def test_failed_pull_request_is_published_again_after_starting_over(self): + result = self.publish(expected=1, env={"GH_FAIL": "create"}) + commands = self.start_over(result.stderr) + self.assertIn("push origin --delete chore/publish-", commands[-1]) + self.publish() self.published_branch() - result = self.publish() - self.assertIn("resuming chore/publish-", result.stdout) - self.assertIn("https://github.com/example/template/pull/1", result.stdout) self.assertEqual(len(self.gh_calls(["pr", "create"])), 2) - def test_rerun_after_a_failed_auto_merge_request_completes_the_publication(self): - self.publish(expected=1, env={"AUTO_MERGE": "true", "GH_FAIL": "merge"}) - result = self.publish(env={"AUTO_MERGE": "true"}) - self.assertIn("auto-merge requested", result.stdout) + def test_failed_auto_merge_request_leaves_the_open_pull_request(self): + result = self.publish(expected=1, env={"AUTO_MERGE": "true", "GH_FAIL": "merge"}) + self.assertIn("https://github.com/example/template/pull/1 is open; merge it after the required checks pass", + result.stderr) self.assertEqual(len(self.gh_calls(["pr", "create"])), 1) - self.assertEqual(len(self.gh_calls(["pr", "merge"])), 2) - def test_published_branch_resumes_from_the_default_branch(self): + def test_published_releases_stop_before_writing(self): self.publish() branch, _ = self.published_branch() - self.git("switch", "-q", "master", cwd=self.template) - self.git("branch", "-q", "-D", branch, cwd=self.template) - result = self.publish() - self.assertIn(f"resuming {branch}", result.stdout) - self.assertEqual(len(self.gh_calls(["pr", "create"])), 1) - - def test_branch_on_an_older_default_head_is_not_resumed(self): - self.publish(expected=1, env={"GH_FAIL": "create"}) - other = self.root / "other" - self.git("clone", "-q", "https://github.com/example/template.git", str(other), cwd=self.root) - self.commit(other, {"Keep.md": "newer\n"}) + guide = (self.template / "Docs/Guide.md").read_text() + calls = len(self.gh_calls()) result = self.publish(expected=1) - self.assertIn("does not build on origin's master head", result.stderr) + self.assertIn(f"branch {branch} already exists", result.stderr) + self.assertEqual((self.template / "Docs/Guide.md").read_text(), guide) + self.assertEqual(len(self.gh_calls()), calls) + self.start_over(result.stderr) + self.assertEqual(self.git("rev-parse", "--abbrev-ref", "HEAD", cwd=self.template).strip(), "master") + self.publish() + self.assertEqual(len(self.gh_calls(["pr", "create"])), 2) def test_stale_template_fails_before_publishing(self): other = self.root / "other" self.git("clone", "-q", "https://github.com/example/template.git", str(other), cwd=self.root) self.commit(other, {"Keep.md": "newer\n"}) result = self.publish(expected=1) - self.assertIn("is neither origin's master head nor branch", result.stderr) + self.assertIn("is not origin's master head", result.stderr) self.assertEqual(self.gh_calls(), []) def test_undeclared_generated_file_fails_before_writing(self): From 4faabed907de721b3fb201647aaf4dcb38f7aa47 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:44:36 +0800 Subject: [PATCH 5/5] fix: print template recovery commands without contacting origin The recovery after a failed push or pull request is built from where the failure happened instead of another ls-remote, so an outage that fails the push still prints the original error and the commands that delete the publication branch. --- scripts/publish-template.py | 13 ++++++++----- tests/test_publish_template.py | 13 +++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/scripts/publish-template.py b/scripts/publish-template.py index 322b3f9..cd6888f 100755 --- a/scripts/publish-template.py +++ b/scripts/publish-template.py @@ -253,9 +253,8 @@ def existing_branch(template, branch): return local, remote -def start_over(template, base, branch): +def start_over(template, base, branch, *, local, remote): """Describe how to delete a publication branch so that the same command publishes again.""" - local, remote = existing_branch(template, branch) checkout = shlex.quote(str(template)) commands = [] if local: @@ -288,10 +287,13 @@ def pull_request(template, repository, base, branch, title, body): head = git("rev-parse", "HEAD", cwd=template).strip() try: git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=template) + except PublishError as error: + raise PublishError(f"{error}\n{start_over(template, base, branch, local=True, remote=False)}") from error + try: url = gh("pr", "create", "-R", repository, "--base", base, "--head", branch, "--title", title, "--body", body).strip() except PublishError as error: - raise PublishError(f"{error}\n{start_over(template, base, branch)}") from error + raise PublishError(f"{error}\n{start_over(template, base, branch, local=True, remote=True)}") from error print(url) if gh("api", f"repos/{repository}", "--jq", ".allow_auto_merge").strip() != "true": print(f"auto-merge is disabled for {repository}; merge after the required checks pass") @@ -320,10 +322,11 @@ def publish(declaration, template, *, write_only=False): if not write_only: branch = publication_branch(declaration_commit, sources) base, _ = remote_default(template) - if any(existing_branch(template, branch)): + local, remote = existing_branch(template, branch) + if local or remote: raise PublishError( f"branch {branch} already exists: these releases were published before. " - + start_over(template, base, branch) + + start_over(template, base, branch, local=local, remote=remote) ) require_current(template) check_destinations(template, [target for generator in generators for target in generator["files"]]) diff --git a/tests/test_publish_template.py b/tests/test_publish_template.py index 79c9702..536dfd2 100644 --- a/tests/test_publish_template.py +++ b/tests/test_publish_template.py @@ -51,6 +51,11 @@ def load_script(): program, path = shlex.split(sys.argv[-1]) service = program.removeprefix("git-") +# Once a push is attempted, the network stays down for the rest of the run. +outage = os.environ.get("OUTAGE_FROM_PUSH") +if outage and (service == "receive-pack" or os.path.exists(outage)): + open(outage, "w").close() + sys.exit("ssh: connect to host github.com: Network is unreachable") sys.exit(subprocess.call(["git", service, os.path.join(os.environ["FAKE_GITHUB"], path)])) """ @@ -273,6 +278,14 @@ def test_failed_push_is_published_again_after_starting_over(self): self.assertIn("`Assets/Mark.txt`, `Docs/Guide.md`", create[11]) self.assertEqual(self.git("rev-parse", "--abbrev-ref", "HEAD", cwd=self.template).strip(), branch) + def test_network_outage_after_commit_still_prints_the_recovery(self): + result = self.publish(expected=1, env={"OUTAGE_FROM_PUSH": str(self.root / "outage")}) + self.assertIn("Network is unreachable", result.stderr) + self.assertIn("Delete the publication branch, then run the same command again:", result.stderr) + self.assertEqual(len(self.start_over(result.stderr)), 2) + self.publish() + self.published_branch() + def test_failed_pull_request_is_published_again_after_starting_over(self): result = self.publish(expected=1, env={"GH_FAIL": "create"}) commands = self.start_over(result.stderr)