178 lines
11 KiB
Python
178 lines
11 KiB
Python
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
|
|
from forge.commands import runner
|
|
|
|
|
|
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 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]]
|
|
return run
|
|
|
|
|
|
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)
|
|
|
|
def test_a_conflict_fails_for_a_person_from_a_runner_that_shows_stdout_where_stderr_is_empty(self) -> None:
|
|
self.commit("ABC-1", "a.txt", "epic\n")
|
|
self.commit("main", "a.txt", "main\n")
|
|
run = runner(str(self.clone))
|
|
done = levelled("ABC-1", "origin/main", run=lambda *args, **more: run(["git", *args]))
|
|
self.assertEqual(done, Failure("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"))
|
|
|
|
def test_a_merge_that_fails_other_than_by_a_conflict_fails_with_gits_reason(self) -> None:
|
|
sh(self.clone, "checkout", "--quiet", "--orphan", "stray")
|
|
sh(self.clone, "commit", "--quiet", "-m", "stray")
|
|
sh(self.clone, "push", "--quiet", "origin", "HEAD:refs/heads/ABC-1")
|
|
before = sh(self.origin, "rev-parse", "ABC-1")
|
|
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), Failure("git merge-tree --write-tree origin/ABC-1 origin/main: fatal: refusing to merge unrelated histories"))
|
|
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), before)
|
|
|
|
def test_a_git_older_than_2_38_fails_naming_the_git_levelling_needs(self) -> None:
|
|
# What git 2.36 prints: it reads --write-tree as a commit.
|
|
old = Failure("git merge-tree --write-tree origin/ABC-1 origin/main: fatal: unknown rev --write-tree")
|
|
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted([], merge_tree=old)), Failure("levelling origin/ABC-1 with origin/main needs git 2.38 or later: git merge-tree --write-tree origin/ABC-1 origin/main: fatal: unknown rev --write-tree"))
|
|
|
|
def test_a_merge_another_chunk_pushed_first_is_fetched_and_found_level(self) -> None:
|
|
self.commit("ABC-1", "b.txt", "epic\n")
|
|
self.commit("main", "c.txt", "main\n")
|
|
other = self.clone.parent / "other"
|
|
sh(self.clone.parent, "clone", "--quiet", str(self.origin), str(other))
|
|
sh(other, "config", "user.name", "Other")
|
|
sh(other, "config", "user.email", "other@example.com")
|
|
raced: list[str | Failure] = []
|
|
|
|
def racing(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
|
|
"""Runs git, after the other clone levels the branch just before this clone's first push."""
|
|
if args[0] == "push" and not raced:
|
|
raced.append(levelled("ABC-1", "origin/main", cwd=str(other)))
|
|
return git_repo.git(*args, cwd=cwd, timeout=timeout, guarded=guarded, errors=errors)
|
|
|
|
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone), run=racing), "origin/ABC-1 already holds origin/main.")
|
|
self.assertEqual(raced, ["Merged origin/main into origin/ABC-1."])
|
|
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(other, "rev-parse", "origin/ABC-1"))
|
|
|
|
def test_a_push_that_fails_again_after_a_fresh_fetch_fails_with_gits_reason(self) -> None:
|
|
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)
|
|
|
|
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"])):
|
|
with self.subTest(origin_calls=origin_calls):
|
|
timed: list[tuple[str, float | None]] = []
|
|
answering = scripted([], **answers)
|
|
|
|
def run(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
|
|
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])
|
|
|
|
|
|
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")
|
|
|
|
def test_a_guarded_read_of_the_recorded_base_runs_every_git_call_guarded(self) -> None:
|
|
calls: list[tuple[tuple[str, ...], bool]] = []
|
|
answers = {"remote": "origin\n", "symbolic-ref": "ABC-2\n", "config": "ABC-1\n"}
|
|
|
|
def run(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
|
|
calls.append((args, guarded))
|
|
return answers[args[0]]
|
|
self.assertEqual(git_repo.default_ref(guarded=True, run=run), "origin/ABC-1")
|
|
self.assertEqual(calls, [(("remote",), True), (("symbolic-ref", "--quiet", "--short", "HEAD"), True), (("config", "--get", "branch.ABC-2.chunk-base"), True)])
|
|
|
|
def test_a_base_git_cannot_record_fails_with_gits_reason(self) -> None:
|
|
refused = Failure("git config branch.ABC-2.chunk-base ABC-1: could not lock config file")
|
|
self.assertEqual(git_repo.record_chunk_base("ABC-2", "ABC-1", run=lambda *args, **more: refused), refused)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|