1use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use crate::error::WorktreeError;
9
10#[derive(Debug, Clone)]
12pub struct WorktreeEntry {
13 pub path: PathBuf,
15 pub head: String,
17 pub branch: Option<String>,
19 pub detached: bool,
21 pub locked: bool,
23 pub prunable: bool,
25}
26
27pub struct GitWorktree {
29 repo_root: PathBuf,
30}
31
32impl GitWorktree {
33 pub fn new(repo_root: impl Into<PathBuf>) -> Self {
35 Self {
36 repo_root: repo_root.into(),
37 }
38 }
39
40 pub fn add(&self, path: &Path, commit: &str, detach: bool) -> Result<(), WorktreeError> {
48 let mut args = vec!["worktree", "add"];
49 if detach {
50 args.push("--detach");
51 }
52 let path_str = path
53 .to_str()
54 .ok_or_else(|| WorktreeError::InvalidPath(path.display().to_string()))?;
55 args.push(path_str);
56 args.push(commit);
57
58 self.run(&args)
59 }
60
61 pub fn list(&self) -> Result<Vec<WorktreeEntry>, WorktreeError> {
63 let output = self.run_output(&["worktree", "list", "--porcelain"])?;
64 parse_porcelain_output(&output)
65 }
66
67 pub fn remove(&self, path: &Path, force: bool) -> Result<(), WorktreeError> {
74 let mut args = vec!["worktree", "remove"];
75 if force {
76 args.push("--force");
77 }
78 let path_str = path
79 .to_str()
80 .ok_or_else(|| WorktreeError::InvalidPath(path.display().to_string()))?;
81 args.push(path_str);
82
83 self.run(&args)
84 }
85
86 pub fn prune(&self) -> Result<String, WorktreeError> {
88 self.run_output(&["worktree", "prune", "--verbose"])
89 }
90
91 fn run(&self, args: &[&str]) -> Result<(), WorktreeError> {
93 let output = Command::new("git")
94 .args(args)
95 .current_dir(&self.repo_root)
96 .output()?;
97
98 if !output.status.success() {
99 let stderr = String::from_utf8_lossy(&output.stderr);
100 return Err(WorktreeError::GitFailed(stderr.trim().to_string()));
101 }
102 Ok(())
103 }
104
105 fn run_output(&self, args: &[&str]) -> Result<String, WorktreeError> {
107 let output = Command::new("git")
108 .args(args)
109 .current_dir(&self.repo_root)
110 .output()?;
111
112 if !output.status.success() {
113 let stderr = String::from_utf8_lossy(&output.stderr);
114 return Err(WorktreeError::GitFailed(stderr.trim().to_string()));
115 }
116 Ok(String::from_utf8_lossy(&output.stdout).to_string())
117 }
118}
119
120fn parse_porcelain_output(output: &str) -> Result<Vec<WorktreeEntry>, WorktreeError> {
133 let mut entries = Vec::new();
134 let mut current: Option<WorktreeEntry> = None;
135
136 for line in output.lines() {
137 let line = line.trim();
138 if line.is_empty() {
139 if let Some(entry) = current.take() {
140 entries.push(entry);
141 }
142 continue;
143 }
144
145 if let Some(path) = line.strip_prefix("worktree ") {
146 if let Some(entry) = current.take() {
148 entries.push(entry);
149 }
150 current = Some(WorktreeEntry {
151 path: PathBuf::from(path),
152 head: String::new(),
153 branch: None,
154 detached: false,
155 locked: false,
156 prunable: false,
157 });
158 } else if let Some(head) = line.strip_prefix("HEAD ") {
159 if let Some(ref mut entry) = current {
160 entry.head = head.to_string();
161 }
162 } else if let Some(branch) = line.strip_prefix("branch ") {
163 if let Some(ref mut entry) = current {
164 entry.branch = Some(branch.to_string());
165 }
166 } else if line == "detached" {
167 if let Some(ref mut entry) = current {
168 entry.detached = true;
169 }
170 } else if line == "locked" || line.starts_with("locked ") {
171 if let Some(ref mut entry) = current {
172 entry.locked = true;
173 }
174 } else if line == "prunable" || line.starts_with("prunable ") {
175 if let Some(ref mut entry) = current {
176 entry.prunable = true;
177 }
178 }
179 }
180
181 if let Some(entry) = current {
183 entries.push(entry);
184 }
185
186 Ok(entries)
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 #[test]
194 fn test_parse_porcelain_single_main() {
195 let output = r#"worktree /home/user/repo
196HEAD abc123def456
197branch refs/heads/main
198"#;
199
200 let entries = parse_porcelain_output(output).unwrap();
201 assert_eq!(entries.len(), 1);
202 assert_eq!(entries[0].path, PathBuf::from("/home/user/repo"));
203 assert_eq!(entries[0].head, "abc123def456");
204 assert_eq!(entries[0].branch, Some("refs/heads/main".to_string()));
205 assert!(!entries[0].detached);
206 assert!(!entries[0].locked);
207 }
208
209 #[test]
210 fn test_parse_porcelain_with_detached() {
211 let output = r#"worktree /home/user/repo
212HEAD abc123def456
213branch refs/heads/main
214
215worktree /home/user/repo/.grite/worktrees/s-20250117-a2f9
216HEAD def456abc123
217detached
218"#;
219
220 let entries = parse_porcelain_output(output).unwrap();
221 assert_eq!(entries.len(), 2);
222
223 assert_eq!(entries[0].path, PathBuf::from("/home/user/repo"));
224 assert!(!entries[0].detached);
225
226 assert_eq!(
227 entries[1].path,
228 PathBuf::from("/home/user/repo/.grite/worktrees/s-20250117-a2f9")
229 );
230 assert!(entries[1].detached);
231 assert!(entries[1].branch.is_none());
232 }
233
234 #[test]
235 fn test_parse_porcelain_with_locked() {
236 let output = r#"worktree /home/user/repo/.grite/worktrees/test
237HEAD abc123
238detached
239locked
240"#;
241
242 let entries = parse_porcelain_output(output).unwrap();
243 assert_eq!(entries.len(), 1);
244 assert!(entries[0].locked);
245 }
246
247 #[test]
248 fn test_parse_porcelain_empty() {
249 let output = "";
250 let entries = parse_porcelain_output(output).unwrap();
251 assert!(entries.is_empty());
252 }
253}