Let a project's config name a working branch per epic that chunks branch off and merge into
CI / tests (pull_request) Successful in 5m4s
CI / tests (pull_request) Successful in 5m4s
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
"""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
|
||||
+22
-1
@@ -23,6 +23,10 @@ GUARD_SETTINGS = [
|
||||
]
|
||||
|
||||
|
||||
# The key, under `branch.<a chunk's branch>` in a checkout's git config, that names the epic's working branch the chunk merges into (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`).
|
||||
CHUNK_BASE = "chunk-base"
|
||||
|
||||
|
||||
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict", env: typing.Mapping[str, str] | None = None) -> str | Failure:
|
||||
"""What git printed, run in cwd, else in the current directory.
|
||||
|
||||
@@ -72,13 +76,15 @@ def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, s
|
||||
|
||||
|
||||
def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False, run: Git = git) -> str | Failure:
|
||||
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. run runs git.
|
||||
"""The ref the branch checked out merges into, as last fetched, read in cwd, else in the current directory. That is the default branch's: `origin/<branch>` with that remote, else the local main or master. On a chunk's branch that merges into an epic's working branch (`chunk_base`), it is `origin/<that branch>`, so each tool that measures a chunk against its base reads the chunk's own commits and not the epic's. run runs git.
|
||||
|
||||
Where the checkout records no default branch for origin, it asks origin, which fails after timeout seconds. Guarded, it runs git as `git` does with guarded, and fails there instead of asking origin."""
|
||||
remotes = run("remote", cwd=cwd, guarded=guarded)
|
||||
if isinstance(remotes, Failure):
|
||||
return remotes
|
||||
if "origin" in remotes.split():
|
||||
if base := chunk_base(cwd, guarded, run):
|
||||
return f"origin/{base}"
|
||||
recorded = run("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded)
|
||||
if not isinstance(recorded, Failure):
|
||||
return recorded.strip()
|
||||
@@ -89,6 +95,21 @@ def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: b
|
||||
return Failure("no origin remote, and no main or master branch to take as the default branch")
|
||||
|
||||
|
||||
def chunk_base(cwd: str | None = None, guarded: bool = False, run: Git = git) -> str | None:
|
||||
"""The epic's working branch that the branch checked out in cwd merges into, as `record_chunk_base` recorded it; None where none is recorded, as for every branch that merges into the default branch, and on a detached HEAD."""
|
||||
branch = run("symbolic-ref", "--quiet", "--short", "HEAD", cwd=cwd, guarded=guarded)
|
||||
if isinstance(branch, Failure):
|
||||
return None
|
||||
base = run("config", "--get", f"branch.{branch.strip()}.{CHUNK_BASE}", cwd=cwd, guarded=guarded)
|
||||
return None if isinstance(base, Failure) else base.strip() or None
|
||||
|
||||
|
||||
def record_chunk_base(branch: str, base: str, cwd: str | None = None, run: Git = git) -> Failure | None:
|
||||
"""Records in the checkout's git config that the chunk's branch merges into base, an epic's working branch. The branch need not exist yet, and deleting it removes the record."""
|
||||
recorded = run("config", f"branch.{branch}.{CHUNK_BASE}", base, cwd=cwd)
|
||||
return recorded if isinstance(recorded, Failure) else None
|
||||
|
||||
|
||||
def branch_titles(default: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> list[str] | Failure:
|
||||
"""The titles of the branch's own commits since default, newest first, read in cwd, else in the current directory.
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from git_cli import git_repo
|
||||
from git_cli.epic_branch import levelled
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
class Levelled(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.origin, self.clone = pathlib.Path(folder.name) / "origin.git", pathlib.Path(folder.name) / "clone"
|
||||
sh(pathlib.Path(folder.name), "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin))
|
||||
sh(pathlib.Path(folder.name), "clone", "--quiet", str(self.origin), str(self.clone))
|
||||
sh(self.clone, "config", "user.name", "T")
|
||||
sh(self.clone, "config", "user.email", "t@example.com")
|
||||
self.commit("main", "a.txt", "one\n")
|
||||
|
||||
def commit(self, branch: str, file: str, text: str) -> None:
|
||||
"""Commits text as file on origin's branch, made off origin/main where origin has none."""
|
||||
sh(self.clone, "fetch", "--quiet", "origin")
|
||||
known = subprocess.run(["git", "rev-parse", "--quiet", "--verify", f"refs/remotes/origin/{branch}"], cwd=self.clone, capture_output=True).returncode == 0
|
||||
sh(self.clone, "checkout", "--quiet", "-B", "scratch", *([f"origin/{branch}"] if known else []))
|
||||
(self.clone / file).write_text(text)
|
||||
sh(self.clone, "add", file)
|
||||
sh(self.clone, "commit", "--quiet", "-m", f"{file} on {branch}")
|
||||
sh(self.clone, "push", "--quiet", "origin", f"HEAD:refs/heads/{branch}")
|
||||
sh(self.clone, "fetch", "--quiet", "origin")
|
||||
|
||||
def test_makes_the_branch_off_the_default_branch_where_origin_has_none(self) -> None:
|
||||
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"))
|
||||
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_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")
|
||||
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "origin/ABC-1 already holds origin/main.")
|
||||
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), before)
|
||||
|
||||
def test_merges_a_moved_default_branch_in_with_a_merge_commit_and_no_checkout(self) -> None:
|
||||
self.commit("ABC-1", "b.txt", "epic\n")
|
||||
epic = sh(self.origin, "rev-parse", "ABC-1")
|
||||
self.commit("main", "c.txt", "main\n")
|
||||
checked_out = sh(self.clone, "rev-parse", "HEAD")
|
||||
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "Merged origin/main into origin/ABC-1.")
|
||||
self.assertEqual(sh(self.origin, "rev-list", "--parents", "-n", "1", "ABC-1").split()[1:], [epic, sh(self.origin, "rev-parse", "main")])
|
||||
self.assertEqual(sh(self.origin, "ls-tree", "--name-only", "ABC-1").split(), ["a.txt", "b.txt", "c.txt"])
|
||||
self.assertEqual(sh(self.origin, "log", "-1", "--format=%s", "ABC-1"), "Merge remote-tracking branch 'origin/main' into ABC-1")
|
||||
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "ABC-1"))
|
||||
self.assertEqual(sh(self.clone, "rev-parse", "HEAD"), checked_out)
|
||||
|
||||
def test_a_conflict_fails_for_a_person_and_leaves_the_branch(self) -> None:
|
||||
self.commit("ABC-1", "a.txt", "epic\n")
|
||||
before = sh(self.origin, "rev-parse", "ABC-1")
|
||||
self.commit("main", "a.txt", "main\n")
|
||||
done = levelled("ABC-1", "origin/main", cwd=str(self.clone))
|
||||
assert isinstance(done, Failure), done
|
||||
self.assertEqual(done.reason, "origin/main doesn't merge into origin/ABC-1 cleanly, so a person merges it: check ABC-1 out, run `git merge origin/main`, resolve the conflicts and push")
|
||||
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), before)
|
||||
|
||||
|
||||
class ChunkBase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.clone = pathlib.Path(folder.name)
|
||||
sh(self.clone, "init", "--quiet", "--initial-branch=main")
|
||||
sh(self.clone, "remote", "add", "origin", "https://example.com/acme.git")
|
||||
sh(self.clone, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
|
||||
|
||||
def test_a_branch_with_a_recorded_base_measures_against_it_and_any_other_against_the_default_branch(self) -> None:
|
||||
self.assertIsNone(git_repo.record_chunk_base("ABC-2", "ABC-1", cwd=str(self.clone)))
|
||||
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/main", "main has no recorded base")
|
||||
sh(self.clone, "checkout", "--quiet", "-b", "ABC-2")
|
||||
self.assertEqual(git_repo.chunk_base(cwd=str(self.clone)), "ABC-1")
|
||||
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/ABC-1")
|
||||
self.assertEqual(git_repo.default_ref(cwd=str(self.clone), guarded=True), "origin/ABC-1")
|
||||
sh(self.clone, "checkout", "--quiet", "-b", "ABC-3")
|
||||
self.assertIsNone(git_repo.chunk_base(cwd=str(self.clone)))
|
||||
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/main")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user