"""Keep an epic's working branch on origin: made off the default branch by the epic's first chunk, and level with it before each chunk starts and before the epic's own pull request opens (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`).""" import re from failure import Failure 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. A call to origin still running after timeout seconds fails. again is False in the second try `merged` makes after a push that failed.""" # Asked before the fetch: a branch another chunk makes after the fetch would be on origin and missing here. held = on_origin(branch, cwd, timeout, run) failed = held if isinstance(held, Failure) else fetched(cwd, timeout, run) if isinstance(failed, Failure): return failed 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/` 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}" behind = run("rev-list", "--count", f"{ours}..{default}", cwd=cwd) if isinstance(behind, Failure): return behind if behind.strip() == "0": return f"{ours} already holds {default}." # git 2.38 or later: merges two commits into a tree without a checkout. tree = run("merge-tree", "--write-tree", ours, default, cwd=cwd) if isinstance(tree, Failure): return unmerged(tree, branch, default) commit = run("commit-tree", tree.strip(), "-p", ours, "-p", default, "-m", f"Merge remote-tracking branch '{default}' into {branch}", cwd=cwd) if isinstance(commit, Failure): return commit failed = pushed(commit.strip(), branch, cwd, timeout, run) if failed and again: return levelled(branch, default, cwd, timeout, run, again=False) return failed or f"Merged {default} into {ours}." def unmerged(failed: Failure, branch: str, default: str) -> Failure: """Why `git merge-tree --write-tree` didn't merge default into origin's branch, from its Failure. A conflict prints nothing on stderr, so its reason ends at `git :`, or, from a runner that shows stdout in place of an empty stderr, goes on with the merged tree's id. Git older than 2.38 reads --write-tree as a commit, which it doesn't find. Any other Failure is git's own.""" ours = f"origin/{branch}" if re.fullmatch(r"git merge-tree [^:]*:\s*(?:[0-9a-f]{40,64}\b.*)?", failed.reason, re.DOTALL): return Failure(f"{default} doesn't merge into {ours} cleanly, so a person merges it: check {branch} out, run `git merge {default}`, resolve the conflicts and push") if "unknown rev --write-tree" in failed.reason: return Failure(f"levelling {ours} with {default} needs git 2.38 or later: {failed.reason}") return failed 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.""" 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)