From cc2b04104833f9c2deff9945496d2e329fd97f6c Mon Sep 17 00:00:00 2001 From: ThatXliner Date: Mon, 7 Sep 2026 19:12:17 -0700 Subject: [PATCH] Use GitPython for Git operations --- pyproject.toml | 1 + src/git_worm/files.py | 55 +++++++--------- src/git_worm/routes/prune.py | 20 +++--- src/git_worm/worktree.py | 124 ++++++++++++++++------------------- tests/test_files.py | 18 +++++ tests/test_integration.py | 20 ++++++ tests/test_worktree.py | 105 ++++++++++++++++++++++++++++- uv.lock | 39 ++++++++++- 8 files changed, 273 insertions(+), 109 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 21effef..8a445cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Topic :: Software Development :: Version Control :: Git", ] dependencies = [ + "gitpython>=3.1.46", "xclif>=0.6.1", ] diff --git a/src/git_worm/files.py b/src/git_worm/files.py index 5c45348..e3d588a 100644 --- a/src/git_worm/files.py +++ b/src/git_worm/files.py @@ -10,6 +10,8 @@ from fnmatch import fnmatch from pathlib import Path +from git import Repo + from git_worm.config import ShareRule EXCLUDED_NAMES = {".git", ".worktrees"} @@ -29,14 +31,17 @@ def _reflink_cmd(src: Path, dst: Path, *, recursive: bool = False) -> list[str]: def _has_tracked_files(repo: Path, directory: str) -> bool: """Check if a directory contains any files tracked by git.""" - result = subprocess.run( - ["git", "ls-files", directory], - cwd=repo, - check=True, - capture_output=True, - text=True, - ) - return bool(result.stdout.strip()) + with Repo(repo, search_parent_directories=True) as git_repo: + return bool(git_repo.git.ls_files(directory).strip()) + + +def _ignored_paths(status_output: str) -> list[str]: + """Extract ignored paths from NUL-delimited porcelain status output.""" + return [ + record.removeprefix("!! ") + for record in status_output.split("\0") + if record.startswith("!! ") + ] def get_ignored_entries(repo: Path) -> list[Path]: @@ -46,19 +51,14 @@ def get_ignored_entries(repo: Path) -> list[Path]: For tracked directories that contain ignored files, returns the individual ignored file paths instead. """ - result = subprocess.run( - ["git", "status", "--ignored", "--porcelain"], - cwd=repo, - check=True, - capture_output=True, - text=True, - ) + with Repo(repo, search_parent_directories=True) as git_repo: + status_output = git_repo.git.status( + "--ignored", "--porcelain", "-z", "--no-renames" + ) entries = [] seen: set[str] = set() - for line in result.stdout.splitlines(): - if not line.startswith("!! "): - continue - rel = line.removeprefix("!! ").rstrip("/") + for ignored_path in _ignored_paths(status_output): + rel = ignored_path.rstrip("/") top_level = rel.split("/")[0] if top_level in EXCLUDED_NAMES: continue @@ -81,18 +81,13 @@ def get_ignored_entries(repo: Path) -> list[Path]: def _get_ignored_files_in(repo: Path, directory: str) -> list[Path]: """Get individual ignored file paths within a partially-tracked directory.""" - result = subprocess.run( - ["git", "status", "--ignored", "--porcelain", directory], - cwd=repo, - check=True, - capture_output=True, - text=True, - ) + with Repo(repo, search_parent_directories=True) as git_repo: + status_output = git_repo.git.status( + "--ignored", "--porcelain", "-z", "--no-renames", "--", directory + ) paths = [] - for line in result.stdout.splitlines(): - if not line.startswith("!! "): - continue - rel = line.removeprefix("!! ").rstrip("/") + for ignored_path in _ignored_paths(status_output): + rel = ignored_path.rstrip("/") path = repo / rel if path.exists(): paths.append(path) diff --git a/src/git_worm/routes/prune.py b/src/git_worm/routes/prune.py index 5663649..3f39ffe 100644 --- a/src/git_worm/routes/prune.py +++ b/src/git_worm/routes/prune.py @@ -1,8 +1,14 @@ -import subprocess from pathlib import Path from typing import Annotated -from git_worm.worktree import find_repo_root, is_dirty, is_merged, list_worktrees, remove_worktree +from git_worm.worktree import ( + find_repo_root, + is_dirty, + is_merged, + list_worktrees, + prune_worktrees, + remove_worktree, +) from xclif import Option, command, console @@ -40,13 +46,7 @@ def _( """ repo = find_repo_root() - stale_result = subprocess.run( - ["git", "worktree", "prune", "--verbose", "--dry-run", "--expire=now"], - check=True, - capture_output=True, - text=True, - ) - stale_lines = stale_result.stderr.strip().splitlines() if stale_result.stderr.strip() else [] + stale_lines = prune_worktrees(cwd=repo, dry_run=True) merged_worktrees: list[dict[str, str]] = [] dirty_merged: list[dict[str, str]] = [] @@ -86,7 +86,7 @@ def _( return if stale_lines: - subprocess.run(["git", "worktree", "prune", "--verbose", "--expire=now"], check=True, capture_output=True, text=True) + prune_worktrees(cwd=repo) for line in stale_lines: console.print(f"[dim]pruned:[/dim] {line}") diff --git a/src/git_worm/worktree.py b/src/git_worm/worktree.py index 56f2f8d..4bb5d16 100644 --- a/src/git_worm/worktree.py +++ b/src/git_worm/worktree.py @@ -2,18 +2,16 @@ from __future__ import annotations -import subprocess from pathlib import Path +from git import Repo +from git.exc import GitCommandError, InvalidGitRepositoryError + def branch_exists(branch: str) -> bool: """Return True if a local branch with this name already exists.""" - result = subprocess.run( - ["git", "rev-parse", "--verify", f"refs/heads/{branch}"], - capture_output=True, - text=True, - ) - return result.returncode == 0 + with Repo(Path.cwd(), search_parent_directories=True) as repo: + return any(head.name == branch for head in repo.heads) def add_worktree(path: Path, branch: str, *, from_ref: str | None = None) -> bool: @@ -26,28 +24,21 @@ def add_worktree(path: Path, branch: str, *, from_ref: str | None = None) -> boo """ path.parent.mkdir(parents=True, exist_ok=True) if branch_exists(branch): - subprocess.run( - ["git", "worktree", "add", str(path), branch], - check=True, - capture_output=True, - text=True, - ) + with Repo(Path.cwd(), search_parent_directories=True) as repo: + repo.git.worktree("add", str(path), branch) return True - subprocess.run( - ["git", "worktree", "add", "-b", branch, str(path), from_ref or "HEAD"], - check=True, - capture_output=True, - text=True, - ) + with Repo(Path.cwd(), search_parent_directories=True) as repo: + repo.git.worktree("add", "-b", branch, str(path), from_ref or "HEAD") return False def remove_worktree(path: Path, *, force: bool = False) -> None: """Remove a worktree.""" - cmd = ["git", "worktree", "remove", str(path)] + args = ["remove", str(path)] if force: - cmd.append("--force") - subprocess.run(cmd, check=True, capture_output=True, text=True) + args.append("--force") + with Repo(Path.cwd(), search_parent_directories=True) as repo: + repo.git.worktree(*args) def find_worktree(branch: str, *, cwd: Path | None = None) -> dict[str, str] | None: @@ -60,27 +51,24 @@ def find_worktree(branch: str, *, cwd: Path | None = None) -> dict[str, str] | N def list_worktrees(cwd: Path | None = None) -> list[dict[str, str]]: """List all worktrees. Returns list of dicts with 'path', 'head', 'branch' keys.""" - result = subprocess.run( - ["git", "worktree", "list", "--porcelain"], - check=True, - capture_output=True, - text=True, - cwd=cwd, - ) + with Repo(Path.cwd() if cwd is None else cwd, search_parent_directories=True) as repo: + output = repo.git.worktree("list", "--porcelain", "-z") worktrees = [] current: dict[str, str] = {} - for line in result.stdout.splitlines(): - if line.startswith("worktree "): + for field in output.split("\0"): + if not field: + continue + if field.startswith("worktree "): if current: worktrees.append(current) - current = {"path": str(Path(line.removeprefix("worktree ")))} - elif line.startswith("HEAD "): - current["head"] = line.removeprefix("HEAD ") - elif line.startswith("branch "): - current["branch"] = line.removeprefix("branch ").removeprefix("refs/heads/") - elif line == "bare": + current = {"path": str(Path(field.removeprefix("worktree ")))} + elif field.startswith("HEAD "): + current["head"] = field.removeprefix("HEAD ") + elif field.startswith("branch "): + current["branch"] = field.removeprefix("branch ").removeprefix("refs/heads/") + elif field == "bare": current["bare"] = "true" - elif line == "detached": + elif field == "detached": current["detached"] = "true" if current: worktrees.append(current) @@ -89,13 +77,10 @@ def list_worktrees(cwd: Path | None = None) -> list[dict[str, str]]: def find_repo_root() -> Path: """Find the git repo root from cwd.""" - result = subprocess.run( - ["git", "rev-parse", "--show-toplevel"], - check=True, - capture_output=True, - text=True, - ) - return Path(result.stdout.strip()) + with Repo(Path.cwd(), search_parent_directories=True) as repo: + if repo.bare or repo.working_tree_dir is None: + raise InvalidGitRepositoryError("Cannot find a working tree for a bare repository") + return Path(repo.working_tree_dir) def get_default_branch(cwd: Path | None = None) -> str: @@ -105,14 +90,14 @@ def get_default_branch(cwd: Path | None = None) -> str: 1. refs/remotes/origin/HEAD (remote's default branch) 2. Primary worktree's branch (local default when no remote) """ - result = subprocess.run( - ["git", "symbolic-ref", "refs/remotes/origin/HEAD"], - capture_output=True, - text=True, - cwd=cwd, - ) - if result.returncode == 0: - return result.stdout.strip().removeprefix("refs/remotes/origin/") + repo_path = Path.cwd() if cwd is None else cwd + try: + with Repo(repo_path, search_parent_directories=True) as repo: + remote_head = repo.git.symbolic_ref("refs/remotes/origin/HEAD") + except GitCommandError: + remote_head = None + if remote_head is not None: + return remote_head.strip().removeprefix("refs/remotes/origin/") worktrees = list_worktrees(cwd=cwd) if worktrees and "branch" in worktrees[0]: return worktrees[0]["branch"] @@ -124,21 +109,26 @@ def is_merged(branch: str, cwd: Path | None = None) -> bool: default = get_default_branch(cwd=cwd) if branch == default: return False - result = subprocess.run( - ["git", "merge-base", "--is-ancestor", branch, default], - capture_output=True, - cwd=cwd, - ) - return result.returncode == 0 + with Repo(Path.cwd() if cwd is None else cwd, search_parent_directories=True) as repo: + try: + return repo.is_ancestor(branch, default) + except GitCommandError: + return False def is_dirty(path: Path) -> bool: """Check if a worktree has uncommitted changes.""" - result = subprocess.run( - ["git", "status", "--porcelain"], - cwd=path, - check=True, - capture_output=True, - text=True, - ) - return bool(result.stdout.strip()) + with Repo(path, search_parent_directories=True) as repo: + return repo.is_dirty(untracked_files=True) + + +def prune_worktrees(cwd: Path | None = None, *, dry_run: bool = False) -> list[str]: + """Prune stale worktree references and return verbose output lines.""" + args = ["prune"] + if dry_run: + args.append("--dry-run") + args.extend(["--verbose", "--expire=now"]) + with Repo(Path.cwd() if cwd is None else cwd, search_parent_directories=True) as repo: + _, stdout, stderr = repo.git.worktree(*args, with_extended_output=True) + output = "\n".join(part for part in (stderr, stdout) if part) + return output.strip().splitlines() if output.strip() else [] diff --git a/tests/test_files.py b/tests/test_files.py index 60bb9be..2fb1a8d 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -170,3 +170,21 @@ def test_copy_ignored_files_matches_relative_paths(git_repo): ) assert (dst / "src" / "cache.pyc").read_text() == "cache" assert results == [{"name": "src/cache.pyc", "action": "copied"}] + + +def test_ignored_files_in_partially_tracked_directory_keep_spaces_and_unicode(git_repo): + directory = git_repo / "partially tracked" + directory.mkdir() + (directory / "tracked.txt").write_text("tracked") + ignored = directory / "caché résumé.txt" + ignored.write_text("ignored") + (git_repo / ".gitignore").write_text("partially tracked/*\n!partially tracked/tracked.txt\n") + subprocess.run(["git", "add", ".gitignore", str(directory / "tracked.txt")], cwd=git_repo, check=True, capture_output=True) + subprocess.run( + ["git", "commit", "-m", "track partial directory"], + cwd=git_repo, + check=True, + capture_output=True, + ) + + assert get_ignored_entries(git_repo) == [ignored] diff --git a/tests/test_integration.py b/tests/test_integration.py index 6b56f64..f097dc8 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -206,3 +206,23 @@ def test_full_workflow(self, repo): assert _run(["rm", "feat-e2e", "--yes"], repo).returncode == 0 assert not (repo / ".worktrees" / "feat-e2e").exists() + + +def test_workflow_from_nested_and_linked_worktree(repo): + (repo / "src").mkdir() + (repo / "src" / "tracked.txt").write_text("tracked") + (repo / ".gitignore").write_text("*.cache\n.worktrees/\n") + _git(["add", "."], repo) + _git(["commit", "-m", "nested files"], repo) + ignored = "résumé cache.cache" + (repo / "src" / ignored).write_text("cached content") + + _run(["new", "nested-feature"], repo / "src") + wt = repo / ".worktrees" / "nested-feature" + assert (wt / "src" / ignored).read_text() == "cached content" + result = _run(["switch", "nested-feature", "--path"], wt / "src") + assert result.stdout.strip() == str(wt) + assert "nested-feature" in _run(["list"], wt / "src").stdout + + _run(["rm", "nested-feature", "--yes"], repo / "src") + assert not wt.exists() diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 4b0b25a..5ff4dda 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -1,6 +1,20 @@ +import shutil import subprocess -from git_worm.worktree import add_worktree, remove_worktree, list_worktrees, is_dirty, is_merged, get_default_branch +import pytest +from git.exc import GitCommandError, InvalidGitRepositoryError + +from git_worm.worktree import ( + add_worktree, + branch_exists, + find_repo_root, + get_default_branch, + is_dirty, + is_merged, + list_worktrees, + prune_worktrees, + remove_worktree, +) def test_add_worktree_creates_directory(git_repo): @@ -49,6 +63,95 @@ def test_is_dirty_with_tracked_changes(git_repo): assert is_dirty(git_repo) +def test_is_dirty_with_staged_changes_and_ignores_ignored_files(git_repo): + (git_repo / ".gitignore").write_text("ignored.txt\n") + subprocess.run(["git", "add", ".gitignore"], cwd=git_repo, check=True, capture_output=True) + subprocess.run( + ["git", "commit", "-m", "add gitignore"], + cwd=git_repo, + check=True, + capture_output=True, + ) + (git_repo / "ignored.txt").write_text("ignored") + assert not is_dirty(git_repo) + + (git_repo / "README.md").write_text("staged") + subprocess.run(["git", "add", "README.md"], cwd=git_repo, check=True, capture_output=True) + assert is_dirty(git_repo) + + +def test_branch_exists_only_checks_local_branches(git_repo): + branch = subprocess.run( + ["git", "branch", "--show-current"], + cwd=git_repo, + check=True, + capture_output=True, + text=True, + ).stdout.strip() + subprocess.run(["git", "tag", "v1"], cwd=git_repo, check=True, capture_output=True) + + assert branch_exists(branch) + assert not branch_exists("v1") + + +def test_find_repo_root_from_nested_directory(git_repo, monkeypatch): + nested = git_repo / "nested" / "directory" + nested.mkdir(parents=True) + monkeypatch.chdir(nested) + + assert find_repo_root() == git_repo + + +def test_find_repo_root_rejects_bare_repo(tmp_path, monkeypatch): + bare = tmp_path / "bare.git" + subprocess.run(["git", "init", "--bare", str(bare)], check=True, capture_output=True) + monkeypatch.chdir(bare) + + with pytest.raises(InvalidGitRepositoryError): + find_repo_root() + + +def test_list_worktrees_marks_detached_worktree(git_repo): + wt_path = git_repo / ".worktrees" / "detached" + add_worktree(wt_path, "detached") + subprocess.run( + ["git", "checkout", "--detach", "HEAD"], + cwd=wt_path, + check=True, + capture_output=True, + ) + + worktree = next(wt for wt in list_worktrees() if wt["path"] == str(wt_path)) + assert worktree.get("detached") == "true" + assert "branch" not in worktree + + +def test_remove_dirty_worktree_requires_force(git_repo): + wt_path = git_repo / ".worktrees" / "dirty" + add_worktree(wt_path, "dirty") + (wt_path / "untracked.txt").write_text("dirty") + + with pytest.raises(GitCommandError): + remove_worktree(wt_path) + + remove_worktree(wt_path, force=True) + assert not wt_path.exists() + + +def test_prune_worktrees_dry_run_then_removes_stale_ref(git_repo): + wt_path = git_repo / ".worktrees" / "stale" + add_worktree(wt_path, "stale") + shutil.rmtree(wt_path) + + dry_run_lines = prune_worktrees(cwd=git_repo, dry_run=True) + assert dry_run_lines + assert any("stale" in line for line in dry_run_lines) + assert any(wt.get("branch") == "stale" for wt in list_worktrees(cwd=git_repo)) + + prune_worktrees(cwd=git_repo) + assert all(wt.get("branch") != "stale" for wt in list_worktrees(cwd=git_repo)) + + def test_get_default_branch_no_remote(git_repo): # No remote configured — should fall back to the primary worktree's branch branch = get_default_branch(cwd=git_repo) diff --git a/uv.lock b/uv.lock index 3c1dc2e..6631cf7 100644 --- a/uv.lock +++ b/uv.lock @@ -100,6 +100,7 @@ name = "git-worm" version = "0.6.0" source = { editable = "." } dependencies = [ + { name = "gitpython" }, { name = "xclif" }, ] @@ -110,7 +111,10 @@ dev = [ ] [package.metadata] -requires-dist = [{ name = "xclif", specifier = ">=0.6.1" }] +requires-dist = [ + { name = "gitpython", specifier = ">=3.1.46" }, + { name = "xclif", specifier = ">=0.6.1" }, +] [package.metadata.requires-dev] dev = [ @@ -118,6 +122,30 @@ dev = [ { name = "pytest-cov", specifier = ">=7.1.0" }, ] +[[package]] +name = "gitdb" +version = "4.0.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "smmap" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/94/63b0fc47eb32792c7ba1fe1b694daec9a63620db1e313033d18140c2320a/gitdb-4.0.12.tar.gz", hash = "sha256:5ef71f855d191a3326fcfbc0d5da835f26b13fbcba60c32c21091c349ffdb571", size = 394684, upload-time = "2025-01-02T07:20:46.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" }, +] + +[[package]] +name = "gitpython" +version = "3.1.62" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "gitdb" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/db/3ca813cbacb23ab6fe46ff38a9b5ef8e73e970c8051f2ce903aacafe0446/gitpython-3.1.62.tar.gz", hash = "sha256:1791de66309bc0c7cfca40bf8d2e3de7ca091cbf94e6051be1ad0722c61062af", size = 231728, upload-time = "2026-09-07T02:57:21.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/0b/29d7965215f8ef830a7ca1f42997fe13e5693d85e9edb18f938d063ef5f2/gitpython-3.1.62-py3-none-any.whl", hash = "sha256:7002251225e10e29d2e1f49e6532613fe5d5d9f0b6f1f02997a52b38fe56899e", size = 222753, upload-time = "2026-09-07T02:57:19.762Z" }, +] + [[package]] name = "iniconfig" version = "2.3.0" @@ -227,6 +255,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/25/b208c5683343959b670dc001595f2f3737e051da617f66c31f7c4fa93abc/rich-14.3.3-py3-none-any.whl", hash = "sha256:793431c1f8619afa7d3b52b2cdec859562b950ea0d4b6b505397612db8d5362d", size = 310458, upload-time = "2026-02-19T17:23:13.732Z" }, ] +[[package]] +name = "smmap" +version = "5.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/ea/49c993d6dfdd7338c9b1000a0f36817ed7ec84577ae2e52f890d1a4ff909/smmap-5.0.3.tar.gz", hash = "sha256:4d9debb8b99007ae47165abc08670bd74cb74b5227dda7f643eccc4e9eb5642c", size = 22506, upload-time = "2026-03-09T03:43:26.1Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, +] + [[package]] name = "tomlkit" version = "0.14.0"