890 lines
47 KiB
Python
890 lines
47 KiB
Python
import datetime
|
|
import io
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from deploy_release import ci_script, cut, patch, trace
|
|
from failure import Failure
|
|
from test_env import isolated_env
|
|
|
|
TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release"
|
|
|
|
|
|
class DeployRelease(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temp = pathlib.Path(tempfile.mkdtemp())
|
|
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
|
self.origin = self.temp / "origin.git"
|
|
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
|
|
self.source = self.temp / "source"
|
|
self.git(self.temp, "clone", "-q", str(self.origin), str(self.source))
|
|
self.release("0.1.0", "- First.\n", '{"theme": "dark"}\n')
|
|
self.target = self.temp / "dot-claude"
|
|
self.git(self.temp, "clone", "-q", str(self.origin), str(self.target))
|
|
self.git(self.target, "checkout", "-q", "--detach", "v0.1.0")
|
|
|
|
def git(self, cwd: pathlib.Path, *args: str) -> str:
|
|
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=cwd, env=isolated_env(), text=True).stdout
|
|
|
|
def release(self, version: str, entry: str, settings: str) -> None:
|
|
"""Commit a CHANGELOG.md whose newest section is version's, holding entry, and settings.json, then tag it and push both."""
|
|
changelog = self.source / "CHANGELOG.md"
|
|
earlier = changelog.read_text().removeprefix("# Changelog\n\n") if changelog.exists() else ""
|
|
changelog.write_text(f"# Changelog\n\n## {version}\n\n{entry}\n{earlier}")
|
|
(self.source / "settings.json").write_text(settings)
|
|
self.git(self.source, "add", "-A")
|
|
self.git(self.source, "commit", "-q", "-m", f"Cut release {version}")
|
|
self.git(self.source, "tag", f"v{version}")
|
|
self.git(self.source, "push", "-q", "origin", "main", "--tags")
|
|
|
|
def deploy(self) -> subprocess.CompletedProcess[str]:
|
|
return subprocess.run([sys.executable, str(TOOL), str(self.target)], capture_output=True, env=isolated_env(), text=True)
|
|
|
|
def head(self) -> str:
|
|
return self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip()
|
|
|
|
def test_moves_the_checkout_to_the_newest_tag_and_prints_each_newer_versions_changelog(self):
|
|
self.release("0.2.0", "- Second.\n", '{"theme": "dark"}\n')
|
|
self.release("0.3.0", "- Third: run `make thing` once.\n", '{"theme": "dark"}\n')
|
|
(self.source / "CHANGELOG.md").write_text("# Changelog\n\n## Unreleased\n\n- Later.\n\n" + (self.source / "CHANGELOG.md").read_text().removeprefix("# Changelog\n\n"))
|
|
self.git(self.source, "commit", "-q", "-am", "Later work")
|
|
self.git(self.source, "push", "-q", "origin", "main")
|
|
ran = self.deploy()
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.head(), "v0.3.0")
|
|
self.assertIn("Moved from v0.1.0 to v0.3.0.", ran.stdout)
|
|
self.assertIn("## 0.3.0\n\n- Third: run `make thing` once.", ran.stdout)
|
|
self.assertIn("## 0.2.0\n\n- Second.", ran.stdout)
|
|
self.assertNotIn("First.", ran.stdout)
|
|
self.assertNotIn("Later.", ran.stdout)
|
|
self.assertNotIn("/model", ran.stdout)
|
|
|
|
def test_stops_with_gits_error_where_the_index_cannot_be_refreshed(self):
|
|
self.release("0.2.0", "- Second.\n", '{"theme": "dark"}\n')
|
|
(self.target / ".git" / "index").write_bytes(b"DIRC")
|
|
ran = self.deploy()
|
|
self.assertNotEqual(ran.returncode, 0)
|
|
self.assertIn("index", ran.stderr)
|
|
self.assertNotIn("uncommitted", ran.stderr)
|
|
self.assertEqual(self.git(self.target, "rev-parse", "HEAD"), self.git(self.source, "rev-parse", "v0.1.0^{commit}"))
|
|
|
|
def test_says_so_where_the_checkout_is_on_the_newest_tag_already(self):
|
|
ran = self.deploy()
|
|
self.assertEqual((ran.returncode, ran.stdout), (0, "Already on v0.1.0, the newest release.\n"))
|
|
|
|
def test_refuses_an_uncommitted_change_to_a_tracked_file_and_leaves_the_checkout_as_it_was(self):
|
|
self.release("0.2.0", "- Second.\n", '{"theme": "dark"}\n')
|
|
(self.target / "CHANGELOG.md").write_text("Edited here.\n")
|
|
(self.target / "projects").mkdir()
|
|
(self.target / "projects" / "session.jsonl").write_text("{}\n")
|
|
ran = self.deploy()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("CHANGELOG.md", ran.stderr)
|
|
self.assertNotIn("projects", ran.stderr, "an untracked file is Claude Code's own state, not a change")
|
|
self.assertEqual(self.head(), "v0.1.0")
|
|
|
|
def test_takes_an_uncommitted_change_the_new_release_holds_as_no_change(self):
|
|
(self.target / "settings.json").write_text('{"theme": "light"}\n')
|
|
self.release("0.2.0", "- Second.\n", '{"theme": "light"}\n')
|
|
ran = self.deploy()
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.head(), "v0.2.0")
|
|
|
|
def test_refuses_to_move_a_checkout_back_from_commits_no_release_holds(self):
|
|
self.git(self.target, "switch", "-q", "main")
|
|
(self.source / "new.md").write_text("Unreleased.\n")
|
|
self.git(self.source, "add", "-A")
|
|
self.git(self.source, "commit", "-q", "-m", "Unreleased work")
|
|
self.git(self.source, "push", "-q", "origin", "main")
|
|
self.git(self.target, "pull", "-q", "--ff-only")
|
|
ran = self.deploy()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("v0.1.0 doesn't hold", ran.stderr)
|
|
self.assertEqual(self.git(self.target, "branch", "--show-current").strip(), "main")
|
|
|
|
def test_takes_a_model_picked_with_the_clean_filter_set_as_no_change(self):
|
|
self.release("0.2.0", "- Second.\n", '{\n "theme": "dark"\n}\n')
|
|
self.git(self.target, "fetch", "-q", "--tags", "origin")
|
|
self.git(self.target, "checkout", "-q", "--detach", "v0.2.0")
|
|
(self.target / ".gitattributes").write_text("/settings.json filter=settings\n")
|
|
self.git(self.target, "config", "filter.settings.clean", f"{sys.executable} {TOOL.parent / 'settings_filter.py'}")
|
|
(self.target / "settings.json").write_text('{"model": "claude-opus-5-5", "theme": "dark"}\n')
|
|
self.release("0.3.0", "- Third.\n", '{\n "theme": "dark"\n}\n')
|
|
ran = self.deploy()
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.head(), "v0.3.0")
|
|
self.assertIn('"model"', (self.target / "settings.json").read_text(), "a release that leaves settings.json as it was keeps the pick")
|
|
|
|
def test_moves_a_settings_json_that_differs_only_by_a_model_pick_and_key_order_where_the_release_changes_it(self):
|
|
self.release("0.2.0", "- Second.\n", '{\n "permissions": {},\n "theme": "dark"\n}\n')
|
|
self.git(self.target, "fetch", "-q", "--tags", "origin")
|
|
self.git(self.target, "checkout", "-q", "--detach", "v0.2.0")
|
|
(self.target / ".gitattributes").write_text("/settings.json filter=settings\n")
|
|
self.git(self.target, "config", "filter.settings.clean", f"{sys.executable} {TOOL.parent / 'settings_filter.py'}")
|
|
(self.target / "settings.json").write_text('{\n "theme": "dark",\n "model": "opus",\n "permissions": {}\n}\n')
|
|
self.release("0.3.0", "- Third.\n", '{\n "permissions": {},\n "theme": "light"\n}\n')
|
|
ran = self.deploy()
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.head(), "v0.3.0")
|
|
self.assertEqual((self.target / "settings.json").read_text(), '{\n "permissions": {},\n "theme": "light"\n}\n')
|
|
self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout)
|
|
|
|
def test_asks_for_the_model_again_where_the_release_changes_settings_json(self):
|
|
self.release("0.2.0", "- Second.\n", '{"theme": "light"}\n')
|
|
ran = self.deploy()
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout)
|
|
|
|
|
|
TODO = """# todo
|
|
|
|
## Scoring
|
|
|
|
`Score = 100 * V / (2**S + 8)`
|
|
|
|
`Bar = 0.1`
|
|
|
|
`Next ID = 3`
|
|
|
|
## Items
|
|
|
|
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
|
|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
"""
|
|
ROW = "| {id} | {release} | | | **Do thing {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
|
|
# A fake forge, run as tea or as gh. It keeps origin's pull requests in <temp>/forge.json. Its merge moves origin's main only by fast-forward.
|
|
FAKE_FORGE = """#!PYTHON
|
|
import json, pathlib, subprocess, sys
|
|
forge, args = pathlib.Path(sys.argv[0]).name, sys.argv[1:]
|
|
state_file = pathlib.Path(__file__).resolve().parent.parent / "forge.json"
|
|
state = json.loads(state_file.read_text())
|
|
state["calls"].append([forge, *args])
|
|
def save():
|
|
state_file.write_text(json.dumps(state))
|
|
def git(*words):
|
|
return subprocess.run(["git", "--git-dir", state["origin"], *words], capture_output=True, text=True)
|
|
def pull(number):
|
|
return next(found for found in state["pulls"] if str(found["number"]) == number)
|
|
# A fork's head as given; origin's own pull request follows its branch, as a forge does.
|
|
def sha(found):
|
|
return found.get("sha") or git("rev-parse", "refs/heads/" + found["head"]).stdout.strip()
|
|
def merge(number, guard):
|
|
head = sha(pull(number))
|
|
if state.get("refuse_merge"):
|
|
save()
|
|
sys.exit("Not possible to fast-forward")
|
|
if head != guard:
|
|
save()
|
|
sys.exit("head commit changed")
|
|
if git("merge-base", "--is-ancestor", "refs/heads/main", head).returncode:
|
|
save()
|
|
sys.exit("Not possible to fast-forward")
|
|
git("update-ref", "refs/heads/main", head)
|
|
pull(number)["state"] = "merged"
|
|
opened = [found for found in state["pulls"] if found["state"] == "open"]
|
|
if forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]:
|
|
repo = lambda found: {"full_name": "fork/r" if found["fork"] else "o/r"}
|
|
print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "label": found["head"], "sha": sha(found), "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened]))
|
|
elif forge == "gh" and args[:3] == ["pr", "list", "--head"] and args[4:6] == ["--json", "number,headRefOid,isCrossRepository"]:
|
|
for found in opened:
|
|
if found["head"] == args[3]:
|
|
print(f"{found['number']}\t{sha(found)}\t{str(found['fork']).lower()}")
|
|
elif args[:2] in (["pulls", "create"], ["pr", "create"]):
|
|
head = args[args.index("--head") + 1]
|
|
if any(found["head"] == head and not found["fork"] for found in opened):
|
|
save()
|
|
sys.exit("pull request already exists for these targets")
|
|
state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "fork": False, "state": "open"})
|
|
elif forge == "tea" and args == ["api", "repos/{owner}/{repo}/branches/main"]:
|
|
print(json.dumps(state.get("branch", {"name": "main"})))
|
|
elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"):
|
|
checks = state["checks"]
|
|
print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1, "statuses": [] if checks == "none" else [{"context": "CI / tests (pull_request)", "status": checks}]}))
|
|
elif forge == "gh" and args[:2] == ["pr", "checks"]:
|
|
if state["checks"] == "none":
|
|
save()
|
|
sys.exit("no checks reported on the 'release' branch")
|
|
if state["checks"] == "failure":
|
|
save()
|
|
sys.exit("lint\tfail")
|
|
elif forge == "tea" and args[:5] == ["api", "--method", "POST", "--field", "Do=fast-forward-only"] and args[5] == "--field" and args[7].endswith("/merge"):
|
|
try:
|
|
merge(args[7].split("/")[-2], args[6].removeprefix("head_commit_id="))
|
|
except SystemExit as refused:
|
|
# Gitea answers an error with a message, and tea api exits 0 all the same.
|
|
print(json.dumps({"message": str(refused)}))
|
|
elif args[:2] == ["pr", "merge"] and args[3:5] == ["--rebase", "--match-head-commit"]:
|
|
merge(args[2], args[5])
|
|
else:
|
|
save()
|
|
sys.exit("unexpected call")
|
|
save()
|
|
""".replace("PYTHON", sys.executable)
|
|
|
|
|
|
# The protection of main that requires CI's check.
|
|
REQUIRED = '{"name": "main", "enable_status_check": true, "status_check_contexts": ["CI / tests (pull_request)"]}'
|
|
|
|
|
|
class Cut(unittest.TestCase):
|
|
"""A development clone whose next release, 0.2.0, holds no item, has its release review landed and one change unreleased; and a ~/.claude on v0.1.0."""
|
|
|
|
def setUp(self):
|
|
self.temp = pathlib.Path(os.path.realpath(tempfile.mkdtemp()))
|
|
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
|
self.origin = self.temp / "origin.git"
|
|
fake = self.temp / "fake-bin"
|
|
fake.mkdir()
|
|
for name in ("tea", "gh"):
|
|
(fake / name).write_text(FAKE_FORGE)
|
|
(fake / name).chmod(0o755)
|
|
(self.temp / "gitconfig").write_text("[user]\n\tname = t\n\temail = t@t\n")
|
|
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}", "XDG_STATE_HOME": str(self.temp / "state")}
|
|
self.forge_state({"origin": str(self.origin), "pulls": [], "checks": "none", "calls": []})
|
|
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
|
|
self.clone = self.temp / "claude-config"
|
|
self.git(self.temp, "clone", "-q", str(self.origin), str(self.clone))
|
|
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0"), "tool.txt": "broken\n", "ci.sh": "exit 0\n"}, "Start")
|
|
self.git(self.clone, "tag", "-a", "v0.1.0", "-m", "Cut release 0.1.0")
|
|
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0")}, "Ship item 1")
|
|
self.git(self.clone, "commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
|
|
self.git(self.clone, "push", "-q", "origin", "main", "--tags")
|
|
self.target = self.temp / "dot-claude"
|
|
self.git(self.temp, "clone", "-q", str(self.origin), str(self.target))
|
|
self.git(self.target, "checkout", "-q", "--detach", "v0.1.0")
|
|
|
|
def git(self, cwd: pathlib.Path, *args: str) -> str:
|
|
return subprocess.run(["git", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout
|
|
|
|
def commit(self, files: dict[str, str], title: str) -> None:
|
|
for name, text in files.items():
|
|
(self.clone / name).write_text(text)
|
|
self.git(self.clone, "add", "-A")
|
|
self.git(self.clone, "commit", "-q", "-m", title)
|
|
|
|
def forge_state(self, state: dict | None = None) -> dict:
|
|
if state is not None:
|
|
(self.temp / "forge.json").write_text(json.dumps(state))
|
|
return json.loads((self.temp / "forge.json").read_text())
|
|
|
|
def set_checks(self, checks: str) -> None:
|
|
self.forge_state({**self.forge_state(), "checks": checks})
|
|
|
|
def cut(self) -> subprocess.CompletedProcess[str]:
|
|
return subprocess.run([sys.executable, str(TOOL), "--cut", str(self.target)], capture_output=True, cwd=self.clone, env=self.env, text=True)
|
|
|
|
def origin_git(self, *args: str) -> str:
|
|
return self.git(self.temp, "--git-dir", str(self.origin), *args)
|
|
|
|
def assert_cut(self, ran: subprocess.CompletedProcess[str]) -> None:
|
|
"""origin's main ends in the cut commit, tagged v0.2.0, and ~/.claude is on that tag."""
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Cut release 0.2.0")
|
|
changelog = self.origin_git("show", "main:CHANGELOG.md")
|
|
self.assertIn("## 0.2.0\n\n- Second.", changelog)
|
|
self.assertNotIn("Unreleased", changelog)
|
|
self.assertEqual(self.origin_git("rev-parse", "v0.2.0^{commit}"), self.origin_git("rev-parse", "main"))
|
|
self.assertEqual(self.origin_git("cat-file", "-t", "v0.2.0").strip(), "tag", "the tag is annotated")
|
|
self.assertEqual(self.origin_git("tag", "-l", "--format=%(contents:subject)", "v0.2.0").strip(), "Cut release 0.2.0")
|
|
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.2.0")
|
|
|
|
def test_cuts_the_next_release_through_a_tea_pull_request_merged_fast_forward_then_tags_and_deploys_it(self):
|
|
head = self.git(self.clone, "rev-parse", "HEAD")
|
|
ran = self.cut()
|
|
self.assert_cut(ran)
|
|
self.assertIn("v0.2.0", ran.stdout)
|
|
calls = self.forge_state()["calls"]
|
|
self.assertIn(["tea", "pulls", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
|
|
self.assertIn("Do=fast-forward-only", [word for call in calls if call[-1].endswith("/pulls/1/merge") for word in call])
|
|
self.assertEqual(self.git(self.clone, "rev-parse", "HEAD"), head, "the clone's own checkout stays where it was")
|
|
self.assertEqual(self.git(self.clone, "status", "--porcelain"), "")
|
|
|
|
def test_cuts_through_gh_on_a_github_origin(self):
|
|
self.use_github()
|
|
ran = self.cut()
|
|
self.assert_cut(ran)
|
|
calls = self.forge_state()["calls"]
|
|
self.assertIn(["gh", "pr", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
|
|
self.assertIn(["gh", "pr", "merge", "1", "--rebase"], [call[:5] for call in calls])
|
|
|
|
def test_refuses_changing_nothing_while_the_next_release_holds_an_item(self):
|
|
self.commit({"todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Plan item 1 again")
|
|
self.git(self.clone, "push", "-q", "origin", "main")
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("0.2.0", ran.stderr)
|
|
self.assertEqual(self.forge_state()["pulls"], [])
|
|
self.assertEqual(self.origin_git("branch", "--list", "release-*"), "")
|
|
|
|
def test_refuses_changing_nothing_until_the_release_review_has_landed(self):
|
|
self.git(self.clone, "reset", "-q", "--hard", "HEAD~1")
|
|
self.git(self.clone, "push", "-q", "--force", "origin", "main")
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("release review", ran.stderr)
|
|
self.assertEqual(self.forge_state()["pulls"], [])
|
|
|
|
def test_stops_on_a_failing_check_leaving_the_pull_request_and_a_rerun_continues_it(self):
|
|
self.set_checks("failure")
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("failure", ran.stderr)
|
|
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"])
|
|
self.assertNotEqual(self.origin_git("branch", "--list", "release-0.2.0"), "")
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.2.0"), "")
|
|
self.set_checks("success")
|
|
self.assert_cut(self.cut())
|
|
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request")
|
|
|
|
def test_stops_with_the_forges_reason_where_it_refuses_the_merge(self):
|
|
self.forge_state({**self.forge_state(), "refuse_merge": True})
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("Not possible to fast-forward", ran.stderr)
|
|
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"])
|
|
|
|
def test_a_rerun_rebuilds_the_cut_commit_on_main_where_main_moved_past_the_branch(self):
|
|
self.set_checks("failure")
|
|
self.cut()
|
|
self.commit({"other.md": "Later.\n"}, "Fix the check")
|
|
self.git(self.clone, "push", "-q", "origin", "main")
|
|
self.set_checks("success")
|
|
self.assert_cut(self.cut())
|
|
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main~1").strip(), "Fix the check")
|
|
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request")
|
|
|
|
def test_deletes_the_tag_it_made_where_its_push_fails_so_a_rerun_tags_again(self):
|
|
hook = self.origin / "hooks" / "pre-receive"
|
|
hook.write_text("#!/bin/sh\nif grep -q refs/tags/; then echo 'tags are refused' >&2; exit 1; fi\n")
|
|
hook.chmod(0o755)
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("tags are refused", ran.stderr)
|
|
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0"), "")
|
|
hook.unlink()
|
|
self.assert_cut(self.cut())
|
|
|
|
def test_refuses_changing_nothing_where_the_clone_is_not_a_clone_of_the_checkouts_origin(self):
|
|
self.git(self.target, "remote", "set-url", "origin", str(self.temp / "other.git"))
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("origin", ran.stderr)
|
|
self.assertEqual(self.forge_state()["pulls"], [])
|
|
|
|
def test_says_as_each_step_finishes_and_ends_saying_the_release_is_cut_and_the_checkout_on_it(self):
|
|
self.forge_state({**self.forge_state(), "checks": "success", "branch": json.loads(REQUIRED)})
|
|
ran = self.cut()
|
|
self.assert_cut(ran)
|
|
merged = self.origin_git("rev-parse", "main").strip()
|
|
# Each step's line, in order, with the facts it must name.
|
|
steps = [("pushed", "release-0.2.0"), ("opened", "1"), ("waiting", "1", "CI / tests (pull_request)"), ("passed", "1"), ("merged", "1"), ("tagged", merged[:12], "v0.2.0"), ("pushed", "v0.2.0"), ("deleted", "release-0.2.0")]
|
|
lines = ran.stderr.splitlines()
|
|
self.assertEqual(len(lines), len(steps), ran.stderr)
|
|
for line, facts in zip(lines, steps):
|
|
self.assertTrue(line.startswith("deploy-release: "), line)
|
|
for fact in facts:
|
|
self.assertIn(fact, line)
|
|
self.assertEqual(ran.stdout.splitlines()[-1], f"Done: v0.2.0 is cut and pushed, and {self.target} is on it.")
|
|
|
|
def test_deletes_the_merged_release_branch_on_origin(self):
|
|
self.assert_cut(self.cut())
|
|
self.assertEqual(self.origin_git("branch", "--list", "release-0.2.0"), "")
|
|
|
|
def test_only_warns_where_deleting_the_release_branch_fails(self):
|
|
hook = self.origin / "hooks" / "pre-receive"
|
|
hook.write_text("#!/bin/sh\nif grep -q '^[^ ]* 0000000000000000000000000000000000000000 refs/heads/'; then echo 'deletes are refused' >&2; exit 1; fi\n")
|
|
hook.chmod(0o755)
|
|
ran = self.cut()
|
|
self.assert_cut(ran)
|
|
self.assertIn("deploy-release: warning: the branch release-0.2.0 stays on origin:", ran.stderr)
|
|
self.assertIn("deletes are refused", ran.stderr)
|
|
self.assertEqual(ran.stdout.splitlines()[-1], f"Done: v0.2.0 is cut and pushed, and {self.target} is on it.")
|
|
|
|
def test_stops_where_the_tag_exists_on_another_commit_and_a_rerun_tags_the_merged_commit(self):
|
|
self.git(self.clone, "switch", "-q", "-c", "side")
|
|
self.commit({"side.md": "Side.\n"}, "Side")
|
|
self.git(self.clone, "tag", "-a", "v0.2.0", "-m", "Wrong")
|
|
self.git(self.clone, "push", "-q", "origin", "side", "v0.2.0")
|
|
self.git(self.clone, "switch", "-q", "main")
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("v0.2.0", ran.stderr)
|
|
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Cut release 0.2.0")
|
|
self.git(self.clone, "tag", "-d", "v0.2.0")
|
|
self.origin_git("tag", "-d", "v0.2.0")
|
|
self.assert_cut(self.cut())
|
|
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun finds the merged commit, so it opens no second pull request")
|
|
|
|
def use_github(self) -> None:
|
|
"""Point the clone's origin at a GitHub URL that git reads as the local origin, so the cut runs gh."""
|
|
self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git")
|
|
self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git")
|
|
|
|
def assert_fork_pull_ignored(self) -> None:
|
|
"""After a failed first run, a fork opens a pull request from its own release-0.2.0, listed first; the rerun merges only origin's."""
|
|
self.set_checks("failure")
|
|
self.cut()
|
|
self.git(self.clone, "switch", "-q", "-c", "fork", "origin/release-0.2.0")
|
|
self.commit({"settings.json": "{}\n"}, "Cut release 0.2.0")
|
|
self.git(self.clone, "push", "-q", "origin", "fork:refs/forks/release-0.2.0")
|
|
self.git(self.clone, "switch", "-q", "main")
|
|
state = self.forge_state()
|
|
fork = {"number": 9, "head": "release-0.2.0", "sha": self.git(self.clone, "rev-parse", "fork").strip(), "fork": True, "state": "open"}
|
|
self.forge_state({**state, "pulls": [fork, *state["pulls"]], "checks": "success"})
|
|
self.assert_cut(self.cut())
|
|
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open", "merged"])
|
|
self.assertNotIn("settings.json", self.origin_git("ls-tree", "--name-only", "main"))
|
|
|
|
def test_merges_only_origins_own_pull_request_on_tea_where_a_fork_opened_one_from_a_branch_of_the_same_name(self):
|
|
self.assert_fork_pull_ignored()
|
|
|
|
def test_merges_only_origins_own_pull_request_on_gh_where_a_fork_opened_one_from_a_branch_of_the_same_name(self):
|
|
self.use_github()
|
|
self.assert_fork_pull_ignored()
|
|
|
|
def test_a_rerun_drops_a_cut_tag_an_earlier_run_made_but_never_pushed(self):
|
|
self.set_checks("failure")
|
|
self.cut()
|
|
self.set_checks("success")
|
|
hook = self.origin / "hooks" / "pre-receive"
|
|
hook.write_text("#!/bin/sh\nif grep -q refs/tags/; then exit 1; fi\n")
|
|
hook.chmod(0o755)
|
|
self.cut()
|
|
# A run that died between tagging and pushing left this tag behind.
|
|
self.git(self.clone, "fetch", "-q", "origin")
|
|
self.git(self.clone, "tag", "-a", "v0.2.0", "-m", "Cut release 0.2.0", "origin/main")
|
|
hook.unlink()
|
|
self.assert_cut(self.cut())
|
|
|
|
def test_keeps_a_pushed_cut_tag_and_an_unpushed_tag_on_any_other_commit(self):
|
|
self.git(self.clone, "switch", "-q", "-c", "side")
|
|
self.commit({"side.md": "Side.\n"}, "Side")
|
|
self.git(self.clone, "tag", "-a", "v9.9.9", "-m", "Mine")
|
|
self.git(self.clone, "switch", "-q", "main")
|
|
self.assert_cut(self.cut())
|
|
self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses")
|
|
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"])
|
|
|
|
def traces(self) -> list[str]:
|
|
"""The text of each run's trace, oldest first."""
|
|
return [file.read_text() for file in sorted((self.temp / "state" / "deploy-release").glob("*.log")) if not file.name.endswith("-ci.log")]
|
|
|
|
def test_keeps_each_step_of_a_cut_with_its_time_in_a_file_of_the_run(self):
|
|
self.assert_cut(self.cut())
|
|
[kept] = self.traces()
|
|
lines = kept.splitlines()
|
|
self.assertRegex(lines[0], rf"^[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}T[0-9:]{{8}}\S* deploy-release --cut {self.target} in {self.clone}$")
|
|
self.assertRegex(kept, r"(?m)^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}\S* pushed the tag v0\.2\.0$")
|
|
self.assertIn("Done: v0.2.0 is cut and pushed", lines[-1])
|
|
|
|
def test_keeps_the_reason_a_cut_stopped_in_its_trace_and_a_rerun_writes_its_own(self):
|
|
self.assert_cut(self.cut())
|
|
self.assertEqual(self.cut().returncode, 1)
|
|
first, second = self.traces()
|
|
self.assertTrue(second.endswith(" release 0.3.0 still holds items in todo.md\n"), second)
|
|
self.assertNotIn("still holds items", first)
|
|
|
|
def test_reads_whether_the_next_releases_review_landed_beside_the_release(self):
|
|
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 2, 0), reviewed=True))
|
|
self.plan_patch()
|
|
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 1, 1), reviewed=False))
|
|
|
|
def test_refuses_before_any_change_where_mains_changelog_has_no_unreleased_heading(self):
|
|
ran = self.cut_patch(self.plan_patch({"CHANGELOG.md": "# Changelog\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}))
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("CHANGELOG.md on origin/main has no ## Unreleased section", ran.stderr)
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
|
|
def test_says_where_ci_shs_output_goes_and_keeps_it_there(self):
|
|
ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite ran\nexit 0\n"}))
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
[log] = (self.temp / "state" / "deploy-release").glob("*-ci.log")
|
|
self.assertEqual(log.read_text(), "the suite ran\n")
|
|
self.assertIn(f"ci.sh's output goes to {log}", ran.stderr)
|
|
|
|
def plan_patch(self, fix: dict[str, str] | None = None) -> str:
|
|
"""On top of setUp's main: a feature no patch may ship, item 3 filed under 0.1.1, then the commit that fixes tool.txt and finishes item 3, pushed. The revision range that names only the fix."""
|
|
self.commit({"feature.txt": "new\n"}, "Add a feature")
|
|
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=3, release="0.1.1")}, "File item 3")
|
|
base = self.git(self.clone, "rev-parse", "HEAD").strip()
|
|
self.commit({"tool.txt": "fixed\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0"), "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n", **(fix or {})}, "Fix item 3")
|
|
head = self.git(self.clone, "rev-parse", "HEAD").strip()
|
|
self.git(self.clone, "push", "-q", "origin", "main")
|
|
return f"{base}..{head}"
|
|
|
|
def cut_patch(self, *commits: str) -> subprocess.CompletedProcess[str]:
|
|
return subprocess.run([sys.executable, str(TOOL), "--cut-patch", *commits, str(self.target)], capture_output=True, cwd=self.clone, env=self.env, text=True)
|
|
|
|
def test_cuts_a_patch_of_the_newest_tag_holding_only_the_named_commits_then_merges_the_tag_back_and_deploys_it(self):
|
|
ran = self.cut_patch(self.plan_patch())
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.origin_git("cat-file", "-t", "v0.1.1").strip(), "tag", "the tag is annotated")
|
|
self.assertEqual(self.origin_git("tag", "-l", "--format=%(contents:subject)", "v0.1.1").strip(), "Cut release 0.1.1")
|
|
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "v0.1.1").strip(), "Cut release 0.1.1")
|
|
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}~1"), self.origin_git("rev-parse", "v0.1.0^{commit}"))
|
|
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
|
|
self.assertEqual(self.origin_git("show", "v0.1.1:CHANGELOG.md"), "# Changelog\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
|
|
self.assertEqual(self.origin_git("show", "v0.1.1:todo.md"), self.origin_git("show", "v0.1.0:todo.md"))
|
|
self.assertNotIn("feature.txt", self.origin_git("ls-tree", "--name-only", "v0.1.1"))
|
|
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
|
|
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Merge release 0.1.1 into main")
|
|
self.assertEqual(self.origin_git("show", "main:CHANGELOG.md"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
|
|
self.assertEqual(self.origin_git("show", "main:feature.txt"), "new\n")
|
|
self.assertIn(["tea", "pulls", "create", "--head", "release-0.1.1", "--base", "main"], [call[:7] for call in self.forge_state()["calls"]])
|
|
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.1.1")
|
|
self.assertIn("Done: v0.1.1 is cut and pushed", ran.stdout)
|
|
|
|
def test_takes_one_commit_as_the_patch(self):
|
|
head = self.plan_patch().split("..")[1]
|
|
ran = self.cut_patch(head)
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
|
|
|
|
def test_refuses_before_any_change_where_the_plan_names_no_patch_release(self):
|
|
self.commit({"tool.txt": "fixed\n", "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Fix tool.txt")
|
|
self.git(self.clone, "push", "-q", "origin", "main")
|
|
ran = self.cut_patch("HEAD")
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("0.1.1", ran.stderr)
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
self.assertEqual(self.forge_state()["pulls"], [])
|
|
|
|
def test_refuses_before_any_change_while_the_patch_release_holds_an_item(self):
|
|
self.plan_patch()
|
|
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=4, release="0.1.1")}, "File item 4")
|
|
self.git(self.clone, "push", "-q", "origin", "main")
|
|
ran = self.cut_patch("HEAD~1")
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("still holds items", ran.stderr)
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
|
|
def test_skips_the_release_review_a_patch_would_otherwise_wait_for(self):
|
|
self.git(self.clone, "reset", "-q", "--hard", "HEAD~1")
|
|
self.git(self.clone, "push", "-q", "--force", "origin", "main")
|
|
ran = self.cut_patch(self.plan_patch())
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
|
|
def test_refuses_a_commit_the_tag_holds(self):
|
|
self.plan_patch()
|
|
ran = self.cut_patch("v0.1.0")
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn(self.git(self.clone, "rev-parse", "v0.1.0^{commit}")[:12] + " is in v0.1.0 already", ran.stderr)
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
|
|
def test_refuses_a_commit_origins_main_doesnt_hold(self):
|
|
self.plan_patch()
|
|
self.commit({"tool.txt": "local\n"}, "Unpushed")
|
|
ran = self.cut_patch("HEAD")
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn(self.git(self.clone, "rev-parse", "HEAD")[:12] + " isn't on origin/main", ran.stderr)
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
|
|
def test_leaves_out_the_commits_a_merge_of_main_brought_into_the_chunk(self):
|
|
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=3, release="0.1.1")}, "File item 3")
|
|
base = self.git(self.clone, "rev-parse", "HEAD").strip()
|
|
self.commit({"feature.txt": "new\n"}, "Add a feature")
|
|
self.git(self.clone, "switch", "-q", "-c", "chunk", base)
|
|
self.git(self.clone, "merge", "-q", "--no-ff", "-m", "Sync with main", "main")
|
|
self.commit({"tool.txt": "fixed\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0"), "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Fix item 3")
|
|
head = self.git(self.clone, "rev-parse", "HEAD").strip()
|
|
self.git(self.clone, "switch", "-q", "main")
|
|
self.git(self.clone, "merge", "-q", "--ff-only", "chunk")
|
|
self.git(self.clone, "push", "-q", "origin", "main")
|
|
ran = self.cut_patch(f"{base}..{head}")
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertNotIn("feature.txt", self.origin_git("ls-tree", "--name-only", "v0.1.1"))
|
|
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
|
|
|
|
def test_says_which_commits_the_patch_ships_before_it_applies_them(self):
|
|
ran = self.cut_patch(self.plan_patch())
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertIn("deploy-release: ships " + self.git(self.clone, "log", "-1", "--format=%h %s", "HEAD").strip(), ran.stderr)
|
|
self.assertNotIn("Add a feature", ran.stderr)
|
|
|
|
def test_refuses_on_a_github_origin_whose_merge_would_drop_the_tag_from_main(self):
|
|
commits = self.plan_patch()
|
|
self.use_github()
|
|
ran = self.cut_patch(commits)
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("GitHub", ran.stderr)
|
|
self.assertEqual(self.forge_state()["calls"], [])
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
|
|
def test_a_rerun_merges_back_and_deploys_a_patch_cut_by_hand_as_the_refusal_says(self):
|
|
self.commit({"tool.txt": "half fixed\n"}, "Change tool.txt on main")
|
|
commits = self.plan_patch()
|
|
refused = self.cut_patch(commits)
|
|
self.assertEqual(refused.returncode, 1)
|
|
self.assertIn("exactly these lines:\n- Fixed.", refused.stderr)
|
|
self.git(self.clone, "switch", "-q", "--detach", "v0.1.0")
|
|
self.commit({"tool.txt": "fixed\n", "CHANGELOG.md": "# Changelog\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Cut release 0.1.1")
|
|
self.git(self.clone, "tag", "-a", "v0.1.1", "-m", "Cut release 0.1.1")
|
|
self.git(self.clone, "push", "-q", "origin", "v0.1.1")
|
|
self.git(self.clone, "switch", "-q", "main")
|
|
tagged = self.origin_git("rev-parse", "v0.1.1^{commit}")
|
|
ran = self.cut_patch(commits)
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}"), tagged)
|
|
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
|
|
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.1.1")
|
|
|
|
def test_a_rerun_refuses_a_pushed_tag_cut_from_other_commits(self):
|
|
self.set_checks("failure")
|
|
commits = self.plan_patch()
|
|
self.assertEqual(self.cut_patch(commits).returncode, 1)
|
|
self.commit({"tool.txt": "fixed twice\n", "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n- Fixed twice.\n\n## 0.1.0\n\n- First.\n"}, "Fix item 3 again")
|
|
self.git(self.clone, "push", "-q", "origin", "main")
|
|
self.set_checks("success")
|
|
ran = self.cut_patch("HEAD")
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("The tag lists:\n- Fixed.\nThe commits added:\n- Fixed twice.", ran.stderr)
|
|
self.assertNotIn("Fixed twice", self.origin_git("show", "main:CHANGELOG.md").split("## 0.1.0")[0].split("## Unreleased")[0])
|
|
|
|
def test_refuses_commits_that_add_no_changelog_entry_under_unreleased(self):
|
|
self.plan_patch()
|
|
self.commit({"tool.txt": "fixed again\n"}, "Fix more")
|
|
self.git(self.clone, "push", "-q", "origin", "main")
|
|
ran = self.cut_patch("HEAD")
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("## Unreleased", ran.stderr)
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
|
|
def test_stops_before_tagging_where_ci_fails_on_the_patch(self):
|
|
ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite failed >&2\nexit 1\n"}))
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("ci.sh", ran.stderr)
|
|
self.assertIn("the suite failed", ran.stderr)
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.1.1"), "")
|
|
self.assertEqual(self.forge_state()["pulls"], [])
|
|
|
|
def test_stops_naming_the_commit_that_does_not_apply_on_the_tag(self):
|
|
self.commit({"tool.txt": "half fixed\n"}, "Change tool.txt on main")
|
|
ran = self.cut_patch(self.plan_patch())
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("Fix item 3", ran.stderr)
|
|
self.assertIn("v0.1.0", ran.stderr)
|
|
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
|
|
|
def test_a_rerun_after_a_failed_merge_back_check_keeps_the_pushed_tag_and_merges_back(self):
|
|
self.set_checks("failure")
|
|
commits = self.plan_patch()
|
|
ran = self.cut_patch(commits)
|
|
self.assertEqual(ran.returncode, 1)
|
|
tagged = self.origin_git("rev-parse", "v0.1.1^{commit}")
|
|
self.set_checks("success")
|
|
ran = self.cut_patch(commits)
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}"), tagged)
|
|
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
|
|
|
|
def test_plain_cut_refuses_a_patch_release_and_names_cut_patch(self):
|
|
self.plan_patch()
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("--cut-patch", ran.stderr)
|
|
self.assertEqual(self.forge_state()["pulls"], [])
|
|
|
|
def test_cut_patch_needs_its_commits(self):
|
|
ran = subprocess.run([sys.executable, str(TOOL), "--cut-patch"], capture_output=True, cwd=self.clone, env=self.env, text=True)
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("usage", ran.stderr)
|
|
self.assertEqual(self.forge_state()["calls"], [])
|
|
|
|
def test_refuses_an_option_it_does_not_know(self):
|
|
ran = subprocess.run([sys.executable, str(TOOL), "--cut", "--force"], capture_output=True, cwd=self.clone, env=self.env, text=True)
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("usage", ran.stderr)
|
|
self.assertEqual(self.forge_state()["calls"], [])
|
|
|
|
def test_stops_where_origins_open_pull_request_has_another_head_than_the_branch(self):
|
|
self.set_checks("failure")
|
|
self.cut()
|
|
state = self.forge_state()
|
|
state["pulls"][0]["sha"] = "0" * 40
|
|
self.forge_state({**state, "checks": "success"})
|
|
ran = self.cut()
|
|
self.assertEqual(ran.returncode, 1)
|
|
self.assertIn("already exists", ran.stderr)
|
|
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0")
|
|
|
|
|
|
|
|
def still_runs(pid: int) -> bool:
|
|
"""Whether the process pid runs: one that ended and that nobody has waited for yet doesn't."""
|
|
try:
|
|
return pathlib.Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z"
|
|
except OSError:
|
|
return False
|
|
|
|
|
|
class PatchCi(unittest.TestCase):
|
|
"""The patch's ci.sh run, read in-process with the runner handed in, and the runner itself on a real ci.sh."""
|
|
|
|
def setUp(self):
|
|
self.worktree = pathlib.Path(tempfile.mkdtemp())
|
|
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.worktree)])
|
|
self.log = self.worktree / "ci.log"
|
|
self.said: list[str] = []
|
|
|
|
def test_passes_where_ci_sh_exits_zero(self):
|
|
(self.worktree / "ci.sh").write_text("exit 0\n")
|
|
seen: list[pathlib.Path] = []
|
|
self.assertIsNone(patch.run_ci(self.worktree, "origin/main", lambda worktree: seen.append(worktree) or patch.CiRan(0, "fine\n")))
|
|
self.assertEqual(seen, [self.worktree])
|
|
|
|
def test_a_failed_ci_sh_gives_the_last_30_lines_of_its_output(self):
|
|
(self.worktree / "ci.sh").write_text("exit 1\n")
|
|
failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: patch.CiRan(1, "".join(f"line {number}\n" for number in range(1, 41))))
|
|
self.assertIsInstance(failed, Failure)
|
|
self.assertIn("ci.sh failed on the patch, so nothing is tagged. Fix it on origin/main", failed.reason)
|
|
self.assertTrue(failed.reason.endswith("\nline 11\n" + "\n".join(f"line {number}" for number in range(12, 41))), failed.reason)
|
|
self.assertNotIn("line 10\n", failed.reason)
|
|
|
|
def test_a_ci_sh_that_could_not_run_or_was_stopped_tags_nothing_and_gives_the_runners_reason(self):
|
|
(self.worktree / "ci.sh").write_text("exit 0\n")
|
|
failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: Failure("ci.sh still ran after 30 minutes and was stopped"))
|
|
self.assertEqual(failed, Failure("ci.sh still ran after 30 minutes and was stopped, so nothing is tagged. Rerun once that is fixed."))
|
|
|
|
def test_refuses_a_patch_without_ci_sh_before_running_anything(self):
|
|
self.assertEqual(patch.run_ci(self.worktree, "origin/main", lambda worktree: self.fail("ran")), Failure("the patch holds no ci.sh to test it with"))
|
|
|
|
def test_the_runner_writes_ci_shs_output_to_the_log_as_it_runs_and_gives_its_exit_code(self):
|
|
(self.worktree / "ci.sh").write_text("echo out\necho err >&2\nexit 3\n")
|
|
ran = ci_script.ci_runner(self.log, 30, self.said.append)(self.worktree)
|
|
self.assertEqual(ran, patch.CiRan(3, "out\nerr\n"))
|
|
self.assertEqual(self.log.read_text(), "out\nerr\n")
|
|
self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after 30 seconds"])
|
|
|
|
def test_the_runner_stops_a_ci_sh_that_hangs_with_what_it_started_and_says_so(self):
|
|
(self.worktree / "ci.sh").write_text("echo started\nsleep 60 &\necho $! >child.pid\nwait\n")
|
|
began = time.monotonic()
|
|
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, grace=0.2)(self.worktree)
|
|
self.assertLess(time.monotonic() - began, 20)
|
|
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
|
|
self.assertEqual(self.log.read_text(), "started\n")
|
|
child = int((self.worktree / "child.pid").read_text())
|
|
deadline = time.monotonic() + 5
|
|
while still_runs(child) and time.monotonic() < deadline:
|
|
time.sleep(0.05)
|
|
self.assertFalse(still_runs(child), "the process ci.sh started still runs")
|
|
|
|
def test_the_runner_gives_a_failure_where_ci_sh_cannot_start(self):
|
|
ran = ci_script.ci_runner(self.log, 30, self.said.append)(self.worktree / "gone")
|
|
self.assertIsInstance(ran, Failure)
|
|
self.assertIn("ci.sh could not run: ", ran.reason)
|
|
self.assertIn(str(self.worktree / "gone"), ran.reason)
|
|
|
|
def test_the_runner_gives_a_failure_where_the_log_cannot_be_written(self):
|
|
(self.worktree / "ci.sh").write_text("exit 0\n")
|
|
ran = ci_script.ci_runner(self.worktree / "no-folder" / "ci.log", 30, self.said.append)(self.worktree)
|
|
self.assertIsInstance(ran, Failure)
|
|
self.assertIn(str(self.worktree / "no-folder" / "ci.log"), ran.reason)
|
|
|
|
|
|
class Trace(unittest.TestCase):
|
|
"""What a cut says, in-process, with the clock and stderr handed in."""
|
|
|
|
def setUp(self):
|
|
self.temp = pathlib.Path(tempfile.mkdtemp())
|
|
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
|
self.now = lambda: datetime.datetime(2026, 11, 27, 9, 30, 5)
|
|
|
|
def test_keeps_traces_under_the_state_folder_xdg_names_else_under_homes(self):
|
|
self.assertEqual(trace.trace_folder({"XDG_STATE_HOME": "/x/state"}, pathlib.Path("/home/u")), pathlib.Path("/x/state/deploy-release"))
|
|
self.assertEqual(trace.trace_folder({}, pathlib.Path("/home/u")), pathlib.Path("/home/u/.local/state/deploy-release"))
|
|
|
|
def test_names_a_run_by_its_start_and_its_process(self):
|
|
self.assertEqual(trace.run_name(self.now(), 4711), "2026-11-27T09-30-05-4711")
|
|
|
|
def test_starts_a_trace_with_the_command_then_appends_each_step_with_its_time_and_says_it(self):
|
|
file = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now)
|
|
self.assertEqual(file, self.temp / "state" / "deploy-release" / "run.log")
|
|
out = io.StringIO()
|
|
say = trace.saying(file, self.now, out)
|
|
say("pushed the tag v0.2.0")
|
|
say("merged pull request 3")
|
|
self.assertEqual(out.getvalue(), "deploy-release: pushed the tag v0.2.0\ndeploy-release: merged pull request 3\n")
|
|
self.assertEqual(file.read_text(), "2026-11-27T09:30:05 deploy-release --cut\n2026-11-27T09:30:05 pushed the tag v0.2.0\n2026-11-27T09:30:05 merged pull request 3\n")
|
|
|
|
def test_a_trace_that_cannot_be_started_is_a_failure_naming_the_file(self):
|
|
(self.temp / "state").write_text("a file where the folder goes\n")
|
|
made = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now)
|
|
self.assertIsInstance(made, Failure)
|
|
self.assertIn(str(self.temp / "state" / "deploy-release" / "run.log"), made.reason)
|
|
|
|
def test_still_says_each_step_where_there_is_no_trace_or_it_cannot_be_written(self):
|
|
out = io.StringIO()
|
|
trace.saying(None, self.now, out)("pushed the tag v0.2.0")
|
|
trace.saying(self.temp / "gone" / "run.log", self.now, out)("merged pull request 3")
|
|
self.assertEqual(out.getvalue().splitlines()[:2], ["deploy-release: pushed the tag v0.2.0", "deploy-release: merged pull request 3"])
|
|
self.assertIn(f"warning: the trace {self.temp / 'gone' / 'run.log'} could not be written", out.getvalue().splitlines()[2])
|
|
|
|
|
|
class Rewritten(unittest.TestCase):
|
|
"""A cut's file edits, where the filesystem refuses one."""
|
|
|
|
def setUp(self):
|
|
self.temp = pathlib.Path(tempfile.mkdtemp())
|
|
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
|
|
|
def test_replaces_a_files_text_and_hands_none_for_a_file_that_is_not_there(self):
|
|
file = self.temp / "CHANGELOG.md"
|
|
self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", lambda text: f"{text!r} new\n"))
|
|
self.assertEqual(file.read_text(), "None new\n")
|
|
self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", lambda text: text.upper()))
|
|
self.assertEqual(file.read_text(), "NONE NEW\n")
|
|
|
|
def test_a_file_that_cannot_be_read_or_written_is_a_failure_naming_the_step_and_the_file(self):
|
|
folder = self.temp / "CHANGELOG.md"
|
|
folder.mkdir()
|
|
# A folder can't be read as a file, and a file in a folder that isn't there can't be written.
|
|
for file in (folder, self.temp / "gone" / "commit.patch"):
|
|
with self.subTest(file=file):
|
|
failed = cut.rewritten(file, "head CHANGELOG.md with ## 0.1.1, so nothing is tagged", lambda text: "new\n")
|
|
self.assertIsInstance(failed, Failure)
|
|
self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md with ## 0.1.1, so nothing is tagged: "), failed.reason)
|
|
self.assertIn(str(file), failed.reason)
|
|
|
|
def test_gives_the_rewrites_own_failure_and_leaves_the_file(self):
|
|
file = self.temp / "CHANGELOG.md"
|
|
file.write_text("old\n")
|
|
self.assertEqual(cut.rewritten(file, "x", lambda text: Failure("no heading")), Failure("no heading"))
|
|
self.assertEqual(file.read_text(), "old\n")
|
|
|
|
|
|
class PatchChangelog(unittest.TestCase):
|
|
"""The changelog edits of a patch cut, read in-process, so a mutation tester reaches them."""
|
|
|
|
def test_heads_the_tags_changelog_with_the_patchs_section(self):
|
|
self.assertEqual(patch.headed("# Changelog\n\n## 0.1.0\n\n- First.\n", ["- Fixed.", "- Also."], "0.1.1"), "# Changelog\n\n## 0.1.1\n\n- Fixed.\n- Also.\n\n## 0.1.0\n\n- First.\n")
|
|
|
|
def test_appends_the_patchs_section_to_a_changelog_without_sections(self):
|
|
self.assertEqual(patch.headed("# Changelog\n\nFor Linux and macOS X\n\n", ["- Fixed."], "0.1.1"), "# Changelog\n\nFor Linux and macOS X\n\n## 0.1.1\n\n- Fixed.\n")
|
|
|
|
def test_moves_the_patchs_entries_from_unreleased_to_a_section_after_it(self):
|
|
changelog = "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"
|
|
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
|
|
|
|
def test_leaves_an_older_section_entry_that_reads_the_same(self):
|
|
changelog = "# Changelog\n\n## Unreleased\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n"
|
|
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n")
|
|
|
|
def test_puts_the_section_last_where_unreleased_is_the_last_section(self):
|
|
self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n")
|
|
|
|
def test_a_changelog_without_an_unreleased_heading_is_a_failure_that_names_it(self):
|
|
self.assertEqual(patch.moved_entries("# Changelog\n\n## 0.1.0\n\n- First.\n", ["- Fixed."], "0.1.1"), Failure("CHANGELOG.md has no ## Unreleased heading to move the entries of 0.1.1 from"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|