1use std::fs;
11use std::io::Write as _;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15const UNREGISTERED_GITDIR_NAME: &str = "fallow-audit-unregistered";
17
18const LEGACY_UNREGISTERED_GITDIR_STUB: &str = "gitdir: fallow-audit-unregistered\n";
22
23const FALLOW_BASE_WORKTREE_PREFIX: &str = "fallow-audit-base-";
25
26#[must_use]
40pub fn unregistered_gitdir_stub(snapshot: &Path) -> String {
41 let gitdir = snapshot.join(".git").join(UNREGISTERED_GITDIR_NAME);
42 format!("gitdir: {}\n", gitdir.display())
43}
44
45#[must_use]
48pub fn is_unregistered_gitdir_stub(snapshot: &Path, contents: &str) -> bool {
49 if contents == LEGACY_UNREGISTERED_GITDIR_STUB {
50 return true;
51 }
52 let Some(gitdir) = parse_worktree_gitdir(contents) else {
53 return false;
54 };
55 let Some(gitfile) = gitdir
56 .file_name()
57 .is_some_and(|name| name == UNREGISTERED_GITDIR_NAME)
58 .then(|| gitdir.parent())
59 .flatten()
60 else {
61 return false;
62 };
63 if gitfile.file_name().is_none_or(|name| name != ".git") {
64 return false;
65 }
66 gitfile
67 .parent()
68 .is_some_and(|owner| owner == snapshot || same_existing_path(owner, snapshot))
69}
70
71fn same_existing_path(left: &Path, right: &Path) -> bool {
72 match (dunce::canonicalize(left), dunce::canonicalize(right)) {
73 (Ok(left), Ok(right)) => left == right,
74 _ => false,
75 }
76}
77
78#[must_use]
83pub fn enclosing_unregistered_snapshot(dir: &Path) -> Option<PathBuf> {
84 let dir = std::path::absolute(dir).ok()?;
85 for candidate in dir.ancestors() {
86 let gitfile = candidate.join(".git");
87 let Ok(metadata) = fs::symlink_metadata(&gitfile) else {
88 continue;
89 };
90 if !is_regular_file(&metadata) {
91 return None;
92 }
93 let contents = fs::read_to_string(&gitfile).ok()?;
94 return is_unregistered_gitdir_stub(candidate, &contents).then(|| candidate.to_path_buf());
95 }
96 None
97}
98
99pub fn confine_git_to_host(command: &mut Command, cwd: &Path) {
108 let Some(snapshot) = enclosing_unregistered_snapshot(cwd) else {
109 return;
110 };
111 command.env(
112 "GIT_DIR",
113 snapshot.join(".git").join(UNREGISTERED_GITDIR_NAME),
114 );
115 if let Some(parent) = snapshot.parent() {
116 command.env("GIT_CEILING_DIRECTORIES", parent);
117 }
118}
119
120pub fn deregister_base_worktree(repo_root: &Path, path: &Path) -> std::io::Result<()> {
136 if !path.exists() {
137 return Ok(());
138 }
139 let gitfile = path.join(".git");
140 let metadata = fs::symlink_metadata(&gitfile)?;
141 if !is_regular_file(&metadata) {
142 return Err(std::io::Error::new(
143 std::io::ErrorKind::InvalidData,
144 "refusing to deregister through a non-file audit worktree .git entry",
145 ));
146 }
147 let contents = fs::read_to_string(&gitfile)?;
148 if is_unregistered_gitdir_stub(path, &contents) {
149 if contents == unregistered_gitdir_stub(path) {
150 return Ok(());
151 }
152 return write_unregistered_gitdir_stub(&gitfile);
153 }
154 let Some(admin_dir) = trusted_base_worktree_admin_dir(repo_root, path) else {
155 return Err(std::io::Error::new(
156 std::io::ErrorKind::InvalidData,
157 "refusing to deregister an unverified audit worktree admin entry",
158 ));
159 };
160 match fs::remove_dir_all(&admin_dir) {
161 Ok(()) => {}
162 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
163 Err(err) => return Err(err),
164 }
165 write_unregistered_gitdir_stub(&gitfile)
166}
167
168pub fn write_unregistered_gitdir_stub(gitfile: &Path) -> std::io::Result<()> {
176 let mut options = fs::OpenOptions::new();
177 options.write(true).truncate(true);
178 match fs::symlink_metadata(gitfile) {
179 Ok(metadata) if is_regular_file(&metadata) => {}
180 Ok(_) => {
181 return Err(std::io::Error::new(
182 std::io::ErrorKind::InvalidData,
183 "refusing to replace non-file audit worktree .git entry",
184 ));
185 }
186 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
187 options.create_new(true);
188 }
189 Err(error) => return Err(error),
190 }
191 let snapshot = gitfile.parent().ok_or_else(|| {
192 std::io::Error::new(
193 std::io::ErrorKind::InvalidInput,
194 "audit worktree .git entry has no parent directory",
195 )
196 })?;
197 let stub = unregistered_gitdir_stub(snapshot);
198 let mut file = options.open(gitfile)?;
199 file.write_all(stub.as_bytes())?;
200 file.sync_all()
201}
202
203#[must_use]
206pub fn trusted_base_worktree_admin_dir(repo_root: &Path, path: &Path) -> Option<PathBuf> {
207 let gitfile = path.join(".git");
208 let metadata = fs::symlink_metadata(&gitfile).ok()?;
209 if !is_regular_file(&metadata) {
210 return None;
211 }
212 let contents = fs::read_to_string(&gitfile).ok()?;
213 let admin_dir = parse_worktree_gitdir(&contents)?;
214 if !is_fallow_admin_dir(&admin_dir) {
215 return None;
216 }
217 let common_dir = crate::changed_files::resolve_git_common_dir(repo_root).ok()?;
218 let worktrees_dir = dunce::canonicalize(common_dir.join("worktrees")).ok()?;
219 let admin_parent = dunce::canonicalize(admin_dir.parent()?).ok()?;
220 if admin_parent != worktrees_dir {
221 return None;
222 }
223 let backlink = fs::read_to_string(admin_dir.join("gitdir")).ok()?;
224 let expected_gitfile = dunce::canonicalize(&gitfile).ok()?;
225 let actual_gitfile = dunce::canonicalize(Path::new(backlink.trim())).ok()?;
226 (actual_gitfile == expected_gitfile).then_some(admin_dir)
227}
228
229#[must_use]
231pub fn parse_worktree_gitdir(contents: &str) -> Option<PathBuf> {
232 contents
233 .lines()
234 .find_map(|line| line.trim().strip_prefix("gitdir:"))
235 .map(|rest| PathBuf::from(rest.trim()))
236}
237
238#[expect(
239 clippy::filetype_is_file,
240 reason = "a gitfile must be a regular file, not an arbitrary non-directory"
241)]
242fn is_regular_file(metadata: &fs::Metadata) -> bool {
243 metadata.file_type().is_file()
244}
245
246fn is_fallow_admin_dir(admin_dir: &Path) -> bool {
249 admin_dir
250 .file_name()
251 .and_then(|name| name.to_str())
252 .is_some_and(|name| name.starts_with(FALLOW_BASE_WORKTREE_PREFIX))
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258 use crate::repo_refs::{TemporaryBaseWorktree, create_detached_base_worktree};
259
260 fn git(root: &Path, args: &[&str]) -> String {
261 let output = crate::git_fixture::fixture_git_command_with_identity(
262 root,
263 crate::git_fixture::FixtureIdentity::RepositoryConfig,
264 )
265 .args(args)
266 .output()
267 .expect("git command starts");
268 assert!(
269 output.status.success(),
270 "git {args:?} failed: {}",
271 String::from_utf8_lossy(&output.stderr)
272 );
273 String::from_utf8_lossy(&output.stdout).trim().to_owned()
274 }
275
276 fn committed_repo(parent: &Path) -> PathBuf {
277 let repo = parent.join("repo");
278 fs::create_dir_all(&repo).expect("create repo");
279 git(&repo, &["init", "-b", "main"]);
280 git(&repo, &["config", "user.name", "Test User"]);
281 git(&repo, &["config", "user.email", "test@example.com"]);
282 git(&repo, &["config", "commit.gpgsign", "false"]);
283 fs::write(repo.join(".gitignore"), "ignored/\n").expect("write gitignore");
284 fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
285 git(&repo, &["add", "."]);
286 git(&repo, &["commit", "-m", "initial"]);
287 repo
288 }
289
290 fn registered_worktrees(repo: &Path) -> Vec<String> {
291 git(repo, &["worktree", "list", "--porcelain"])
292 .lines()
293 .filter_map(|line| line.strip_prefix("worktree "))
294 .map(str::to_owned)
295 .collect()
296 }
297
298 #[test]
302 fn temporary_base_worktree_is_unregistered_while_it_is_in_use() {
303 let temp = tempfile::tempdir().expect("temp dir");
304 let repo = committed_repo(temp.path());
305 let before = registered_worktrees(&repo);
306
307 let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
308 .expect("temporary worktree should be created");
309
310 assert_eq!(
311 registered_worktrees(&repo),
312 before,
313 "the base snapshot must be deregistered before analysis reads it"
314 );
315 assert_eq!(
316 fs::read_to_string(worktree.path().join("tracked.txt")).expect("read tracked file"),
317 "committed\n"
318 );
319 assert_eq!(
320 fs::read_to_string(worktree.path().join(".git")).expect("read gitfile"),
321 unregistered_gitdir_stub(worktree.path()),
322 "the gitfile stays as a stub so gitignore handling still applies"
323 );
324
325 let path = worktree.path().to_path_buf();
326 drop(worktree);
327 assert!(!path.exists(), "temporary worktree must clean up on drop");
328 assert_eq!(registered_worktrees(&repo), before);
329 }
330
331 #[test]
332 fn registered_snapshot_index_keeps_gitlinks_until_deregistration() {
333 let temp = tempfile::tempdir().expect("temp dir");
334 let repo = committed_repo(temp.path());
335 let gitlink_commit = git(&repo, &["rev-parse", "HEAD"]);
336 let cacheinfo = format!("160000,{gitlink_commit},vendor/submodule");
337 git(&repo, &["update-index", "--add", "--cacheinfo", &cacheinfo]);
338 git(&repo, &["commit", "-m", "gitlink"]);
339 let destination = temp.path().join("fallow-audit-base-index-probe");
340
341 create_detached_base_worktree(&repo, &destination, "HEAD")
342 .expect("registered worktree should be created");
343 assert!(
344 git(&destination, &["ls-files", "--stage", "vendor/submodule"])
345 .starts_with(&format!("160000 {gitlink_commit} 0\t")),
346 "the linked worktree index must retain the gitlink object id"
347 );
348
349 deregister_base_worktree(&repo, &destination).expect("snapshot deregisters");
350 assert_eq!(registered_worktrees(&repo).len(), 1);
351 assert!(destination.join("tracked.txt").is_file());
352 }
353
354 #[cfg(unix)]
357 fn write_crafted_gitdir(dir: &Path, marker: &Path) {
358 fs::create_dir_all(dir.join("objects")).expect("create objects");
359 fs::create_dir_all(dir.join("refs")).expect("create refs");
360 fs::write(dir.join("objects/.keep"), "").expect("write objects keep");
361 fs::write(dir.join("refs/.keep"), "").expect("write refs keep");
362 fs::write(dir.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
363 fs::write(
364 dir.join("config"),
365 format!(
366 "[core]\n\trepositoryformatversion = 0\n\tfsmonitor = \"touch '{}'; false\"\n",
367 marker.display()
368 ),
369 )
370 .expect("write config");
371 }
372
373 #[cfg(unix)]
374 fn raw_git_status(cwd: &Path, confine: bool) -> bool {
375 let mut command = std::process::Command::new("git");
376 crate::changed_files::clear_ambient_git_env(&mut command);
377 if confine {
378 confine_git_to_host(&mut command, cwd);
379 }
380 command
381 .args(["status", "--porcelain"])
382 .current_dir(cwd)
383 .output()
384 .expect("git command starts")
385 .status
386 .success()
387 }
388
389 #[cfg(unix)]
393 #[test]
394 fn crafted_gitdirs_in_the_base_commit_are_never_read() {
395 let temp = tempfile::tempdir().expect("temp dir");
396 let repo = committed_repo(temp.path());
397 let marker = temp.path().join("fsmonitor-ran");
398 write_crafted_gitdir(&repo.join(UNREGISTERED_GITDIR_NAME), &marker);
399 write_crafted_gitdir(&repo.join("pkg"), &marker);
400 git(&repo, &["add", "-f", "."]);
401 git(&repo, &["commit", "-m", "crafted"]);
402
403 let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
404 .expect("temporary worktree should be created");
405 let snapshot = worktree.path();
406 assert!(
407 snapshot
408 .join(UNREGISTERED_GITDIR_NAME)
409 .join("config")
410 .is_file()
411 );
412
413 assert!(
414 !raw_git_status(snapshot, false),
415 "Git at the snapshot root must not find a repository"
416 );
417 assert!(!raw_git_status(&snapshot.join("pkg"), true));
418 assert!(!crate::churn::is_git_repo(snapshot));
419 assert!(!crate::churn::is_git_repo(&snapshot.join("pkg")));
420 assert!(
421 crate::changed_files::resolve_git_toplevel(&snapshot.join("pkg")).is_err(),
422 "changed-file probes must not find the nested bare repository"
423 );
424 for dir in [snapshot.to_path_buf(), snapshot.join("pkg")] {
425 let status = crate::git_env::git_command(&dir)
426 .args(["status", "--porcelain"])
427 .output()
428 .expect("git command starts")
429 .status;
430 assert!(
431 !status.success(),
432 "the shared Git wrapper found a repository"
433 );
434 }
435 assert!(
436 !marker.exists(),
437 "a config from the base commit ran a command"
438 );
439 }
440
441 #[cfg(unix)]
444 #[test]
445 fn shared_git_wrapper_refuses_implicit_bare_repositories() {
446 let temp = tempfile::tempdir().expect("temp dir");
447 let repo = committed_repo(temp.path());
448 let marker = temp.path().join("fsmonitor-ran");
449 let bare = temp.path().join("bare");
450 write_crafted_gitdir(&bare, &marker);
451 fs::create_dir_all(repo.join("sub")).expect("create subdirectory");
452
453 let run = |dir: &Path| {
454 crate::git_env::git_command(dir)
455 .args(["status", "--porcelain"])
456 .output()
457 .expect("git command starts")
458 .status
459 .success()
460 };
461
462 assert!(!run(&bare), "an implicit bare repository must be refused");
463 assert!(!marker.exists());
464 assert!(run(&repo), "an ordinary checkout must keep working");
465 assert!(
466 run(&repo.join("sub")),
467 "a checkout subdirectory must keep working"
468 );
469 }
470
471 #[test]
475 fn bare_clone_worktree_layout_keeps_working() {
476 let temp = tempfile::tempdir().expect("temp dir");
477 let source = committed_repo(temp.path());
478 let bare = temp.path().join("bare.git");
479 let linked = temp.path().join("linked");
480 let parent = temp.path();
481 git(
482 parent,
483 &[
484 "clone",
485 "--quiet",
486 "--bare",
487 source.to_str().expect("UTF-8"),
488 "bare.git",
489 ],
490 );
491 git(
492 &bare,
493 &[
494 "worktree",
495 "add",
496 "--quiet",
497 linked.to_str().expect("UTF-8"),
498 "main",
499 ],
500 );
501 assert!(
502 fs::symlink_metadata(linked.join(".git"))
503 .expect("gitfile")
504 .is_file()
505 );
506
507 let toplevel = crate::git_env::git_command(&linked)
508 .args(["rev-parse", "--show-toplevel"])
509 .output()
510 .expect("git command starts");
511 assert!(toplevel.status.success(), "{toplevel:?}");
512 assert!(crate::churn::is_git_repo(&linked));
513 assert!(crate::changed_files::resolve_git_toplevel(&linked).is_ok());
514
515 let worktree = TemporaryBaseWorktree::create(&linked, "HEAD", &[])
516 .expect("base snapshot from a bare-clone worktree");
517 assert!(worktree.path().join("tracked.txt").is_file());
518 assert_eq!(
519 registered_worktrees(&bare).len(),
520 2,
521 "only the bare clone and its linked worktree stay registered"
522 );
523 }
524
525 #[test]
528 fn unregistered_snapshot_keeps_gitignore_handling() {
529 let temp = tempfile::tempdir().expect("temp dir");
530 let repo = committed_repo(temp.path());
531 let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
532 .expect("temporary worktree should be created");
533 fs::create_dir_all(worktree.path().join("ignored")).expect("create ignored dir");
534 fs::write(worktree.path().join("ignored/skip.ts"), "").expect("write ignored file");
535
536 let walked: Vec<PathBuf> = ignore::WalkBuilder::new(worktree.path())
537 .build()
538 .filter_map(Result::ok)
539 .map(|entry| entry.into_path())
540 .collect();
541
542 assert!(walked.iter().any(|path| path.ends_with("tracked.txt")));
543 assert!(
544 !walked.iter().any(|path| path.ends_with("ignored/skip.ts")),
545 "the base walk must honor .gitignore: {walked:?}"
546 );
547 assert_eq!(
548 enclosing_unregistered_snapshot(&worktree.path().join("ignored")).as_deref(),
549 Some(worktree.path())
550 );
551 }
552}