Answer stability round 1: 1 🔴, 5 🟡 (0 misread); hold a pull request's base on the forge to the recorded one, ask origin for the epic branch, and name where a chunk's work landed
CI / tests (pull_request) Successful in 3m46s

This commit is contained in:
Lilleman
2026-11-20 21:42:32 +01:00
parent 525f3f8836
commit d464f271bf
13 changed files with 352 additions and 74 deletions
+30 -11
View File
@@ -8,13 +8,35 @@ from git_cli.git_repo import Git, git
def levelled(branch: str, default: str, cwd: str | None = None, timeout: float | None = None, run: Git = git, again: bool = True) -> str | Failure:
"""Brings origin's branch level with default, the default branch's ref, such as `origin/main`, and fetches it: what it did, as a sentence. Where origin has no such branch, it makes one at default.
It merges with a merge commit, never a rebase, since several chunks share the branch, and without a checkout, since no worktree has the branch checked out. A Failure where the two don't merge cleanly: a person resolves that, never the loop. A call to origin still running after timeout seconds fails. Where the merge's push fails, as when another chunk pushed its own merge first, it fetches and levels once more, unless again is False."""
fetched = run("fetch", "--quiet", "origin", cwd=cwd, timeout=timeout)
if isinstance(fetched, Failure):
return fetched
A call to origin still running after timeout seconds fails. again is False in the second try `merged` makes after a push that failed."""
held = fetched(cwd, timeout, run) or on_origin(branch, cwd, timeout, run)
if isinstance(held, Failure):
return held
if not held:
return pushed(default, branch, cwd, timeout, run) or f"Made origin/{branch} off {default}."
return merged(branch, default, cwd, timeout, run, again)
def fetched(cwd: str | None, timeout: float | None, run: Git) -> Failure | None:
"""Fetches origin, and once more where that fails: chunks that start at once fetch into one checkout, and git fails the fetch that finds a ref another one just moved."""
fetch = ("fetch", "--quiet", "origin")
if not isinstance(run(*fetch, cwd=cwd, timeout=timeout), Failure):
return None
second = run(*fetch, cwd=cwd, timeout=timeout)
return second if isinstance(second, Failure) else None
def on_origin(branch: str, cwd: str | None, timeout: float | None, run: Git) -> bool | Failure:
"""Whether origin has branch, asked of origin itself: a fetch keeps this checkout's `origin/<branch>` after origin deleted the branch."""
listed = run("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=cwd, timeout=timeout)
return listed if isinstance(listed, Failure) else bool(listed.strip())
def merged(branch: str, default: str, cwd: str | None, timeout: float | None, run: Git, again: bool) -> str | Failure:
"""Merges default into origin's branch, as this checkout fetched it, and pushes the merge: what it did, as a sentence.
It merges with a merge commit, never a rebase, since several chunks share the branch, and without a checkout, since no worktree has the branch checked out. A Failure where the two don't merge cleanly: a person resolves that, never the loop. Where the push fails, as when another chunk pushed its own merge first, it levels the branch once more from a fresh fetch, unless again is False."""
ours = f"origin/{branch}"
if isinstance(run("rev-parse", "--quiet", "--verify", f"refs/remotes/{ours}", cwd=cwd), Failure):
return pushed(default, branch, cwd, timeout, run) or f"Made {ours} off {default}."
behind = run("rev-list", "--count", f"{ours}..{default}", cwd=cwd)
if isinstance(behind, Failure):
return behind
@@ -47,8 +69,5 @@ def unmerged(failed: Failure, branch: str, default: str) -> Failure:
def pushed(commit: str, branch: str, cwd: str | None, timeout: float | None, run: Git) -> Failure | None:
"""Pushes commit as origin's branch, without force, so a push that raced another's fails, and fetches it."""
for args in (["push", "--quiet", "origin", f"{commit}:refs/heads/{branch}"], ["fetch", "--quiet", "origin"]):
done = run(*args, cwd=cwd, timeout=timeout)
if isinstance(done, Failure):
return done
return None
done = run("push", "--quiet", "origin", f"{commit}:refs/heads/{branch}", cwd=cwd, timeout=timeout)
return done if isinstance(done, Failure) else fetched(cwd, timeout, run)
+45 -7
View File
@@ -16,16 +16,22 @@ def sh(cwd: pathlib.Path, *args: str) -> str:
return subprocess.run(["git", "-c", "user.name=T", "-c", "user.email=t@example.com", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
def scripted(calls: list[tuple[str, ...]], **answers: str | Failure) -> git_repo.Git:
"""A git that records each command in calls and answers it by its first word: as answers has it, else as a checkout where origin/ABC-1 lacks a commit of origin/main that merges in cleanly."""
answered = {"fetch": "", "rev-parse": "abc\n", "rev-list": "1\n", "merge-tree": "7ree\n", "commit-tree": "c0mm17\n", "push": ""} | {name.replace("_", "-"): answer for name, answer in answers.items()}
def scripted(calls: list[tuple[str, ...]], **answers: str | Failure | list[str | Failure]) -> git_repo.Git:
"""A git that records each command in calls and answers it by its first word: as answers has it, else as a checkout where origin/ABC-1 lacks a commit of origin/main that merges in cleanly. A list answers one call with each entry, in order, and every later call with its last."""
answered = {"fetch": "", "ls-remote": "abc\trefs/heads/ABC-1\n", "rev-list": "1\n", "merge-tree": "7ree\n", "commit-tree": "c0mm17\n", "push": ""} | {name.replace("_", "-"): answer for name, answer in answers.items()}
def run(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
calls.append(args)
return answered[args[0]]
answer = answered[args[0]]
if not isinstance(answer, list):
return answer
return answer.pop(0) if len(answer) > 1 else answer[0]
return run
LOCKED = Failure("git fetch --quiet origin: error: cannot lock ref 'refs/remotes/origin/main': is at 2222 but expected 1111")
class Levelled(unittest.TestCase):
def setUp(self) -> None:
folder = tempfile.TemporaryDirectory()
@@ -53,6 +59,25 @@ class Levelled(unittest.TestCase):
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), sh(self.origin, "rev-parse", "main"))
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "main"), "fetched, so a worktree can branch off it")
def test_makes_a_fresh_branch_off_the_default_branch_where_origin_deleted_the_one_this_checkout_still_tracks(self) -> None:
self.commit("ABC-1", "b.txt", "epic\n")
self.commit("main", "b.txt", "epic\n")
sh(self.origin, "branch", "--quiet", "-D", "ABC-1")
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "Made origin/ABC-1 off origin/main.")
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), sh(self.origin, "rev-parse", "main"), "not the commits the deleted branch held")
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "main"))
def test_asks_origin_for_exactly_the_branch(self) -> None:
calls: list[tuple[str, ...]] = []
levelled("ABC-1", "origin/main", run=scripted(calls))
self.assertEqual(calls[1], ("ls-remote", "--heads", "origin", "refs/heads/ABC-1"))
def test_an_origin_that_cannot_say_whether_it_has_the_branch_fails_with_gits_reason(self) -> None:
calls: list[tuple[str, ...]] = []
unreachable = Failure("git ls-remote --heads origin refs/heads/ABC-1: fatal: unable to access origin")
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted(calls, ls_remote=unreachable)), unreachable)
self.assertEqual([args[0] for args in calls], ["fetch", "ls-remote"], "makes no branch on an origin it could not ask")
def test_leaves_a_branch_that_holds_the_default_branch(self) -> None:
self.commit("ABC-1", "b.txt", "epic\n")
before = sh(self.origin, "rev-parse", "ABC-1")
@@ -123,10 +148,23 @@ class Levelled(unittest.TestCase):
calls: list[tuple[str, ...]] = []
declined = Failure("git push --quiet origin c0mm17:refs/heads/ABC-1: ! [remote rejected] c0mm17 -> ABC-1 (protected branch hook declined)")
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted(calls, push=declined)), declined)
self.assertEqual([args[0] for args in calls], ["fetch", "rev-parse", "rev-list", "merge-tree", "commit-tree", "push"] * 2)
self.assertEqual([args[0] for args in calls], ["fetch", "ls-remote", "rev-list", "merge-tree", "commit-tree", "push"] * 2)
def test_a_fetch_that_fails_is_tried_once_more_since_a_chunk_starting_beside_it_may_hold_the_ref(self) -> None:
merge = ["rev-list", "merge-tree", "commit-tree", "push"]
for fetches, names in (([LOCKED, ""], ["fetch", "fetch", "ls-remote", *merge, "fetch"]), (["", LOCKED, ""], ["fetch", "ls-remote", *merge, "fetch", "fetch"])):
with self.subTest(fetches=fetches):
calls: list[tuple[str, ...]] = []
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted(calls, fetch=list(fetches))), "Merged origin/main into origin/ABC-1.")
self.assertEqual([args[0] for args in calls], names)
def test_a_fetch_that_fails_twice_fails_with_gits_reason(self) -> None:
calls: list[tuple[str, ...]] = []
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted(calls, fetch=LOCKED)), LOCKED)
self.assertEqual([args[0] for args in calls], ["fetch", "fetch"])
def test_every_call_to_origin_stops_after_the_timeout_given(self) -> None:
for answers, origin_calls in (({"rev_parse": Failure("git rev-parse: no such ref")}, ["fetch", "push", "fetch"]), ({"push": Failure("git push: rejected")}, ["fetch", "push", "fetch", "push"])):
for answers, origin_calls in (({"ls_remote": ""}, ["fetch", "ls-remote", "push", "fetch"]), ({"push": Failure("git push: rejected")}, ["fetch", "ls-remote", "push", "fetch", "ls-remote", "push"])):
with self.subTest(origin_calls=origin_calls):
timed: list[tuple[str, float | None]] = []
answering = scripted([], **answers)
@@ -135,7 +173,7 @@ class Levelled(unittest.TestCase):
timed.append((args[0], timeout))
return answering(*args, cwd=cwd, timeout=timeout, guarded=guarded, errors=errors)
levelled("ABC-1", "origin/main", timeout=5, run=run)
self.assertEqual([(name, timeout) for name, timeout in timed if name in ("fetch", "push")], [(name, 5) for name in origin_calls])
self.assertEqual([(name, timeout) for name, timeout in timed if name in ("fetch", "ls-remote", "push")], [(name, 5) for name in origin_calls])
class ChunkBase(unittest.TestCase):