anodizer_core/git/
worktree.rs1use anyhow::{Context as _, Result};
18use std::path::{Path, PathBuf};
19use std::process::Command;
20
21pub struct Worktree {
22 repo_root: PathBuf,
23 path: PathBuf,
24}
25
26impl Worktree {
27 pub fn add(repo_root: &Path, path: &Path, commit: &str) -> Result<Self> {
50 if path.to_string_lossy().chars().any(char::is_whitespace) {
51 anyhow::bail!(
52 "git worktree path {} contains whitespace; pick a scratch directory \
53 without spaces or tabs (the determinism harness composes this path \
54 into RUSTFLAGS via `--remap-path-prefix`, which is space-delimited \
55 with no quoting support)",
56 path.display()
57 );
58 }
59 let out = Command::new("git")
60 .arg("-C")
61 .arg(repo_root)
62 .args(["worktree", "add", "--detach"])
63 .arg(path)
64 .arg(commit)
65 .output()
66 .with_context(|| format!("spawn 'git worktree add' for {}", path.display()))?;
67 if !out.status.success() {
68 anyhow::bail!(
69 "git worktree add failed (exit {:?}) for {}: {}",
70 out.status.code(),
71 path.display(),
72 String::from_utf8_lossy(&out.stderr).trim()
73 );
74 }
75 Ok(Self {
76 repo_root: repo_root.to_path_buf(),
77 path: path.to_path_buf(),
78 })
79 }
80
81 pub fn path(&self) -> &Path {
83 &self.path
84 }
85}
86
87impl Drop for Worktree {
88 fn drop(&mut self) {
89 match Command::new("git")
98 .arg("-C")
99 .arg(&self.repo_root)
100 .args(["worktree", "remove", "--force"])
101 .arg(&self.path)
102 .output()
103 {
104 Ok(out) if out.status.success() => {}
105 Ok(out) => {
106 tracing::warn!(
107 "git worktree remove '{}' failed during Drop (exit {:?}: {}); \
108 run `git worktree prune` in the parent repo to reap the stale entry",
109 self.path.display(),
110 out.status.code(),
111 String::from_utf8_lossy(&out.stderr).trim(),
112 );
113 }
114 Err(err) => {
115 tracing::warn!(
116 "failed to spawn 'git worktree remove' for '{}' during Drop ({err}); \
117 run `git worktree prune` in the parent repo to reap the stale entry",
118 self.path.display(),
119 );
120 }
121 }
122 }
123}
124
125#[cfg(test)]
126mod tests {
127 use super::*;
128 use std::process::Command;
129 use tempfile::TempDir;
130
131 fn init_repo() -> TempDir {
132 let dir = tempfile::tempdir().unwrap();
133 Command::new("git")
134 .arg("-C")
135 .arg(dir.path())
136 .arg("init")
137 .output()
138 .unwrap();
139 Command::new("git")
140 .arg("-C")
141 .arg(dir.path())
142 .args(["config", "user.email", "test@example.com"])
143 .output()
144 .unwrap();
145 Command::new("git")
146 .arg("-C")
147 .arg(dir.path())
148 .args(["config", "user.name", "test"])
149 .output()
150 .unwrap();
151 std::fs::write(dir.path().join("a.txt"), "hello").unwrap();
152 Command::new("git")
153 .arg("-C")
154 .arg(dir.path())
155 .args(["add", "a.txt"])
156 .output()
157 .unwrap();
158 Command::new("git")
159 .arg("-C")
160 .arg(dir.path())
161 .args(["commit", "-m", "init"])
162 .output()
163 .unwrap();
164 dir
165 }
166
167 #[test]
168 fn worktree_add_creates_directory_at_given_path() {
169 let repo = init_repo();
170 let wt_dir = tempfile::tempdir().unwrap();
171 let wt = Worktree::add(repo.path(), &wt_dir.path().join("wt1"), "HEAD").unwrap();
172 assert!(wt.path().exists());
173 assert!(wt.path().join("a.txt").exists());
174 }
175
176 #[test]
177 fn worktree_drop_removes_directory_and_prunes() {
178 let repo = init_repo();
179 let wt_dir = tempfile::tempdir().unwrap();
180 let path: PathBuf;
181 {
182 let wt = Worktree::add(repo.path(), &wt_dir.path().join("wt2"), "HEAD").unwrap();
183 path = wt.path().to_path_buf();
184 assert!(path.exists());
185 } assert!(!path.exists(), "worktree path persisted after Drop");
188 }
189
190 #[test]
191 fn worktree_add_for_explicit_commit_checks_out_that_commit() {
192 let repo = init_repo();
193 let out = Command::new("git")
195 .arg("-C")
196 .arg(repo.path())
197 .args(["rev-parse", "HEAD"])
198 .output()
199 .unwrap();
200 let head_hash = String::from_utf8(out.stdout).unwrap().trim().to_string();
201 let wt_dir = tempfile::tempdir().unwrap();
202 let wt = Worktree::add(repo.path(), &wt_dir.path().join("wt3"), &head_hash).unwrap();
203 let out = Command::new("git")
205 .arg("-C")
206 .arg(wt.path())
207 .args(["rev-parse", "HEAD"])
208 .output()
209 .unwrap();
210 let wt_head = String::from_utf8(out.stdout).unwrap().trim().to_string();
211 assert_eq!(wt_head, head_hash);
212 }
213
214 #[test]
215 fn worktree_concurrent_adds_do_not_collide() {
216 let repo = init_repo();
217 let wt_dir = tempfile::tempdir().unwrap();
218 let wt1 = Worktree::add(repo.path(), &wt_dir.path().join("wt-a"), "HEAD").unwrap();
219 let wt2 = Worktree::add(repo.path(), &wt_dir.path().join("wt-b"), "HEAD").unwrap();
220 assert_ne!(wt1.path(), wt2.path());
221 assert!(wt1.path().exists());
222 assert!(wt2.path().exists());
223 }
224
225 #[test]
226 fn worktree_add_surfaces_stderr_on_failure() {
227 let repo = init_repo();
231 let wt_dir = tempfile::tempdir().unwrap();
232 let result = Worktree::add(
233 repo.path(),
234 &wt_dir.path().join("wt-bad"),
235 "this-ref-does-not-exist-anywhere",
236 );
237 let err = match result {
238 Err(e) => e,
239 Ok(_) => panic!("invalid commit must error"),
240 };
241 let msg = err.to_string();
242 assert!(
243 msg.contains("fatal:")
244 || msg.contains("invalid reference")
245 || msg.contains("not a valid"),
246 "error must include captured git stderr; got: {msg}",
247 );
248 assert!(
249 msg.contains("git worktree add failed"),
250 "error must still identify the failing operation; got: {msg}",
251 );
252 }
253
254 #[test]
255 fn worktree_add_rejects_whitespace_in_path() {
256 let repo = init_repo();
260 let wt_dir = tempfile::tempdir().unwrap();
261 let bad_path = wt_dir.path().join("wt with spaces");
262 let err = match Worktree::add(repo.path(), &bad_path, "HEAD") {
263 Err(e) => e,
264 Ok(_) => panic!("whitespace path must be rejected"),
265 };
266 let msg = err.to_string();
267 assert!(
268 msg.contains("whitespace"),
269 "error must explain the whitespace constraint; got: {msg}"
270 );
271 assert!(
272 msg.contains("RUSTFLAGS"),
273 "error must point at the downstream RUSTFLAGS reason; got: {msg}"
274 );
275 }
276
277 #[test]
278 fn worktree_drop_does_not_panic_when_path_already_removed() {
279 let repo = init_repo();
285 let wt_dir = tempfile::tempdir().unwrap();
286 let wt = Worktree::add(repo.path(), &wt_dir.path().join("wt-vanish"), "HEAD").unwrap();
287 let path = wt.path().to_path_buf();
288 std::fs::remove_dir_all(&path).expect("manual remove should succeed");
289 assert!(!path.exists());
290 drop(wt);
292 }
293}