use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use super::{Outcome, RepositoryWorktrees, State, Worktree, WorktreeOptions};
pub(super) struct Orphan {
main: PathBuf,
gitdir: PathBuf,
}
pub(super) fn orphan(work_tree: &Path) -> Option<Orphan> {
let dot_git = work_tree.join(".git");
if !std::fs::symlink_metadata(&dot_git).ok()?.file_type().is_file() {
return None;
}
let contents = crate::io::read_capped_text(&dot_git, 4096)?;
let named = contents
.lines()
.find_map(|line| line.trim().strip_prefix("gitdir:"))?
.trim();
let gitdir = if Path::new(named).is_absolute() {
PathBuf::from(named)
} else {
work_tree.join(named)
};
if gitdir.exists() || gitdir.parent()?.file_name() != Some(OsStr::new("worktrees")) {
return None;
}
let store = gitdir.parent()?.parent()?;
let main = if store.file_name() == Some(OsStr::new(".git")) {
store.parent()?
} else {
store
};
Some(Orphan {
main: main.to_path_buf(),
gitdir,
})
}
pub(super) fn attach(
found: &mut Vec<RepositoryWorktrees>,
checkout: &Path,
orphan: &Orphan,
roots: &[PathBuf],
current: Option<&Path>,
options: WorktreeOptions,
) {
let canonical = checkout.canonicalize().unwrap_or_else(|_| checkout.to_path_buf());
let mut state = if !roots
.iter()
.any(|root| canonical != *root && canonical.starts_with(root))
{
State::OutsideRoot
} else if current.is_some_and(|cwd| cwd.starts_with(&canonical)) {
State::Current
} else {
State::Dangling {
gitdir: orphan.gitdir.clone(),
bytes: 0,
}
};
let outcome = if let State::Dangling { bytes, .. } = &mut state {
if options.aggressive {
let (outcome, measured) = remove(checkout, orphan, roots, options.dry_run);
*bytes = measured;
Some(outcome)
} else {
*bytes = crate::size::measure(&canonical);
None
}
} else {
None
};
let entry = Worktree {
path: canonical,
branch: None,
state,
outcome,
};
let main = orphan.main.canonicalize().unwrap_or_else(|_| orphan.main.clone());
match found.iter_mut().find(|repository| repository.repository == main) {
Some(repository) => {
repository.worktrees.push(entry);
repository.worktrees.sort_by(|left, right| left.path.cmp(&right.path));
}
None => found.push(RepositoryWorktrees {
repository: main,
default_branch: None,
worktrees: vec![entry],
error: None,
}),
}
}
fn remove(checkout: &Path, expected: &Orphan, roots: &[PathBuf], dry_run: bool) -> (Outcome, u64) {
let guard = match crate::delete::Guard::new(roots, true) {
Ok(guard) => guard,
Err(error) => return (Outcome::Failed(format!("checking dangling checkout: {error}")), 0),
};
if orphan(checkout).is_none_or(|now| now.gitdir != expected.gitdir) {
return (
Outcome::Failed("dangling checkout administration changed before removal".to_owned()),
0,
);
}
let removal = if dry_run {
crate::delete::Removal::dry()
} else {
crate::delete::Removal::new()
};
let (outcome, bytes) = guard.reclaim(checkout, removal);
let outcome = match outcome {
crate::delete::Outcome::Removed | crate::delete::Outcome::Detached => Outcome::Removed,
crate::delete::Outcome::WouldRemove => Outcome::WouldRemove,
outcome => Outcome::Failed(format!(
"removing dangling checkout {}: {outcome:?}",
checkout.display()
)),
};
(outcome, bytes)
}