use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use super::{RepositoryWorktrees, State, Worktree};
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>,
) {
let canonical = checkout.canonicalize().unwrap_or_else(|_| checkout.to_path_buf());
let 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: crate::size::measure(&canonical),
}
};
let entry = Worktree {
path: canonical,
branch: None,
state,
outcome: None,
};
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,
}),
}
}