use std::path::{Path, PathBuf};
use rho_protocol::SessionWorktree;
use super::{canonical, succeeded, WorktreeError};
#[derive(Debug)]
pub(crate) struct Unowned {
pub(crate) worktree: SessionWorktree,
pub(crate) detached: bool,
}
pub(crate) async fn unowned(root: &Path, owned: &[&Path]) -> Vec<Unowned> {
let entries = match canonical(root).and_then(|root| {
std::fs::read_dir(&root).map_err(|error| WorktreeError::Io { path: root, error })
}) {
Ok(entries) => entries,
Err(WorktreeError::Io { error, .. }) if error.kind() == std::io::ErrorKind::NotFound => {
return Vec::new();
}
Err(error) => {
tracing::warn!(
root = %root.display(),
%error,
"could not list the worktree directory; checking no worktree no session owns"
);
return Vec::new();
}
};
let mut found = Vec::new();
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(error) => {
tracing::warn!(
root = %root.display(),
%error,
"could not read an entry of the worktree directory; leaving it"
);
continue;
}
};
let path = entry.path();
let is_dir = match entry.file_type() {
Ok(kind) => kind.is_dir(),
Err(error) => {
tracing::warn!(
path = %path.display(),
%error,
"could not tell what an entry of the worktree directory is; leaving it"
);
continue;
}
};
if !is_dir || !path.join(".git").is_file() || owned.contains(&path.as_path()) {
continue;
}
match read(path.clone()).await {
Ok(unowned) => found.push(unowned),
Err(error) => tracing::warn!(
path = %path.display(),
%error,
"could not read a worktree no session owns; leaving it"
),
}
}
found
}
async fn read(path: PathBuf) -> Result<Unowned, WorktreeError> {
let malformed = |detail: &str| WorktreeError::Git {
action: "worktree list".to_owned(),
repository: path.clone(),
detail: detail.to_owned(),
};
let listed = succeeded(&path, "worktree list", ["worktree", "list", "--porcelain"]).await?;
let mut blocks = listed.split("\n\n").map(Entry::parse);
let origin = blocks
.next()
.and_then(|main| main.path)
.ok_or_else(|| malformed("git named no main worktree"))?;
let this = blocks
.find(|entry| {
entry
.path
.as_deref()
.is_some_and(|listed| canonical(listed).is_ok_and(|listed| listed == path))
})
.ok_or_else(|| malformed("git does not list it"))?;
let (branch, detached) = match (this.branch, this.head) {
(Some(branch), _) => (branch.to_owned(), false),
(None, Some(head)) => (head.chars().take(12).collect(), true),
(None, None) => return Err(malformed("git names neither its branch nor its commit")),
};
Ok(Unowned {
worktree: SessionWorktree {
branch,
path,
origin,
},
detached,
})
}
struct Entry<'a> {
path: Option<PathBuf>,
head: Option<&'a str>,
branch: Option<&'a str>,
}
impl<'a> Entry<'a> {
fn parse(block: &'a str) -> Self {
let field = |name: &str| {
block
.lines()
.find_map(|line| line.strip_prefix(name)?.strip_prefix(' '))
};
Self {
path: field("worktree").map(PathBuf::from),
head: field("HEAD"),
branch: field("branch")
.map(|branch| branch.strip_prefix("refs/heads/").unwrap_or(branch)),
}
}
}