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::is_dependency_dir;
use crate::delete::PROTECTED_PATHS;
use crate::scan::NEVER_DESCEND;
const IN_PROGRESS_MARKERS: &[&str] = &[
"rebase-merge",
"rebase-apply",
"MERGE_HEAD",
"CHERRY_PICK_HEAD",
"REVERT_HEAD",
"BISECT_LOG",
];
#[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()
}
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, options.caches, &[]);
let caches = &caches;
let (sender, receiver) = std::sync::mpsc::channel();
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.build_parallel().run(|| {
let sender = sender.clone();
Box::new(move |result| {
let Ok(entry) = result else {
return WalkState::Continue;
};
let path = entry.path();
let file_type = entry.file_type();
let is_symlink = file_type.is_some_and(|file_type| file_type.is_symlink());
if let Some(work_tree) = repository_at(entry.file_name(), path, is_symlink) {
let _ = sender.send(work_tree.to_path_buf());
return WalkState::Skip;
}
if !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;
}
WalkState::Continue
})
});
drop(sender);
into.extend(receiver);
}
fn is_pruned(name: &OsStr) -> bool {
NEVER_DESCEND.iter().any(|never| name == OsStr::new(never)) || is_dependency_dir(name)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Located {
work_tree: PathBuf,
common_dir: PathBuf,
linked: bool,
}
impl Located {
pub(super) fn work_tree(&self) -> &Path {
&self.work_tree
}
pub(super) fn common_dir(&self) -> &Path {
&self.common_dir
}
}
#[derive(Debug, Clone)]
pub(super) enum Resolution {
Repository(Located),
Refused(PathBuf, Skipped),
}
impl Resolution {
fn path(&self) -> &Path {
match self {
Self::Repository(located) => &located.work_tree,
Self::Refused(path, _) => path,
}
}
}
pub(super) fn resolve_all(work_trees: &[PathBuf], roots: &[PathBuf]) -> Vec<Resolution> {
let protected = resolved_protected_paths();
let mut resolved: Vec<Resolution> = work_trees
.iter()
.filter_map(|work_tree| resolve(work_tree, roots, &protected))
.collect();
resolved.sort_by(|left, right| match (left, right) {
(Resolution::Repository(first), Resolution::Repository(second)) => first
.linked
.cmp(&second.linked)
.then_with(|| first.work_tree.cmp(&second.work_tree)),
_ => left.path().cmp(right.path()),
});
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 },
));
}
Err(None) => return None,
};
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),
})
}
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() {
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)
}
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,
};
};
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,
}
}
fn common_dir_of(git_dir: &Path) -> Option<PathBuf> {
let contents = std::fs::read_to_string(git_dir.join("commondir")).ok()?;
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 = std::fs::read_to_string(dot_git).map_err(|error| error.to_string())?;
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())
}
fn resolved_protected_paths() -> Vec<PathBuf> {
PROTECTED_PATHS
.iter()
.filter_map(|protected| Path::new(protected).canonicalize().ok())
.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| canonical == Path::new(protected))
|| resolved.iter().any(|protected| canonical == protected.as_path())
}
fn contained(canonical: &Path, roots: &[PathBuf]) -> bool {
roots.iter().any(|root| canonical.starts_with(root))
}
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 {
use super::*;
use crate::testing::tree;
#[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"
);
}
#[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`"
);
}
#[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);
}
#[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")
);
}
#[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")));
}
#[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);
}
#[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));
}
#[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));
}
#[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:?}"
);
}
}