Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

nushell/tests/test_git_wt.py

Raw
"""End-to-end contract tests for the native ``git wt`` Nushell namespace.

Every repository, hook, approval, fake forge client, and Git configuration used
here lives below the OS temporary directory.  These tests intentionally execute
no network operation: remote refs are local Git fixture refs and forge clients
are deterministic local Python programs.
"""

from __future__ import annotations

import json
import os
from pathlib import Path
import shutil
import stat
import subprocess
import sys
import tempfile
import unittest


NU_DIR = Path(__file__).resolve().parents[1]
MODULE = NU_DIR / "modules" / "git.nu"
GIT = shutil.which("git")


def native_nu() -> str | None:
    """Avoid a version-manager shim after HOME is isolated for each fixture."""
    if os.name == "nt":
        candidate = Path(os.environ.get("ProgramFiles", r"C:\\Program Files")) / "nu" / "bin" / "nu.exe"
        if candidate.is_file():
            return str(candidate)
    return shutil.which("nu")


NU = native_nu()


def nu_literal(value: object) -> str:
    """Return a Nu raw string literal for an arbitrary fixture path/value."""
    text = str(value)
    hashes = "#"
    while f"'{hashes}" in text:
        hashes += "#"
    return f"r{hashes}'{text}'{hashes}"


class GitWtIntegration(unittest.TestCase):
    """Contract coverage for ordinary clones and bare-root repositories."""

    maxDiff = None

    @classmethod
    def setUpClass(cls):
        if not NU or not GIT:
            raise unittest.SkipTest("Nu and Git are required")
        parent = Path(tempfile.gettempdir()) / "pi-nu-wt-tests"
        parent.mkdir(parents=True, exist_ok=True)
        cls._temporary = tempfile.TemporaryDirectory(prefix="native-", dir=parent)
        cls.parent = Path(cls._temporary.name)

    @classmethod
    def tearDownClass(cls):
        cls._temporary.cleanup()

    def setUp(self):
        self.case = Path(tempfile.mkdtemp(prefix=f"{self._testMethodName}-", dir=self.parent))
        self.home = self.case / "home"
        self.home.mkdir()
        self.bin = self.case / "bin"
        self.bin.mkdir()
        self.config = self.case / "personal-wt.nuon"
        self.config.write_text("{}\n", encoding="utf-8")
        self.approvals = self.case / "approvals.nuon"
        self.global_config = self.case / "empty-global.gitconfig"
        self.global_config.write_text("", encoding="utf-8")
        self.system_config = self.case / "empty-system.gitconfig"
        self.system_config.write_text("", encoding="utf-8")
        self.template = self.case / "empty-template"
        self.template.mkdir()
        self.log = self.case / "fake-forge.log"
        self.environment = os.environ.copy()
        for key in list(self.environment):
            if key.lower() in {"home", "userprofile", "xdg_config_home", "xdg_data_home"}:
                self.environment.pop(key)
        self.environment.update(
            HOME=str(self.home),
            USERPROFILE=str(self.home),
            XDG_CONFIG_HOME=str(self.home / "config"),
            XDG_DATA_HOME=str(self.home / "data"),
            GIT_CONFIG_NOSYSTEM="1",
            GIT_CONFIG_GLOBAL=str(self.global_config),
            GIT_CONFIG_SYSTEM=str(self.system_config),
            GIT_TEMPLATE_DIR=str(self.template),
            NU_WT_CONFIG=str(self.config),
            NU_WT_APPROVALS=str(self.approvals),
            WT_FAKE_LOG=str(self.log),
        )
        path_key = next((key for key in self.environment if key.lower() == "path"), "PATH")
        self.environment[path_key] = str(self.bin) + os.pathsep + self.environment.get(path_key, "")
        self._write_forge_fixtures()

    def tearDown(self):
        shutil.rmtree(self.case, ignore_errors=True)

    def git(self, *args: object, cwd: Path | None = None, check: bool = True):
        result = subprocess.run(
            [GIT, *map(str, args)],
            cwd=cwd,
            env=self.environment,
            capture_output=True,
            encoding="utf-8",
            timeout=30,
            check=False,
        )
        if check:
            self.assertEqual(
                0,
                result.returncode,
                f"git {' '.join(map(str, args))}\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}",
            )
        return result

    def configure_identity(self, repo: Path):
        self.git("config", "user.name", "Native WT Test", cwd=repo)
        self.git("config", "user.email", "native-wt@example.invalid", cwd=repo)
        self.git("config", "commit.gpgsign", "false", cwd=repo)
        self.git("config", "core.hooksPath", str(self.template), cwd=repo)

    def commit(self, repo: Path, name: str, content: str, message: str):
        (repo / name).parent.mkdir(parents=True, exist_ok=True)
        (repo / name).write_text(content, encoding="utf-8")
        self.git("add", name, cwd=repo)
        self.git("commit", "-m", message, cwd=repo)

    def ordinary_clone(self) -> tuple[Path, Path]:
        """Return an ordinary clone plus its local bare remote fixture."""
        seed = self.case / "seed"
        remote = self.case / "origin.git"
        repo = self.case / "ordinary clone"
        self.git("init", "-b", "trunk", seed)
        self.configure_identity(seed)
        self.commit(seed, "README.md", "base\n", "base")
        self.git("init", "--bare", "--initial-branch=trunk", remote)
        self.git("remote", "add", "origin", str(remote), cwd=seed)
        self.git("push", "-u", "origin", "trunk", cwd=seed)
        self.git("clone", str(remote), repo)
        self.configure_identity(repo)
        return repo, remote

    def bare_layout(self) -> tuple[Path, Path]:
        """Return a bare directory and primary worktree beside it."""
        seed = self.case / "seed"
        remote = self.case / "origin.git"
        root = self.case / "bare root"
        bare = root / "project.git"
        primary = root / "trunk"
        self.git("init", "-b", "trunk", seed)
        self.configure_identity(seed)
        self.commit(seed, "README.md", "base\n", "base")
        self.git("init", "--bare", "--initial-branch=trunk", remote)
        self.git("remote", "add", "origin", str(remote), cwd=seed)
        self.git("push", "-u", "origin", "trunk", cwd=seed)
        root.mkdir()
        self.git("clone", "--bare", str(remote), bare)
        self.git("worktree", "add", primary, "trunk", cwd=bare)
        self.configure_identity(primary)
        return bare, primary

    def nu(self, code: str, *, cwd: Path, timeout: int = 90, environment=None):
        """Run one isolated Nu process using the public module namespace."""
        result = subprocess.run(
            [NU, "--no-config-file", "-c", f"$env.config.error_style = 'plain'; use {nu_literal(MODULE)}; cd {nu_literal(cwd)}; {code}"],
            # Nu's logical cd does not release its Windows startup-directory handle.
            cwd=self.case,
            env=self.environment if environment is None else environment,
            capture_output=True,
            encoding="utf-8",
            timeout=timeout,
            check=False,
        )
        return result

    def wt_json(self, invocation: str, *, cwd: Path):
        result = self.nu(
            "let result = (" + invocation + "); {result: $result, cwd: (pwd)} | to json",
            cwd=cwd,
        )
        self.assertEqual(
            0,
            result.returncode,
            f"{invocation}\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}",
        )
        self.assertNotIn("deprecated", result.stderr.lower())
        return json.loads(result.stdout)

    def wt_fails(self, invocation: str, *, cwd: Path, contains: str | None = None, environment=None):
        result = self.nu(invocation, cwd=cwd, environment=environment)
        self.assertNotEqual(0, result.returncode, f"unexpected success: {invocation}")
        if contains:
            self.assertIn(contains.lower(), (result.stdout + result.stderr).lower(),
                          f"{invocation}\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}")
        return result

    def branch_exists(self, repo: Path, branch: str) -> bool:
        return self.git("show-ref", "--verify", "--quiet", f"refs/heads/{branch}", cwd=repo, check=False).returncode == 0

    def worktree_path(self, repo: Path, branch: str) -> Path | None:
        output = self.git("worktree", "list", "--porcelain", cwd=repo).stdout.splitlines()
        path = None
        for line in output:
            if line.startswith("worktree "):
                path = Path(line.removeprefix("worktree "))
            elif line == f"branch refs/heads/{branch}":
                return path
        return None

    def write_project_hooks(self, repo: Path, events: dict[str, list[list[str]]]):
        config = repo / ".config" / "nu-wt.nuon"
        config.parent.mkdir(parents=True, exist_ok=True)
        # JSON is valid NUON data, keeps command values literal and cross-platform.
        config.write_text(json.dumps({"hooks": events}) + "\n", encoding="utf-8")

    def _write_forge_fixtures(self):
        program = self.bin / "forge_fixture.py"
        program.write_text(
            "import json, os, pathlib, sys\n"
            "pathlib.Path(os.environ['WT_FAKE_LOG']).parent.mkdir(parents=True, exist_ok=True)\n"
            "with open(os.environ['WT_FAKE_LOG'], 'a', encoding='utf-8') as f:\n"
            "    f.write(sys.argv[1] + ' ' + json.dumps(sys.argv[2:]) + '\\n')\n"
            "name = sys.argv[1]\n"
            "args = sys.argv[2:]\n"
            "mode = os.environ.get('WT_FAKE_MODE', 'ok')\n"
            "if mode == 'failure':\n"
            "    print('fixture authentication failure', file=sys.stderr); sys.exit(17)\n"
            "if mode == 'malformed':\n"
            "    print('unexpected provider output'); sys.exit(0)\n"
            "if name == 'gh' and 'list' in args:\n"
            "    print(json.dumps([{'number': 17, 'title': 'Fixture PR', 'headRefName': 'pr-branch'}]))\n"
            "elif name == 'fj':\n"
            "    print('#17 Fixture PR (by fixture)')\n"
            "sys.exit(0)\n",
            encoding="utf-8",
        )
        if os.name == "nt":
            for name in ("gh", "fj"):
                (self.bin / f"{name}.cmd").write_text(
                    f'@"{sys.executable}" "{program}" {name} %*\r\n', encoding="utf-8"
                )
        else:
            for name in ("gh", "fj"):
                launcher = self.bin / name
                launcher.write_text(
                    f"#!{sys.executable}\n"
                    "import runpy, sys\n"
                    f"sys.argv.insert(1, {name!r})\n"
                    f"runpy.run_path({str(program)!r}, run_name='__main__')\n",
                    encoding="utf-8",
                )
                launcher.chmod(launcher.stat().st_mode | stat.S_IXUSR)

    def test_list_and_status_are_structured_for_ordinary_clone(self):
        repo, _ = self.ordinary_clone()
        self.git("worktree", "add", "-b", "feature", self.case / "external feature", cwd=repo)
        feature = self.case / "external feature"
        (feature / "dirty.txt").write_text("dirty\n", encoding="utf-8")

        listed = self.wt_json("git wt list", cwd=repo)["result"]
        self.assertIsInstance(listed, list)
        by_branch = {row["branch"]: row for row in listed}
        self.assertEqual(str(repo.resolve()), by_branch["trunk"]["path"])
        self.assertTrue(by_branch["trunk"]["current"])
        self.assertTrue(by_branch["feature"]["dirty"])
        self.assertIn("locked", by_branch["feature"])

        default = self.wt_json("git wt", cwd=repo)["result"]
        self.assertEqual(listed, default)
        fast = self.wt_json("git wt list --fast", cwd=repo)["result"]
        self.assertEqual({row["branch"] for row in listed}, {row["branch"] for row in fast})
        self.assertTrue(all("dirty" not in row for row in fast), fast)

    def test_bare_root_lists_and_creates_worktrees_beside_bare_directory(self):
        bare, primary = self.bare_layout()
        self.git('config', 'wt.main-branch', 'trunk', cwd=bare)
        self.git('symbolic-ref', 'HEAD', 'refs/heads/unborn', cwd=bare)
        listed = self.wt_json("git wt list", cwd=primary)["result"]
        self.assertEqual(["trunk"], [row["branch"] for row in listed])
        self.assertEqual(str(primary.resolve()), listed[0]["path"])
        self.assertTrue(listed[0]['primary'])
        self.wt_fails('git wt remove trunk --keep-branch', cwd=primary, contains='primary')

        switched = self.wt_json("git wt switch --create feature --base trunk", cwd=primary)
        feature = bare.parent / "feature"
        self.assertEqual(str(feature.resolve()), switched["cwd"])
        self.assertTrue(feature.is_dir())
        self.assertEqual(feature.resolve(), self.worktree_path(primary, "feature").resolve())

    def test_switch_existing_arbitrary_path_and_new_local_branch_change_cwd(self):
        repo, _ = self.ordinary_clone()
        arbitrary = self.case / "outside" / "quoted existing worktree"
        arbitrary.parent.mkdir()
        self.git("worktree", "add", "-b", "existing", arbitrary, cwd=repo)

        existing = self.wt_json("git wt switch existing", cwd=repo)
        self.assertEqual(str(arbitrary.resolve()), existing["cwd"])
        by_path = self.wt_json(f"git wt switch {nu_literal(arbitrary)}", cwd=repo)
        self.assertEqual(str(arbitrary.resolve()), by_path["cwd"])

        created = self.wt_json("git wt switch --create nested/topic --base trunk", cwd=repo)
        expected = repo.parent / f"{repo.name}.worktrees" / "nested" / "topic"
        self.assertEqual(str(expected.resolve()), created["cwd"])
        self.assertTrue((expected / ".git").exists())

    def test_switch_remote_disambiguation_and_noninteractive_picker_refusal(self):
        repo, _ = self.ordinary_clone()
        self.git("branch", "topic", cwd=repo)
        tip = self.git("rev-parse", "trunk", cwd=repo).stdout.strip()
        self.git("update-ref", "refs/remotes/origin/topic", tip, cwd=repo)
        self.git("update-ref", "refs/remotes/origin/remote-only", tip, cwd=repo)

        self.wt_fails("git wt switch topic", cwd=repo, contains="ambiguous")
        self.wt_fails("git wt switch", cwd=repo, contains="interactive")
        switched = self.wt_json("git wt switch origin/remote-only", cwd=repo)
        expected = repo.parent / f"{repo.name}.worktrees" / "remote-only"
        self.assertEqual(str(expected.resolve()), switched["cwd"])
        self.assertTrue(self.branch_exists(repo, "remote-only"))

    def test_path_mapping_rejects_collision_traversal_reserved_and_case_collision(self):
        repo, _ = self.ordinary_clone()
        destination = repo.parent / f"{repo.name}.worktrees" / "occupied"
        destination.mkdir(parents=True)
        marker = destination / "must-survive"
        marker.write_text("do not delete", encoding="utf-8")

        self.wt_fails("git wt switch --create occupied --base trunk", cwd=repo, contains="occupied")
        self.assertEqual("do not delete", marker.read_text(encoding="utf-8"))
        self.wt_fails("git wt switch --create ../escape --base trunk", cwd=repo, contains="travers")
        self.wt_fails("git wt switch --create CON --base trunk", cwd=repo, contains="reserved")
        self.wt_json("git wt switch --create CaseName --base trunk", cwd=repo)
        self.wt_fails("git wt switch --create casename --base trunk", cwd=repo, contains="case")

    def test_remove_refuses_dirty_locked_primary_and_nested_registered_worktrees(self):
        repo, _ = self.ordinary_clone()
        dirty = self.case / "dirty"
        self.git("worktree", "add", "-b", "dirty", dirty, cwd=repo)
        (dirty / "uncommitted").write_text("x", encoding="utf-8")
        self.wt_fails("git wt remove dirty", cwd=repo, contains="dirty")
        self.assertTrue(dirty.exists())

        locked = self.case / "locked"
        self.git("worktree", "add", "-b", "locked", locked, cwd=repo)
        self.git("worktree", "lock", locked, cwd=repo)
        self.wt_fails("git wt remove locked", cwd=repo, contains="locked")
        self.assertTrue(locked.exists())
        self.wt_fails("git wt remove trunk", cwd=repo, contains="primary")

        parent = self.case / "nested parent"
        child = parent / "child"
        self.git("worktree", "add", "-b", "nested-parent", parent, cwd=repo)
        self.git("worktree", "add", "-b", "nested-child", child, cwd=repo)
        self.wt_fails("git wt remove nested-parent", cwd=repo, contains="nested")
        self.assertTrue(parent.exists())

    def test_default_branch_uses_remote_head_with_slash_remote_name(self):
        repo, remote = self.ordinary_clone()
        source = self.case / 'integrated into release'
        self.git('worktree', 'add', '-b', 'completed', source, cwd=repo)
        self.commit(source, 'completed.txt', 'done\n', 'completed')
        tip = self.git('rev-parse', 'HEAD', cwd=source).stdout.strip()
        self.git('branch', 'release', tip, cwd=repo)
        self.git('remote', 'add', 'up/stream', str(remote), cwd=repo)
        self.git('update-ref', 'refs/remotes/up/stream/release', tip, cwd=repo)
        self.git('symbolic-ref', 'refs/remotes/up/stream/HEAD', 'refs/remotes/up/stream/release', cwd=repo)
        self.git('symbolic-ref', '--delete', 'refs/remotes/origin/HEAD', cwd=repo)
        self.wt_json('git wt remove completed', cwd=repo)
        self.assertFalse(source.exists())
        self.assertFalse(self.branch_exists(repo, 'completed'))
        self.assertEqual(tip, self.git('rev-parse', 'release', cwd=repo).stdout.strip())

    def test_remove_keep_branch_and_integrated_cleanup_change_current_directory(self):
        repo, _ = self.ordinary_clone()
        kept = self.case / "kept"
        self.git("worktree", "add", "-b", "kept", kept, cwd=repo)
        removed = self.wt_json("git wt remove kept --keep-branch", cwd=repo)
        self.assertEqual(str(repo.resolve()), removed["cwd"])
        self.assertFalse(kept.exists())
        self.assertTrue(self.branch_exists(repo, "kept"))

        integrated = self.case / "integrated"
        self.git("worktree", "add", "-b", "integrated", integrated, cwd=repo)
        self.commit(integrated, "integrated.txt", "ok\n", "integrated")
        self.git("merge", "--ff-only", "integrated", cwd=repo)
        cleaned = self.wt_json("git wt remove integrated", cwd=integrated)
        self.assertEqual(str(repo.resolve()), cleaned["cwd"])
        self.assertFalse(integrated.exists())
        self.assertFalse(self.branch_exists(repo, "integrated"))

    def test_project_hook_approval_invalidation_and_literal_launch_argv(self):
        repo, _ = self.ordinary_clone()
        recorder = self.case / "record.py"
        hook_log = self.case / "hook argv.json"
        launch_log = self.case / "launch argv.json"
        recorder.write_text(
            "import json, os, pathlib, sys\n"
            "pathlib.Path(sys.argv[1]).write_text(json.dumps({'argv': sys.argv[2:], 'cwd': os.getcwd(), 'repo': os.environ.get('WT_REPO')}), encoding='utf-8')\n",
            encoding="utf-8",
        )
        self.write_project_hooks(
            repo,
            {"post-create": [[sys.executable, str(recorder), str(hook_log), "hook; literal", "$(not-shell)", ""]]},
        )
        self.git("add", ".config/nu-wt.nuon", cwd=repo)
        self.git("commit", "-m", "configure hooks", cwd=repo)

        unapproved = repo.parent / f"{repo.name}.worktrees" / "unapproved"
        self.wt_fails("git wt switch --create unapproved --base trunk", cwd=repo, contains="approval")
        self.assertTrue(unapproved.exists(), "declined project-hook approval preserves created data")
        approved = self.wt_json("git wt switch --create approved --base trunk --approve-hooks", cwd=repo)
        approved_path = Path(approved["cwd"])
        hook = json.loads(hook_log.read_text(encoding="utf-8"))
        self.assertEqual(["hook; literal", "$(not-shell)", ""], hook["argv"])
        self.assertEqual(str(approved_path), hook["cwd"])

        # Exact command content is trusted, not an event-wide blanket approval.
        self.write_project_hooks(
            approved_path,
            {"post-create": [[sys.executable, str(recorder), str(hook_log), "changed"]]},
        )
        self.wt_fails("git wt hook post-create", cwd=approved_path, contains="approval")

        launched = self.wt_json(
            "git wt switch approved --execute "
            + nu_literal(sys.executable)
            + " "
            + nu_literal(recorder)
            + " "
            + nu_literal(launch_log)
            + " "
            + nu_literal("arg; still literal")
            + " "
            + nu_literal("$(also-not-shell)"),
            cwd=repo,
        )
        self.assertEqual(str(approved_path), launched["cwd"])
        launch = json.loads(launch_log.read_text(encoding="utf-8"))
        self.assertEqual(["arg; still literal", "$(also-not-shell)"], launch["argv"])

    def test_switch_keeps_created_worktree_when_post_create_hook_or_launch_fails(self):
        repo, _ = self.ordinary_clone()
        failer = self.case / "fail.py"
        failer.write_text("import sys\nsys.exit(23)\n", encoding="utf-8")
        self.write_project_hooks(repo, {"post-create": [[sys.executable, str(failer)]]})
        self.git("add", ".config/nu-wt.nuon", cwd=repo)
        self.git("commit", "-m", "failing create hook", cwd=repo)

        created = repo.parent / f"{repo.name}.worktrees" / "hook-fails"
        self.wt_fails("git wt switch --create hook-fails --base trunk --approve-hooks", cwd=repo, contains="hook")
        self.assertTrue(created.exists(), "failed post-create must preserve new worktree")
        self.assertTrue(self.branch_exists(repo, "hook-fails"))

        self.write_project_hooks(repo, {"post-create": []})
        self.git("add", ".config/nu-wt.nuon", cwd=repo)
        self.git("commit", "-m", "disable hook", cwd=repo)
        launch = repo.parent / f"{repo.name}.worktrees" / "launch-fails"
        self.wt_fails(
            "git wt switch --create launch-fails --base trunk --execute " + nu_literal(sys.executable) + " -c " + nu_literal("import sys; sys.exit(29)"),
            cwd=repo,
            contains="launch",
        )
        self.assertTrue(launch.exists(), "failed launch must preserve new worktree")
        self.assertTrue(self.branch_exists(repo, "launch-fails"))

    def test_merge_squashes_rebases_updates_target_and_keeps_recovery_ref(self):
        repo, _ = self.ordinary_clone()
        source = self.case / "source"
        self.git("worktree", "add", "-b", "feature", source, cwd=repo)
        self.commit(source, "feature-one.txt", "one\n", "feature one")
        self.commit(source, "feature-two.txt", "two\n", "feature two")
        old_source_tip = self.git("rev-parse", "feature", cwd=repo).stdout.strip()
        self.commit(repo, "target.txt", "target\n", "target moved")

        merged = self.wt_json("git wt merge trunk --message 'integrate feature'", cwd=source)
        self.assertEqual(str(repo.resolve()), merged["cwd"])
        self.assertFalse(source.exists())
        self.assertFalse(self.branch_exists(repo, "feature"))
        self.assertEqual("target\n", (repo / "target.txt").read_text(encoding="utf-8"))
        self.assertEqual("one\n", (repo / "feature-one.txt").read_text(encoding="utf-8"))
        subjects = self.git("log", "trunk", "--format=%s", cwd=repo).stdout.splitlines()
        self.assertEqual("integrate feature", subjects[0])
        recovery = self.git("for-each-ref", "--contains", old_source_tip, "--format=%(refname)", cwd=repo).stdout.splitlines()
        self.assertTrue(recovery, "rewritten source tip needs a recovery ref")

    def test_merge_refuses_dirty_source_and_target_without_history_changes(self):
        repo, _ = self.ordinary_clone()
        source = self.case / 'dirty-merge-source'
        self.git('worktree', 'add', '-b', 'dirty-merge', source, cwd=repo)
        self.commit(source, 'feature.txt', 'feature\n', 'feature')
        source_tip = self.git('rev-parse', 'HEAD', cwd=source).stdout.strip()
        target_tip = self.git('rev-parse', 'HEAD', cwd=repo).stdout.strip()
        dirty_source = source / 'unfinished.txt'
        dirty_source.write_text('do not stage or discard', encoding='utf-8')
        self.wt_fails('git wt merge trunk', cwd=source, contains='dirty worktree')
        self.assertEqual('do not stage or discard', dirty_source.read_text(encoding='utf-8'))
        dirty_source.unlink()
        dirty_target = repo / 'unfinished-target.txt'
        dirty_target.write_text('keep target', encoding='utf-8')
        self.wt_fails('git wt merge trunk', cwd=source, contains='dirty worktree')
        self.assertEqual('keep target', dirty_target.read_text(encoding='utf-8'))
        self.assertEqual(source_tip, self.git('rev-parse', 'HEAD', cwd=source).stdout.strip())
        self.assertEqual(target_tip, self.git('rev-parse', 'HEAD', cwd=repo).stdout.strip())
        self.assertEqual('', self.git('for-each-ref', '--format=%(refname)', 'refs/wt/recovery/', cwd=repo).stdout.strip())

    def test_merge_keep_retains_source_worktree_and_branch(self):
        repo, _ = self.ordinary_clone()
        source = self.case / "keep source"
        self.git("worktree", "add", "-b", "keep-source", source, cwd=repo)
        self.commit(source, "keep.txt", "keep\n", "keep source")

        merged = self.wt_json("git wt merge trunk --message 'keep source' --keep", cwd=source)
        self.assertEqual(str(source.resolve()), merged["cwd"])
        self.assertEqual("keep\n", (repo / "keep.txt").read_text(encoding="utf-8"))
        self.assertTrue(source.exists())
        self.assertTrue(self.branch_exists(repo, "keep-source"))

    def test_merge_conflict_and_pre_merge_hook_failure_preserve_source_worktree(self):
        repo, _ = self.ordinary_clone()
        source = self.case / "conflict source"
        self.git("worktree", "add", "-b", "conflict", source, cwd=repo)
        self.commit(source, "README.md", "source\n", "source edit")
        self.commit(repo, "README.md", "target\n", "target edit")
        self.wt_fails("git wt merge trunk --message conflict", cwd=source, contains="conflict")
        self.assertTrue(source.exists())
        self.assertTrue(self.branch_exists(repo, "conflict"))
        self.assertNotEqual("", self.git("status", "--porcelain", cwd=source).stdout)

        self.git("rebase", "--abort", cwd=source, check=False)
        self.git("reset", "--hard", "trunk", cwd=source)
        self.commit(source, "hook.txt", "x\n", "hook candidate")
        failer = self.case / "pre_merge_fails.py"
        failer.write_text("import sys\nsys.exit(41)\n", encoding="utf-8")
        self.write_project_hooks(source, {"pre-merge": [[sys.executable, str(failer)]]})
        self.git("add", ".config/nu-wt.nuon", cwd=source)
        self.git("commit", "-m", "configure pre-merge check", cwd=source)
        self.wt_fails("git wt merge trunk --message hook --approve-hooks", cwd=source, contains="hook failed")
        self.assertTrue(source.exists())
        self.assertTrue(self.branch_exists(repo, "conflict"))

    def test_merge_rebase_cannot_auto_approve_new_hook_content(self):
        repo, _ = self.ordinary_clone()
        marker = self.case / 'unexpected-hook'
        writer = self.case / 'write-marker.py'
        writer.write_text('import pathlib, sys\npathlib.Path(sys.argv[1]).write_text("ran")\n', encoding='utf-8')
        self.write_project_hooks(repo, {'pre-merge': [[sys.executable, '-c', 'pass']]})
        self.git('add', '.config/nu-wt.nuon', cwd=repo)
        self.git('commit', '-m', 'initial approved command', cwd=repo)
        source = self.case / 'hook-change-source'
        self.git('worktree', 'add', '-b', 'hook-change', source, cwd=repo)
        self.commit(source, 'feature.txt', 'feature\n', 'feature')
        self.write_project_hooks(repo, {'pre-merge': [[sys.executable, str(writer), str(marker)]]})
        self.git('add', '.config/nu-wt.nuon', cwd=repo)
        self.git('commit', '-m', 'target changes hook', cwd=repo)
        target_tip = self.git('rev-parse', 'HEAD', cwd=repo).stdout.strip()
        self.wt_fails('git wt merge trunk --approve-hooks', cwd=source, contains='approval')
        self.assertFalse(marker.exists())
        self.assertEqual(target_tip, self.git('rev-parse', 'HEAD', cwd=repo).stdout.strip())
        self.assertTrue(source.exists())

    def test_merge_reports_partial_success_when_pre_remove_hook_fails(self):
        repo, _ = self.ordinary_clone()
        source = self.case / "partial source"
        self.git("worktree", "add", "-b", "partial", source, cwd=repo)
        self.commit(source, "partial.txt", "done\n", "partial candidate")
        failer = self.case / "pre_remove_fails.py"
        failer.write_text("import sys\nsys.exit(43)\n", encoding="utf-8")
        self.write_project_hooks(source, {"pre-remove": [[sys.executable, str(failer)]]})
        self.git("add", ".config/nu-wt.nuon", cwd=source)
        self.git("commit", "-m", "configure cleanup check", cwd=source)

        self.wt_fails("git wt merge trunk --message partial --approve-hooks", cwd=source, contains="partial")
        self.assertEqual("done\n", (repo / "partial.txt").read_text(encoding="utf-8"))
        self.assertTrue(source.exists(), "failed cleanup must not remove source")
        self.assertTrue(self.branch_exists(repo, "partial"))

    def test_pr_checkout_and_pr_listing_use_explicit_mocked_provider_only(self):
        repo, remote = self.ordinary_clone()
        tip = self.git("rev-parse", "trunk", cwd=repo).stdout.strip()
        # This local bare remote models GitHub/Forgejo's required pull-head ref
        # without making a network request.  Checkout must explicitly fetch it.
        self.git("update-ref", "refs/pull/17/head", tip, cwd=remote)

        prs = self.wt_json("git wt prs --remote origin", cwd=repo)["result"]
        self.assertEqual(17, prs[0]["number"])
        self.assertEqual("Fixture PR", prs[0]["title"])
        self.assertEqual("origin", prs[0]["remote"])
        self.assertIn("provider", prs[0])
        self.assertTrue(self.log.exists())

        checked_out = self.wt_json("git wt switch pr:17 --remote origin", cwd=repo)
        pr_path = Path(checked_out["cwd"])
        self.assertNotEqual("", self.git("branch", "--show-current", cwd=pr_path).stdout.strip())
        self.assertEqual(tip, self.git("rev-parse", "HEAD", cwd=pr_path).stdout.strip())
        self.assertTrue((pr_path / "README.md").exists())
        self.commit(pr_path, 'local-pr-work.txt', 'keep\n', 'local PR work')
        local_tip = self.git('rev-parse', 'HEAD', cwd=pr_path).stdout.strip()
        repeated = self.wt_json('git wt switch pr:17 --remote origin', cwd=repo)
        self.assertEqual(str(pr_path.resolve()), repeated['cwd'])
        self.assertEqual(local_tip, self.git('rev-parse', 'HEAD', cwd=pr_path).stdout.strip())

    def test_provider_json_and_fail_closed_errors(self):
        repo, _ = self.ordinary_clone()
        self.git('remote', 'set-url', 'origin', 'https://github.com/fixture/project.git', cwd=repo)
        result = self.wt_json('git wt prs --remote origin', cwd=repo)['result']
        self.assertEqual('github', result[0]['provider'])
        self.assertEqual('Fixture PR', result[0]['title'])
        for mode, message in [('failure', 'authentication failure'), ('malformed', 'invalid PR JSON')]:
            environment = self.environment.copy()
            environment['WT_FAKE_MODE'] = mode
            self.wt_fails('git wt prs --remote origin', cwd=repo, contains=message, environment=environment)
        self.assertNotIn('fj ', self.log.read_text(encoding='utf-8'))
        self.git('remote', 'set-url', 'origin', 'https://forgejo.example.invalid/owner/github-project.git', cwd=repo)
        self.assertEqual('forgejo', self.wt_json('git wt prs --remote origin', cwd=repo)['result'][0]['provider'])
        environment = self.environment.copy()
        environment['WT_FAKE_MODE'] = 'malformed'
        self.wt_fails('git wt prs --remote origin', cwd=repo, contains='unrecognized fj', environment=environment)

    def test_completion_is_local_read_only_and_returns_valid_replacement_spans(self):
        repo, _ = self.ordinary_clone()
        self.git("branch", "feature/complete", cwd=repo)
        text = "git wt switch feature/co"
        result = self.nu(
            nu_literal(text) + " | commandline complete --detailed | to json",
            cwd=repo,
        )
        self.assertEqual(0, result.returncode, result.stderr)
        records = json.loads(result.stdout)
        suggestion = next(row for row in records if "feature/complete" in row["value"])
        self.assertIsInstance(suggestion["span"]["start"], int)
        self.assertIsInstance(suggestion["span"]["end"], int)
        self.assertGreaterEqual(suggestion["span"]["start"], 0)
        self.assertLessEqual(suggestion["span"]["end"], len(text))
        completed = text[: suggestion["span"]["start"]] + suggestion["value"] + text[suggestion["span"]["end"] :]
        self.assertIn("feature/complete", completed)
        self.assertFalse(self.log.exists(), "completion must not invoke forge CLIs")

    def test_empty_hook_configs_and_explicit_skip(self):
        repo, _ = self.ordinary_clone()
        self.config.write_text('{hooks: {}}\n', encoding='utf-8')
        self.approvals.write_text('{}\n', encoding='utf-8')
        created = self.wt_json('git wt switch --create empty-config --base trunk', cwd=repo)
        self.assertTrue(Path(created['cwd']).is_dir())
        self.config.write_text('not valid [', encoding='utf-8')
        skipped = self.wt_json('git wt switch --create skip-config --base trunk --no-hooks', cwd=repo)
        self.assertTrue(Path(skipped['cwd']).is_dir())

    def test_completion_quotes_literal_worktree_paths(self):
        repo, _ = self.ordinary_clone()
        arbitrary = self.case / 'literal worktree path'
        self.git('worktree', 'add', '-b', 'quoted-path', arbitrary, cwd=repo)
        text = 'git wt switch `'+ str(arbitrary)[:-4]
        result = self.nu(nu_literal(text) + ' | commandline complete --detailed | to json', cwd=repo)
        self.assertEqual(0, result.returncode, result.stderr)
        records = json.loads(result.stdout)
        suggestion = next(row for row in records if 'literal worktree path' in row['value'])
        span = suggestion['span']
        completed = text[:span['start']] + suggestion['value'] + text[span['end']:]
        switched = self.wt_json(completed, cwd=repo)
        self.assertEqual(str(arbitrary.resolve()), switched['cwd'])

    def test_standard_git_completion_still_delegates(self):
        repo, _ = self.ordinary_clone()
        help_result = self.nu('git wt switch --help', cwd=repo)
        self.assertEqual(0, help_result.returncode, help_result.stderr)
        self.assertIn('--execute', help_result.stdout)
        result = self.nu(
            '$env.config.completions.external.completer = {|place| [external-completion-ok]}; '
            "'git checkout ext' | commandline complete | to json", cwd=repo,
        )
        self.assertEqual(0, result.returncode, result.stderr)
        self.assertIn('external-completion-ok', json.loads(result.stdout))

    @unittest.skipUnless(os.name == 'nt', 'Windows startup-directory handle safety')
    def test_startup_directory_removal_is_refused_without_mutation(self):
        repo, _ = self.ordinary_clone()
        held = self.case / 'held'
        self.git('worktree', 'add', '-b', 'held', held, cwd=repo)
        result = subprocess.run(
            [NU, '--no-config-file', '-c', f"$env.config.error_style = 'plain'; use {nu_literal(MODULE)}; git wt remove --keep-branch"],
            cwd=held, env=self.environment, capture_output=True, encoding='utf-8', timeout=30,
        )
        self.assertNotEqual(0, result.returncode)
        self.assertIn('startup cwd', result.stderr)
        self.assertTrue(held.exists())
        self.assertTrue(self.branch_exists(repo, 'held'))

    def test_git_alias_remains_usable_with_native_namespace(self):
        repo, _ = self.ordinary_clone()
        result = self.nu("alias g = git; g wt list | to json", cwd=repo)
        self.assertEqual(0, result.returncode, result.stderr)
        rows = json.loads(result.stdout)
        self.assertEqual("trunk", rows[0]["branch"])


if __name__ == "__main__":
    unittest.main()