voom 0.14.1

Fast, safe, parallel build-artifact pruning across every major language ecosystem
Documentation
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! Finding repositories, and proving what each one is.
//!
//! Three questions live here, and they are the ones the safety argument rests on:
//!
//! 1. **Where are the repositories?** A sweep answers this for free — the artifact walker meets
//!    `.git` and prunes it, so [`repository_at`] collects the path at that point. The subcommand
//!    walks for itself, ignore-blind for the same reason `scan::configure` is.
//! 2. **Which repository is this, really?** A `.git` file is a linked worktree, a submodule, or a
//!    `--separate-git-dir` checkout, and telling them apart is what keeps voom from running
//!    housekeeping four times over one object store — or from folding a submodule into its
//!    superproject and never pruning it at all.
//! 3. **May voom touch it?** The protected denylist and containment, and whether a git operation
//!    is half-finished inside.

use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use ignore::{WalkBuilder, WalkState};

use super::{DOT_GIT, GitPruneOptions, Skipped};
use crate::caches::CacheRoots;
use crate::classify::{Classifier, Selection, Verdict, is_dependency_dir};
use crate::delete::{PROTECTED_PATHS, paths_equal};
use crate::scan::NEVER_DESCEND;

/// A git control file (`.git`, `commondir`) is a short path or a `gitdir:` line; anything larger
/// is not one, and a FIFO or an enormous file at that path must not block or exhaust the read.
const CONTROL_FILE_MAX_BYTES: u64 = 4096;

/// Files and directories inside a git directory that mean an operation is half-finished.
///
/// Running `gc` under somebody's paused rebase is the avoidable harm here: these are exactly the
/// states where the user still intends to `--continue`, and where the objects holding their work
/// are reachable only from files git treats as scratch.
const IN_PROGRESS_MARKERS: &[&str] = &[
    "rebase-merge",
    "rebase-apply",
    "MERGE_HEAD",
    "CHERRY_PICK_HEAD",
    "REVERT_HEAD",
    "BISECT_LOG",
];

/// The working tree of the repository a walker entry proves, if that entry is a `.git`.
///
/// **This is how a sweep discovers repositories.** The artifact walker already has the entry in
/// hand — `.git` is in [`NEVER_DESCEND`], so it is examined and then pruned — and collecting the
/// path at that point costs one name comparison and no syscall. A second full walk over `$HOME`
/// to find the same directories would roughly double voom's headline number, which is the one
/// thing `perf-discipline` will not trade.
///
/// Both shapes count. A `.git` directory is a main repository; a `.git` *file* is a linked
/// worktree, a submodule, or a `--separate-git-dir` checkout, and [`resolve_all`] decides which.
/// A symlinked `.git` is not followed, for the same reason nothing else in voom is.
#[must_use]
pub fn repository_at<'a>(name: &OsStr, path: &'a Path, is_symlink: bool) -> Option<&'a Path> {
    if is_symlink || name != OsStr::new(DOT_GIT) {
        return None;
    }
    path.parent()
}

/// The standalone discovery walk, for the subcommand.
///
/// Configured ignore-blind for the same reason `scan::configure` is
/// (`adrs/0005-traversal-and-parallelism.md`): a repository very often sits inside a directory
/// some `.gitignore` mentions, and a walker that read ignore files would find a fraction of them.
pub(super) fn repositories(options: &GitPruneOptions) -> Vec<PathBuf> {
    let mut found = Vec::new();
    for root in &options.roots {
        walk(root, options, &mut found);
    }
    found
}

fn walk(root: &Path, options: &GitPruneOptions, into: &mut Vec<PathBuf>) {
    let caches = CacheRoots::for_root(root, &[]);
    // Shared by reference: every worker asks the same set, and `&CacheRoots` is `Copy`, which is
    // what lets the per-thread visitor be a `move` closure without cloning the set per thread.
    let caches = &caches;
    let classifier = prune_classifier();
    let classifier = classifier.as_ref();
    let (sender, receiver) = std::sync::mpsc::channel();

    let builder = walk_builder(root, options);

    builder.build_parallel().run(|| {
        let sender = sender.clone();
        Box::new(move |result| {
            let Ok(entry) = result else {
                // A directory that cannot be read holds no repository voom can act on, and here
                // the walk is a means rather than the subject — unlike a sweep, where a
                // permission failure is a finding the report owes the reader.
                return WalkState::Continue;
            };
            let path = entry.path();
            if !entry.file_type().is_some_and(|file_type| file_type.is_dir()) {
                return WalkState::Continue;
            }
            if options.exclude.matched(path).is_some() || caches.contains(path) || is_pruned(entry.file_name()) {
                return WalkState::Skip;
            }
            if entry.depth() > 0
                && classifier
                    .is_some_and(|classifier| matches!(classifier.classify(root, path, true), Verdict::Artifact(_)))
            {
                return WalkState::Skip;
            }
            // One `lstat` per directory is the price of pruning a linked-worktree checkout before
            // descending into it. Deciding from the walker's own `.git` entry would fire only once
            // the directory had already been entered — exactly the walk this prunes away — so the
            // probe is done at the directory, and it is the cost the pruning buys back many times
            // over on a monorepo's worktrees.
            match probe(path) {
                Probe::None => WalkState::Continue,
                Probe::Repository => {
                    let _ = sender.send(path.to_path_buf());
                    WalkState::Continue
                }
                // Reported, but its checkout is not searched: it shares the main repository's
                // object store, so everything housekeeping needs is already known, and a
                // monorepo checkout holds more files than every other directory put together.
                Probe::LinkedWorktree => {
                    let _ = sender.send(path.to_path_buf());
                    WalkState::Skip
                }
            }
        })
    });

    drop(sender);
    into.extend(receiver);
}

/// The sweep's own classifier, if it can be built, for pruning build output during the walk.
fn prune_classifier() -> Option<Classifier> {
    // The sweep's own classifier, so the walk prunes build output exactly where a *default* sweep
    // would remove it: a `target/` is skipped only beside the marker that proves it. Built without
    // `.permissive()`, so an off-by-default artifact (`build/` beside a `package.json`) is not
    // pruned — a default sweep does not remove one either, and a repository nested inside it stays
    // findable. A failure here is the const catalog failing to compile its own patterns,
    // impossible without a bug in voom, and would only make the walk prune less, so it is said
    // once rather than silently ignored.
    match Classifier::new(Selection::all()) {
        Ok(classifier) => Some(classifier),
        Err(error) => {
            eprintln!("voom: git-prune: {error}; the discovery walk will not prune build output");
            None
        }
    }
}

/// The ignore-blind parallel walker over `root`, shaped by the job count and filesystem options.
fn walk_builder(root: &Path, options: &GitPruneOptions) -> WalkBuilder {
    let mut builder = WalkBuilder::new(root);
    builder
        .git_ignore(false)
        .git_global(false)
        .git_exclude(false)
        .ignore(false)
        .parents(false)
        .hidden(false)
        .follow_links(false)
        .same_file_system(options.one_file_system);
    if let Some(jobs) = options.jobs {
        builder.threads(jobs.max(1));
    }
    builder
}

/// What a directory's `.git` says about it.
enum Probe {
    /// No repository here.
    None,
    /// A main repository, a submodule or a `--separate-git-dir` checkout: its interior can hold
    /// further repositories, so the walk continues.
    Repository,
    /// A linked worktree, which the walk reports and does not enter.
    LinkedWorktree,
}

/// Classifies the `.git` entry of `dir` with one `lstat`, and one bounded read for a file.
///
/// A symlinked `.git` is not followed, for the same reason nothing else in voom is.
fn probe(dir: &Path) -> Probe {
    let dot_git = dir.join(DOT_GIT);
    let Ok(metadata) = std::fs::symlink_metadata(&dot_git) else {
        return Probe::None;
    };
    if metadata.file_type().is_dir() {
        return Probe::Repository;
    }
    if !metadata.file_type().is_file() {
        return Probe::None;
    }
    let linked = crate::io::read_capped_text(&dot_git, CONTROL_FILE_MAX_BYTES)
        .and_then(|contents| {
            contents.lines().find_map(|line| {
                line.trim()
                    .strip_prefix("gitdir:")
                    .map(|gitdir| PathBuf::from(gitdir.trim()))
            })
        })
        .is_some_and(|gitdir| is_linked_gitdir(&gitdir, dir));
    if linked {
        Probe::LinkedWorktree
    } else {
        Probe::Repository
    }
}

/// Whether a `gitdir:` target is a linked worktree's private directory.
///
/// Only a hint for the walk, never an identity: [`locate`] still reads `commondir` before voom
/// acts on anything. A directory whose parent is named `worktrees` is the default layout, and a
/// `commondir` file is what git writes for every layout, including a worktree whose
/// administration has since been deleted along with its parent.
fn is_linked_gitdir(gitdir: &Path, work_tree: &Path) -> bool {
    let absolute = if gitdir.is_absolute() {
        gitdir.to_path_buf()
    } else {
        work_tree.join(gitdir)
    };
    absolute.parent().and_then(Path::file_name) == Some(OsStr::new("worktrees")) || absolute.join("commondir").is_file()
}

/// Whether a directory is one the discovery walk never enters.
fn is_pruned(name: &OsStr) -> bool {
    NEVER_DESCEND.iter().any(|never| name == OsStr::new(never)) || is_dependency_dir(name)
}

/// A repository resolved to the form git will be run against.
///
/// The fields are private and read through accessors so nothing outside this module can assemble
/// one: a `Located` is the claim that a path passed the denylist and containment, and a struct
/// literal elsewhere would be that claim made without the checks. Same reason `delete::Verified`
/// can only be minted by `Guard::check`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Located {
    work_tree: PathBuf,
    common_dir: PathBuf,
    linked: bool,
}

impl Located {
    /// The working tree git runs in, canonicalized.
    pub(super) fn work_tree(&self) -> &Path {
        &self.work_tree
    }

    /// The repository's common directory — its object store, and the deduplication key.
    pub(super) fn common_dir(&self) -> &Path {
        &self.common_dir
    }
}

#[derive(Debug, Clone)]
pub(super) enum Resolution {
    /// The repository to act on.
    Repository(Located),
    /// A path to report and not act on.
    Refused(PathBuf, Skipped),
}

/// The sort key that puts the entry `retain` should keep first within its deduplication group.
///
/// Grouping is on the deduplication key, so everything sharing an object store is adjacent, and
/// `linked` breaks the tie: a main repository sorts before a linked worktree of the same
/// repository, so it is the one kept and the report names the checkout the user thinks of as
/// "the repository". The working tree breaks the remaining tie, for determinism.
///
/// It is a key rather than a hand-written `match` because the `match` was not a total order:
/// two repositories compared on `linked` first while a mixed pair compared on path, so a linked
/// worktree, a main repository and a refusal could form a cycle. `slice::sort_by` detects that
/// and aborts the process. A comparison derived from a tuple key cannot.
fn order_key(resolution: &Resolution) -> (&Path, bool, &Path) {
    match resolution {
        Resolution::Repository(located) => (&located.common_dir, located.linked, &located.work_tree),
        Resolution::Refused(path, _) => (path, false, path),
    }
}

/// Resolves every discovered path and keeps one entry per repository.
///
/// Deduplication is on the **common directory**, not on the working tree, because that is what
/// makes the linked-worktree rule true: four worktrees of one repository share one object store,
/// and running `gc` in each would run it four times over the same objects. A submodule has a
/// common directory of its own, so it survives deduplication and is pruned in its own right.
pub(super) fn resolve_all(work_trees: &[PathBuf], roots: &[PathBuf]) -> Vec<Resolution> {
    let protected = resolved_protected_paths();
    // `filter_map`, so a `.git` that is not a repository leaves no trace at all. A vanished one
    // is worth a line; something that was never a repository — an uninitialised `.git` holding
    // only `hooks/`, which is what a tool leaves behind when it sets a checkout up and stops —
    // is not, and reporting it every run is noise nobody can act on.
    let mut resolved: Vec<Resolution> = work_trees
        .iter()
        .filter_map(|work_tree| resolve(work_tree, roots, &protected))
        .collect();

    resolved.sort_by(|left, right| order_key(left).cmp(&order_key(right)));

    let mut seen = BTreeSet::new();
    resolved.retain(|resolution| match resolution {
        Resolution::Repository(located) => seen.insert(located.common_dir.clone()),
        Resolution::Refused(path, _) => seen.insert(path.clone()),
    });
    resolved
}

fn resolve(work_tree: &Path, roots: &[PathBuf], protected: &[PathBuf]) -> Option<Resolution> {
    let located = match locate(work_tree) {
        Ok(located) => located,
        Err(Some(detail)) => {
            return Some(Resolution::Refused(
                canonical_or_given(work_tree),
                Skipped::Unresolved { detail },
            ));
        }
        // Not a repository, and never was. Nothing to report.
        Err(None) => return None,
    };

    // Both the checkout *and* the store. Checking only the checkout let a `--separate-git-dir`
    // repository inside a scan root send `worktree prune` and `gc` at an object store outside
    // it: voom was pointed at one tree and modified another, and the report named only the
    // path that was not touched.
    let refusal = [&located.work_tree, &located.common_dir].into_iter().find_map(|path| {
        if is_protected(path, protected) {
            Some(Skipped::Protected)
        } else if contained(path, roots) {
            None
        } else {
            Some(Skipped::EscapesRoot)
        }
    });
    Some(match refusal {
        Some(reason) => Resolution::Refused(located.work_tree, reason),
        None => Resolution::Repository(located),
    })
}

/// Works out which repository a `.git` entry belongs to, and where its object store is.
///
/// Three shapes reach here, and telling them apart is what keeps the linked-worktree rule from
/// swallowing submodules:
///
/// - a `.git` **directory** — a main repository, object store beneath it;
/// - a `.git` **file** whose gitdir sits under `<main>/.git/worktrees/<name>` — a linked worktree,
///   which shares the main repository's object store and must not be pruned in its own right;
/// - any other `.git` file — a submodule (`<super>/.git/modules/<name>`) or a
///   `--separate-git-dir` checkout, both of which have an object store of their own and are
///   repositories in their own right.
///
/// `Err(Some(detail))` is a shape voom will not guess at; `Err(None)` is "not a repository".
fn locate(work_tree: &Path) -> Result<Located, Option<String>> {
    let dot_git = work_tree.join(DOT_GIT);
    let metadata = std::fs::symlink_metadata(&dot_git).map_err(|_| None)?;
    let canonical = work_tree.canonicalize().map_err(|_| None)?;

    if metadata.file_type().is_dir() {
        let located = resolve_store(canonical.join(DOT_GIT), canonical, false);
        if !is_repository(&located.common_dir) {
            return Err(None);
        }
        return Ok(located);
    }
    if !metadata.file_type().is_file() {
        // A symlinked `.git` is not followed, for the same reason nothing else in voom is.
        return Err(None);
    }

    let git_dir = read_gitdir(&dot_git, work_tree).map_err(Some)?;
    let located = resolve_store(git_dir, canonical, true);
    if !is_repository(&located.common_dir) {
        return Err(None);
    }
    Ok(located)
}

/// Follows a git directory to the object store git will actually operate on.
///
/// The store is the authoritative identity here — it is what `gc` repacks and what
/// `worktree prune` writes to — so deduplication, the in-progress rails and containment are all
/// keyed on it rather than on the checkout that led here.
///
/// A linked worktree's private directory carries a `commondir` file naming its store. **Reading
/// that file is the whole of the rule.** Inferring it instead, by looking for an ancestor named
/// `worktrees` under a directory named `.git`, is true only of the default layout: a bare clone
/// (`repo.git/worktrees/<name>`) and the common `project/.bare` arrangement both fail the name
/// test, and every worktree of one was then treated as a repository in its own right —
/// repacking one store once per checkout, and, worse, checking the in-progress markers against
/// a private directory that cannot see a rebase paused in a sibling worktree.
/// Whether a git directory is a repository rather than the shell of one.
///
/// `HEAD` is git's own cheapest test, and the one that matters here: a `.git` directory holding
/// only `hooks/` is what a tool leaves behind when it sets a repository up and never initialises
/// it. Without this check voom reported it as a *failed* repository on every sweep —
/// `fatal: not a git repository` — which is noise the user cannot act on, about something that
/// is not a repository at all.
fn is_repository(common_dir: &Path) -> bool {
    common_dir.join("HEAD").exists()
}

fn resolve_store(git_dir: PathBuf, work_tree: PathBuf, linked: bool) -> Located {
    let Some(common_dir) = common_dir_of(&git_dir) else {
        return Located {
            common_dir: git_dir,
            work_tree,
            linked,
        };
    };
    // `<main>/.git` belongs to `<main>`. A bare store belongs to no checkout, so the worktree
    // that led here is the best name the report has for it.
    let main = (common_dir.file_name() == Some(OsStr::new(DOT_GIT)))
        .then(|| common_dir.parent().map(Path::to_path_buf))
        .flatten();
    Located {
        work_tree: main.unwrap_or(work_tree),
        common_dir,
        linked: true,
    }
}

/// The object store a git directory shares, when it is a linked worktree's private directory.
///
/// `None` for a main git directory, which has no `commondir` file and is its own store.
fn common_dir_of(git_dir: &Path) -> Option<PathBuf> {
    let contents = crate::io::read_capped_text(&git_dir.join("commondir"), CONTROL_FILE_MAX_BYTES)?;
    let named = contents.trim();
    if named.is_empty() {
        return None;
    }
    let joined = if Path::new(named).is_absolute() {
        PathBuf::from(named)
    } else {
        git_dir.join(named)
    };
    joined.canonicalize().ok()
}

fn read_gitdir(dot_git: &Path, work_tree: &Path) -> Result<PathBuf, String> {
    let contents = crate::io::read_capped_text(dot_git, CONTROL_FILE_MAX_BYTES)
        .ok_or_else(|| "its `.git` is not a readable regular file".to_owned())?;
    let gitdir = contents
        .lines()
        .find_map(|line| line.trim().strip_prefix("gitdir:"))
        .ok_or_else(|| "its `.git` file names no gitdir".to_owned())?
        .trim();
    let absolute = if Path::new(gitdir).is_absolute() {
        PathBuf::from(gitdir)
    } else {
        work_tree.join(gitdir)
    };
    absolute
        .canonicalize()
        .map_err(|error| format!("its gitdir `{gitdir}` does not resolve: {error}"))
}

fn canonical_or_given(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

/// Every protected path, resolved once per run against this machine.
///
/// `PROTECTED_PATHS` is the sweep's append-only denylist (ADR 0006), and this now genuinely
/// *reuses* the deletion guard's resolution rather than restating it. It used to restate it, and
/// the two answers differed: the guard resolves Windows locations from `SystemRoot`,
/// `ProgramFiles` and `SystemDrive` precisely because the literals assume the system drive is
/// `C:`, and this copy did not. On a machine whose Windows lives on `D:`, `C:\Windows` fails to
/// canonicalize and contributes nothing, so a repository under `D:\Windows` was protected from
/// deletion and not from housekeeping. Nothing here deletes, so the stakes were low — but a
/// reader who checks one list and not the other must not get two answers, which is exactly what
/// the old comment promised and did not deliver.
///
/// The home directory is added on top. A machine with dotfiles versioned at `$HOME` has a
/// repository there, and `voom ~` would otherwise run housekeeping in it by default.
fn resolved_protected_paths() -> Vec<PathBuf> {
    crate::delete::resolved_protected_paths()
        .into_iter()
        .chain(dirs::home_dir().and_then(|home| home.canonicalize().ok()))
        .collect()
}

fn is_protected(canonical: &Path, resolved: &[PathBuf]) -> bool {
    canonical.parent().is_none()
        || PROTECTED_PATHS
            .iter()
            .any(|protected| paths_equal(canonical, Path::new(protected)))
        || resolved.iter().any(|protected| paths_equal(canonical, protected))
}

/// Whether the repository sits at or below one of the scan roots.
///
/// The sweep's containment rail demands *strictly* below, because there the path in question is
/// about to be deleted and voom removes things *in* the tree it was pointed at, never the tree
/// itself. Nothing is deleted here — git decides what is prunable and does the removing — so the
/// equality case is the ordinary invocation, `voom git-prune .` inside a repository, rather than a
/// hazard. Refusing it would leave the command unable to do the most obvious thing anyone will ask
/// of it.
fn contained(canonical: &Path, roots: &[PathBuf]) -> bool {
    roots.iter().any(|root| canonical.starts_with(root))
}

/// The path of the marker proving a git operation is half-finished here, if there is one.
///
/// Both the common directory and each linked worktree's private directory are checked: a rebase
/// paused in a worktree lives in `.git/worktrees/<name>/rebase-merge`, and a repack of the shared
/// object store is the same hazard wherever the paused operation is.
pub(super) fn in_progress(common_dir: &Path) -> Option<PathBuf> {
    if let Some(marker) = marker_in(common_dir) {
        return Some(common_dir.join(marker));
    }
    let entries = std::fs::read_dir(common_dir.join("worktrees")).ok()?;
    for entry in entries.flatten() {
        let dir = entry.path();
        if let Some(marker) = marker_in(&dir) {
            return Some(dir.join(marker));
        }
    }
    None
}

fn marker_in(dir: &Path) -> Option<&'static str> {
    IN_PROGRESS_MARKERS
        .iter()
        .find(|marker| dir.join(marker).exists())
        .copied()
}

#[cfg(test)]
mod tests {

    /// The two denylists must give the same answers, because the code says they are one list.
    ///
    /// They were not. This module resolved `PROTECTED_PATHS` itself and stopped there, while the
    /// deletion guard additionally resolves Windows locations from `SystemRoot`, `ProgramFiles`
    /// and `SystemDrive` — because the literals assume the system drive is `C:`. On a machine
    /// where Windows lives on `D:`, the guard protected `D:\Windows` and this did not.
    ///
    /// **This test is weaker than it looks, and the weakness is worth stating.** The extra
    /// resolution is `#[cfg(windows)]`, so off Windows both lists are identical and this passes
    /// against the old code too — verified by restoring it. Even on Windows it only diverges
    /// when the system drive is not `C:`, which no CI runner has. What actually removed the
    /// defect is that there is now one implementation and this calls it; the test guards against
    /// someone reintroducing a *narrower* second list, on a machine where the two differ.
    #[test]
    fn should_protect_everything_the_deletion_guard_protects() {
        let ours = resolved_protected_paths();

        for guarded in crate::delete::resolved_protected_paths() {
            assert!(
                ours.iter().any(|path| path == &guarded),
                "the deletion guard protects `{}` and git housekeeping does not — the two are \
                 described as one denylist and must answer alike",
                guarded.display()
            );
        }
    }

    /// And the home directory on top, which the guard reaches by a different route.
    #[test]
    fn should_protect_the_home_directory() {
        let Some(home) = dirs::home_dir().and_then(|home| home.canonicalize().ok()) else {
            return;
        };

        assert!(
            is_protected(&home, &resolved_protected_paths()),
            "a machine with dotfiles versioned at $HOME has a repository there"
        );
    }
    use super::*;
    use crate::testing::tree;

    /// The walker surface a sweep collects repositories through: one name comparison, no syscall.
    #[test]
    fn should_recognise_a_git_entry_as_its_parents_repository() {
        let path = Path::new("/projects/api/.git");
        assert_eq!(
            repository_at(OsStr::new(".git"), path, false),
            Some(Path::new("/projects/api"))
        );
        assert_eq!(
            repository_at(OsStr::new("target"), Path::new("/projects/api/target"), false),
            None
        );
        assert_eq!(
            repository_at(OsStr::new(".git"), path, true),
            None,
            "a symlinked .git is not followed"
        );
    }

    /// A linked worktree's store is read from its `commondir` file, which is the documented
    /// answer and the only one that holds for every layout. The rule used to be inferred from an
    /// ancestor named `worktrees` beneath a directory named `.git`, which is true of the default
    /// layout and of nothing else — a bare clone and the common `project/.bare` arrangement both
    /// fail that test.
    #[test]
    fn should_read_a_linked_worktrees_store_from_its_commondir_file() {
        let fixture = tree(&["repo.git/HEAD", "repo.git/worktrees/feature/HEAD"]);
        let private = fixture.path().join("repo.git/worktrees/feature");
        std::fs::write(private.join("commondir"), "../..\n").expect("a commondir file");

        assert_eq!(
            common_dir_of(&private),
            Some(fixture.path().join("repo.git").canonicalize().expect("the store")),
            "a bare store is found even though it is not named `.git`"
        );
    }

    /// A submodule's `.git` file points into `<super>/.git/modules/<name>`, which is a main git
    /// directory with no `commondir` — so it is a repository in its own right and must survive
    /// the deduplication that folds linked worktrees into one store.
    #[test]
    fn should_not_treat_a_submodule_as_a_linked_worktree() {
        let fixture = tree(&["super/.git/modules/vendor/HEAD"]);
        assert_eq!(common_dir_of(&fixture.path().join("super/.git/modules/vendor")), None);
    }

    /// A `.git` file naming a shape voom does not recognise resolves to the checkout itself
    /// rather than to a guess. Guessing is how the wrong repository gets repacked.
    #[test]
    fn should_locate_a_separate_git_dir_checkout_as_its_own_repository() {
        let fixture = tree(&["work/keep.txt", "store/HEAD"]);
        std::fs::write(
            fixture.path().join("work/.git"),
            format!("gitdir: {}\n", fixture.path().join("store").display()),
        )
        .expect("the .git file");

        let located = locate(&fixture.path().join("work")).expect("a repository");

        assert_eq!(
            located.common_dir(),
            fixture.path().join("store").canonicalize().expect("it exists")
        );
        assert_eq!(
            located.work_tree(),
            fixture.path().join("work").canonicalize().expect("it exists")
        );
    }

    /// The rail that keeps a repack out of somebody's paused rebase.
    #[test]
    fn should_find_an_in_progress_marker_in_the_git_directory() {
        let fixture = tree(&[".git/rebase-merge/head-name"]);
        let git_dir = fixture.path().join(".git");
        assert_eq!(in_progress(&git_dir), Some(git_dir.join("rebase-merge")));
    }

    /// A rebase paused inside a linked worktree is the same hazard: the objects holding the
    /// user's work live in the main repository's shared object store.
    #[test]
    fn should_find_an_in_progress_marker_in_a_linked_worktree() {
        let fixture = tree(&[".git/worktrees/feature/MERGE_HEAD"]);
        let git_dir = fixture.path().join(".git");
        assert_eq!(
            in_progress(&git_dir),
            Some(git_dir.join("worktrees/feature/MERGE_HEAD"))
        );
    }

    #[test]
    fn should_find_no_marker_in_a_quiet_repository() {
        let fixture = tree(&[".git/HEAD"]);
        assert_eq!(in_progress(&fixture.path().join(".git")), None);
    }

    /// The rail is reused from the sweep, so `/` and the rest of `PROTECTED_PATHS` are refused
    /// here too.
    #[test]
    fn should_refuse_a_protected_path() {
        let protected = resolved_protected_paths();
        assert!(is_protected(Path::new("/"), &protected));
        assert!(!is_protected(Path::new("/definitely/not/a/protected/path"), &protected));
    }

    /// Containment allows the root itself, which the sweep's rail does not — `voom git-prune .`
    /// inside a repository is the ordinary invocation, and nothing here is deleted.
    #[test]
    fn should_contain_a_repository_at_or_below_a_root() {
        let roots = vec![PathBuf::from("/projects")];
        assert!(contained(Path::new("/projects"), &roots));
        assert!(contained(Path::new("/projects/api"), &roots));
        assert!(!contained(Path::new("/elsewhere/api"), &roots));
    }

    /// The three resolutions whose ordering formed a cycle, in the shape a real run produced.
    fn cyclic_trio() -> Vec<Resolution> {
        let located = |work_tree: &str, common_dir: &str, linked: bool| Located {
            work_tree: PathBuf::from(work_tree),
            common_dir: PathBuf::from(common_dir),
            linked,
        };
        vec![
            Resolution::Repository(located("/a", "/store", true)),
            Resolution::Repository(located("/b", "/store", false)),
            Resolution::Refused(PathBuf::from("/aa"), Skipped::EscapesRoot),
        ]
    }

    /// The deduplication ordering is a total order.
    ///
    /// It was not, and `voom` over a home directory aborted the process on it: two repositories
    /// compared on `linked` first while a mixed pair compared on path, so the main repository at
    /// `/b` sorted before the linked worktree at `/a`, which sorted before the refusal at `/aa`,
    /// which sorted before `/b`. `slice::sort_by` detects such a cycle and panics with
    /// "user-provided comparison function does not correctly implement a total order".
    #[test]
    fn should_order_resolutions_transitively() {
        let items = cyclic_trio();
        for left in &items {
            for middle in &items {
                for right in &items {
                    let (first, second) = (
                        order_key(left) <= order_key(middle),
                        order_key(middle) <= order_key(right),
                    );
                    assert!(
                        !(first && second) || order_key(left) <= order_key(right),
                        "{:?} <= {:?} <= {:?} but not {:?} <= {:?}",
                        order_key(left),
                        order_key(middle),
                        order_key(right),
                        order_key(left),
                        order_key(right)
                    );
                }
            }
        }
    }

    /// A main repository is the one kept when it shares an object store with a linked worktree.
    #[test]
    fn should_keep_the_main_repository_over_a_linked_worktree() {
        let mut items = cyclic_trio();
        items.sort_by(|left, right| order_key(left).cmp(&order_key(right)));

        let kept: Vec<_> = items
            .iter()
            .filter_map(|item| match item {
                Resolution::Repository(located) => Some(located.work_tree.clone()),
                Resolution::Refused(..) => None,
            })
            .collect();
        assert_eq!(
            kept,
            vec![PathBuf::from("/b"), PathBuf::from("/a")],
            "the main repository sorts first"
        );
    }

    /// A repository outside every scan root is named and left alone rather than acted on.
    #[test]
    fn should_refuse_a_repository_outside_every_root() {
        let fixture = tree(&[".git/HEAD"]);
        let elsewhere = tree(&["unrelated/"]);

        let resolved = resolve_all(
            &[fixture.path().to_path_buf()],
            &[elsewhere.path().canonicalize().expect("it exists")],
        );

        assert!(
            matches!(&resolved[..], [Resolution::Refused(_, Skipped::EscapesRoot)]),
            "{resolved:?}"
        );
    }

    fn discovered(root: &Path) -> Vec<PathBuf> {
        let mut found = repositories(&GitPruneOptions {
            roots: vec![root.to_path_buf()],
            ..GitPruneOptions::default()
        });
        found.sort();
        found
    }

    /// A linked worktree's `.git` file, as `git worktree add` writes it.
    fn link_worktree(fixture: &Path, main: &str, name: &str, checkout: &str) {
        let private = fixture.join(main).join(".git/worktrees").join(name);
        std::fs::create_dir_all(&private).expect("the private directory");
        std::fs::write(private.join("commondir"), "../..\n").expect("a commondir file");
        std::fs::create_dir_all(fixture.join(checkout)).expect("the checkout");
        std::fs::write(
            fixture.join(checkout).join(".git"),
            format!("gitdir: {}\n", private.display()),
        )
        .expect("the .git file");
    }

    #[test]
    fn should_find_a_repository_nested_inside_another() {
        let fixture = tree(&["outer/.git/HEAD", "outer/vendored/inner/.git/HEAD", "outer/src/main.rs"]);

        assert_eq!(
            discovered(fixture.path()),
            vec![
                fixture.path().join("outer"),
                fixture.path().join("outer/vendored/inner")
            ]
        );
    }

    #[test]
    fn should_not_walk_into_a_linked_worktrees_checkout() {
        let fixture = tree(&[
            "main/.git/HEAD",
            "main/src.txt",
            "feature/nested/.git/HEAD",
            "feature/src.txt",
        ]);
        link_worktree(fixture.path(), "main", "feature", "feature");

        assert_eq!(
            discovered(fixture.path()),
            vec![fixture.path().join("feature"), fixture.path().join("main")],
            "the checkout is reported, its interior is not searched"
        );
    }

    #[test]
    fn should_report_a_linked_worktree_whose_administration_is_gone() {
        let fixture = tree(&["stray/nested/.git/HEAD"]);
        std::fs::write(
            fixture.path().join("stray/.git"),
            format!(
                "gitdir: {}\n",
                fixture.path().join("gone/.git/worktrees/stray").display()
            ),
        )
        .expect("the .git file");

        assert_eq!(discovered(fixture.path()), vec![fixture.path().join("stray")]);
    }

    /// A submodule's `.git` file points into `<super>/.git/modules/<name>`, which is a main git
    /// directory: `git submodule absorbgitdirs` writes **no** `commondir` there, unlike a linked
    /// worktree's private directory. Confirmed against real absorbed submodules (the module dirs
    /// of several repos under a sibling checkout have no `commondir`), so the fixture below
    /// matches what git actually writes — a bare `HEAD` under `.git/modules/<name>` — and the walk
    /// enters the submodule rather than reporting it once and stopping.
    #[test]
    fn should_still_walk_into_a_submodule_checkout() {
        let fixture = tree(&[
            "super/.git/HEAD",
            "super/sub/inner/.git/HEAD",
            "super/.git/modules/sub/HEAD",
        ]);
        std::fs::write(fixture.path().join("super/sub/.git"), "gitdir: ../.git/modules/sub\n").expect("the .git file");

        assert_eq!(
            discovered(fixture.path()),
            vec![
                fixture.path().join("super"),
                fixture.path().join("super/sub"),
                fixture.path().join("super/sub/inner")
            ]
        );
    }

    /// Pruning an artifact directory needs the same proof the sweep demands: `target/` beside a
    /// `Cargo.toml` is build output, a bare `target/` is somebody's directory and is searched.
    #[test]
    fn should_prune_proven_artifact_directories_and_search_unproven_ones() {
        let fixture = tree(&[
            "crate/Cargo.toml",
            "crate/target/debug/clone/.git/HEAD",
            "loose/target/clone/.git/HEAD",
            "app/node_modules/pkg/.git/HEAD",
        ]);

        assert_eq!(
            discovered(fixture.path()),
            vec![fixture.path().join("loose/target/clone")]
        );
    }
}