diff --git a/README.md b/README.md index 73fd4bc..ac2facb 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,52 @@ 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. 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 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 +after each producer release. + ## Pins and implementation revision Pin reusable workflows by full commit SHA; add a version comment at the family @@ -231,8 +277,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..cd6888f --- /dev/null +++ b/scripts/publish-template.py @@ -0,0 +1,389 @@ +#!/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"}) +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): + 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) + # 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 + + +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") + # 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"}: + 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.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 {targets[parent.as_posix()]!r}" + ) + + +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 gh(*arguments): + return run(["gh", *arguments]) + + +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") + 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(): + raise PublishError(f"{destination}: must be a regular file") + + +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 + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes((output / files[target]).read_bytes()) + + +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}") + + +def require_origin(checkout, repository): + """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 uses {url}, which is not github.com/{repository}") + + +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 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, 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, *, local, remote): + """Describe how to delete a publication branch so that the same command publishes again.""" + 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): + 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") + + " |" + 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" + ) + return title, body + + +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, 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") + 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; merge it after the required checks pass") from error + print("auto-merge requested") + + +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) + declaration_commit = git("rev-parse", "HEAD", cwd=declaration).strip() + # 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}") + if not write_only: + branch = publication_branch(declaration_commit, sources) + base, _ = remote_default(template) + 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, local=local, remote=remote) + ) + 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) + 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): + output = root / f"output-{index}" + output.mkdir() + generate(generator, checkouts[generator["repository"]], { + "template": template.resolve(), "output": output, "declaration": declaration.resolve(), + }, output) + outputs.append(output) + pending = [differences(template, generator["files"], output) for generator, output in zip(generators, outputs)] + for generator, output, targets in zip(generators, outputs, pending): + write(template, generator["files"], output, targets) + 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()): + print(f"{repository} is current") + return 0 + if write_only: + return 0 + title, body = pull_request_text(sources, declaration_commit, changed) + 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 + + +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, OSError) 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..536dfd2 --- /dev/null +++ b/tests/test_publish_template.py @@ -0,0 +1,421 @@ +import importlib.machinery +import importlib.util +import json +import os +from pathlib import Path +import shlex +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") +""" + +# 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-") +# 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)])) +""" + +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(arguments) + "\\n") +state_path = Path(os.environ["GH_STATE"]) +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", "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)) +""" + + +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" + '[url "git@github.com:"]\n\tinsteadOf = https://github.com/\n' + ) + bin_directory = self.root / "bin" + bin_directory.mkdir() + 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", "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"}) + 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): + 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], + 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, command=None): + if not self.gh_log.exists(): + return [] + 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): + 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("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(), []) + + 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() + 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.assertIn("| example/generators | v0.10.0 |", create[11]) + 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) + 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(["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 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("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() + 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_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) + self.assertIn("push origin --delete chore/publish-", commands[-1]) + self.publish() + self.published_branch() + self.assertEqual(len(self.gh_calls(["pr", "create"])), 2) + + 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) + + def test_published_releases_stop_before_writing(self): + self.publish() + branch, _ = self.published_branch() + guide = (self.template / "Docs/Guide.md").read_text() + calls = len(self.gh_calls()) + result = self.publish(expected=1) + 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 not origin's master head", 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) + 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_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_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("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_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("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): + 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_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_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"}}), + "git path in another case": composition({**GUIDE, "files": {".GIT/config": "Guide.md"}}), + "generated git path": composition({**GUIDE, "files": {"Guide.md": "Docs/.Git/x"}}), + "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"}), + "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()