1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"""Git worktree listing and mutation via the git CLI."""
from __future__ import annotations
import subprocess
from dataclasses import dataclass
from pathlib import Path
from pygit2 import Repository
from pygittools.hooks_push import git_executable
@dataclass(frozen=True, slots=True)
class WorktreeInfo:
path: Path
head: str | None
branch: str | None
bare: bool
detached: bool
locked: str | None
prunable: str | None
def list_worktrees(repo: Repository) -> tuple[list[WorktreeInfo], str | None]:
workdir = repo.workdir
if workdir is None:
return [], "Repository has no working directory"
result = subprocess.run(
[git_executable(), "worktree", "list", "--porcelain"],
cwd=workdir,
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
output = (result.stderr or result.stdout or "git worktree list failed").strip()
return [], output.splitlines()[-1]
return parse_worktree_porcelain(result.stdout), None
def parse_worktree_porcelain(text: str) -> list[WorktreeInfo]:
entries: list[WorktreeInfo] = []
block: list[str] = []
for raw_line in text.splitlines():
line = raw_line.strip()
if not line:
if block:
entries.append(_block_to_info(block))
block = []
continue
if line.startswith("worktree "):
if block:
entries.append(_block_to_info(block))
block = [line]
else:
block.append(line)
if block:
entries.append(_block_to_info(block))
return entries
def _block_to_info(lines: list[str]) -> WorktreeInfo:
path = Path(lines[0].removeprefix("worktree ").strip())
head: str | None = None
branch: str | None = None
bare = False
detached = False
locked: str | None = None
prunable: str | None = None
for line in lines[1:]:
if line == "bare":
bare = True
elif line == "detached":
detached = True
elif line == "locked":
locked = ""
elif line.startswith("locked "):
locked = line.removeprefix("locked ").strip()
elif line == "prunable":
prunable = ""
elif line.startswith("prunable "):
prunable = line.removeprefix("prunable ").strip()
elif line.startswith("HEAD "):
head = line.removeprefix("HEAD ").strip()
elif line.startswith("branch "):
ref = line.removeprefix("branch ").strip()
branch = ref.removeprefix("refs/heads/") if ref.startswith("refs/heads/") else ref
return WorktreeInfo(
path=path,
head=head,
branch=branch,
bare=bare,
detached=detached,
locked=locked,
prunable=prunable,
)
def add_worktree(repo: Repository, path: Path, branch: str | None) -> tuple[bool, str]:
workdir = repo.workdir
if workdir is None:
return False, "Repository has no working directory"
trimmed_branch = (branch or "").strip()
target = _resolve_worktree_path(workdir, path)
cmd = [git_executable(), "worktree", "add"]
if trimmed_branch:
local = {name for name in repo.branches.local}
if trimmed_branch in local:
cmd.extend([str(target), trimmed_branch])
else:
cmd.extend(["-b", trimmed_branch, str(target)])
else:
cmd.append(str(target))
result = subprocess.run(
cmd,
cwd=workdir,
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
return True, ""
output = (result.stderr or result.stdout or "git worktree add failed").strip()
if not output:
return False, "git worktree add failed"
return False, output.splitlines()[-1]
def remove_worktree(repo: Repository, path: Path, *, force: bool) -> tuple[bool, str]:
workdir = repo.workdir
if workdir is None:
return False, "Repository has no working directory"
cmd = [git_executable(), "worktree", "remove"]
if force:
cmd.append("--force")
cmd.append(str(path.resolve()))
result = subprocess.run(
cmd,
cwd=workdir,
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
return True, ""
output = (result.stderr or result.stdout or "git worktree remove failed").strip()
if not output:
return False, "git worktree remove failed"
return False, output.splitlines()[-1]
def _resolve_worktree_path(workdir: str | Path, path: Path) -> Path:
if path.is_absolute():
return path
return (Path(workdir) / path).resolve()