Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ classifiers = [
"Topic :: Software Development :: Version Control :: Git",
]
dependencies = [
"gitpython>=3.1.46",
"xclif>=0.6.1",
]

Expand Down
55 changes: 25 additions & 30 deletions src/git_worm/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand All @@ -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]:
Expand All @@ -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
Expand All @@ -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)
Expand Down
20 changes: 10 additions & 10 deletions src/git_worm/routes/prune.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down Expand Up @@ -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]] = []
Expand Down Expand Up @@ -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}")

Expand Down
124 changes: 57 additions & 67 deletions src/git_worm/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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"]
Expand All @@ -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 []
18 changes: 18 additions & 0 deletions tests/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
20 changes: 20 additions & 0 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading