38 lines
2.5 KiB
Python
38 lines
2.5 KiB
Python
"""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 …`)."""
|
|
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) -> 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."""
|
|
fetched = run("fetch", "--quiet", "origin", cwd=cwd, timeout=timeout)
|
|
if isinstance(fetched, Failure):
|
|
return fetched
|
|
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
|
|
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 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")
|
|
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
|
|
return pushed(commit.strip(), branch, cwd, timeout, run) or f"Merged {default} into {ours}."
|
|
|
|
|
|
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
|