use std::path::PathBuf;
use git2::Repository;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CheckedOutWorktree {
pub name: String,
pub path: PathBuf,
pub head_ref: Option<String>,
pub head_resolved: bool,
}
enum AdminHead {
Branch(String),
Pruned,
Unresolved,
}
fn read_worktree_admin_head(repository: &Repository, name: &str) -> AdminHead {
let admin_dir = repository.commondir().join("worktrees").join(name);
if !admin_dir.is_dir() {
return AdminHead::Pruned;
}
let Ok(contents) = std::fs::read_to_string(admin_dir.join("HEAD")) else {
return AdminHead::Unresolved;
};
match contents.trim().strip_prefix("ref:") {
Some(refname) if !refname.trim().is_empty() => {
AdminHead::Branch(refname.trim().to_string())
}
_ => AdminHead::Unresolved,
}
}
pub fn checked_out_worktrees(repository: &Repository) -> Result<Vec<CheckedOutWorktree>, String> {
let names = repository
.worktrees()
.map_err(|err| format!("Error: repository worktrees are unavailable: {err}."))?;
let mut out: Vec<CheckedOutWorktree> = Vec::new();
for entry in names.iter() {
let Ok(Some(name)) = entry else {
out.push(CheckedOutWorktree {
name: "<unnameable-worktree>".to_string(),
path: PathBuf::new(),
head_ref: None,
head_resolved: false,
});
continue;
};
let live = repository
.find_worktree(name)
.ok()
.filter(|worktree| worktree.validate().is_ok());
let (path, head_ref, head_resolved) = match live {
Some(worktree) => {
let path = worktree.path().to_path_buf();
let (head_ref, head_resolved) = match Repository::open_from_worktree(&worktree) {
Ok(repo) => match repo.head() {
Ok(head) if head.is_branch() => match head.name() {
Ok(name) => (Some(name.to_string()), true),
Err(_) => (None, false),
},
Ok(_) => (None, true), Err(_) => (None, false), },
Err(_) => (None, false), };
(path, head_ref, head_resolved)
}
None => match read_worktree_admin_head(repository, name) {
AdminHead::Pruned => continue,
AdminHead::Branch(refname) => (PathBuf::new(), Some(refname), true),
AdminHead::Unresolved => (PathBuf::new(), None, false),
},
};
out.push(CheckedOutWorktree {
name: name.to_string(),
path,
head_ref,
head_resolved,
});
}
out.sort_by(|left, right| left.name.cmp(&right.name));
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
fn init_repo(root: &Path) -> Repository {
git2::Repository::init(root).expect("init repo")
}
fn commit_initial(root: &Path) {
let repository = git2::Repository::open(root).expect("open repo");
std::fs::write(root.join("src.rs"), b"pub fn a() {}\n").expect("write file");
let mut index = repository.index().expect("index");
index
.add_all(["*"], git2::IndexAddOption::DEFAULT, None)
.expect("stage");
index.write().expect("write index");
let tree_id = index.write_tree().expect("write tree");
let tree = repository.find_tree(tree_id).expect("tree");
let signature =
git2::Signature::now("SymForge Test", "symforge@example.invalid").expect("sig");
repository
.commit(Some("HEAD"), &signature, &signature, "initial", &tree, &[])
.expect("commit");
}
fn add_worktree_on_branch(repository: &Repository, path: &Path, name: &str, branch: &str) {
let head_commit = repository
.head()
.expect("head")
.peel_to_commit()
.expect("peel");
repository
.branch(branch, &head_commit, false)
.expect("branch");
let reference = repository
.find_reference(&format!("refs/heads/{branch}"))
.expect("reference");
let mut opts = git2::WorktreeAddOptions::new();
opts.reference(Some(&reference));
repository
.worktree(name, path, Some(&opts))
.expect("add worktree");
}
#[test]
fn classifies_a_linked_worktree_on_a_branch() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
init_repo(root);
commit_initial(root);
let repository = git2::Repository::open(root).expect("open");
let wt_parent = tempfile::tempdir().expect("wt tempdir");
let wt_path = wt_parent.path().join("feature-wt");
add_worktree_on_branch(&repository, &wt_path, "feature-wt", "feature");
let checked_out = checked_out_worktrees(&repository).expect("classify");
assert_eq!(checked_out.len(), 1, "one linked worktree is classified");
let wt = &checked_out[0];
assert_eq!(wt.name, "feature-wt");
assert_eq!(
wt.head_ref.as_deref(),
Some("refs/heads/feature"),
"the worktree HEAD branch is captured"
);
assert!(wt.head_resolved, "a readable worktree HEAD is resolved");
assert!(
wt.path.ends_with("feature-wt"),
"the worktree working directory is captured, got {:?}",
wt.path
);
}
#[test]
fn classifies_empty_when_no_linked_worktrees() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
init_repo(root);
commit_initial(root);
let repository = git2::Repository::open(root).expect("open");
let checked_out = checked_out_worktrees(&repository).expect("classify");
assert!(
checked_out.is_empty(),
"a repo with no linked worktrees classifies empty"
);
}
#[test]
fn moved_but_unpruned_worktree_is_classified_from_admin_head() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
init_repo(root);
commit_initial(root);
let repository = git2::Repository::open(root).expect("open");
let wt_parent = tempfile::tempdir().expect("wt tempdir");
let wt_path = wt_parent.path().join("moved-wt");
add_worktree_on_branch(&repository, &wt_path, "moved-wt", "moved");
std::fs::remove_dir_all(&wt_path).expect("remove worktree working dir");
let checked_out = checked_out_worktrees(&repository).expect("classify");
let moved = checked_out
.iter()
.find(|w| w.name == "moved-wt")
.expect("the moved worktree is still classified, not skipped");
assert_eq!(
moved.head_ref.as_deref(),
Some("refs/heads/moved"),
"the branch is read from the admin HEAD fallback"
);
assert!(
moved.head_resolved,
"an admin-HEAD branch is a resolved (protected) checkout"
);
}
}