use std::collections::{HashMap, HashSet};
use serde::Serialize;
use crate::index::live::ProjectDir;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Checkout {
pub root: String,
pub worktree: Option<String>,
pub branch: Option<String>,
pub sessions: u32,
}
impl Checkout {
pub fn of(cwd: Option<&str>, dir: Option<&ProjectDir>, branch: Option<String>) -> Option<Self> {
let (root, worktree) = match (dir, cwd) {
(Some(d), _) => match &d.worktree {
Some(w) => (w.clone(), Some(base_name(w).to_string())),
None => (d.key.clone(), None),
},
(None, Some(c)) => (c.to_string(), None),
(None, None) => return None,
};
Some(Checkout {
root,
worktree,
branch,
sessions: 0,
})
}
pub fn label(&self, project: &str) -> String {
match &self.worktree {
Some(w) => format!("{project}/{w}"),
None => project.to_string(),
}
}
pub fn branch_label(&self) -> Option<&str> {
self.branch
.as_deref()
.map(|b| if b == "HEAD" { "detached HEAD" } else { b })
}
pub fn branch_to_show(&self) -> Option<&str> {
let b = self.branch.as_deref()?;
match &self.worktree {
Some(w) if b == w || b.strip_prefix("worktree-") == Some(w.as_str()) => None,
None if matches!(b, "main" | "master") => None,
Some(_) | None if b == "HEAD" => Some("detached HEAD"),
Some(_) | None => Some(b),
}
}
pub fn is_shared(&self) -> bool {
self.sessions > 1
}
}
fn base_name(path: &str) -> &str {
path.trim_end_matches(['/', '\\'])
.rsplit(['/', '\\'])
.next()
.unwrap_or(path)
}
pub fn sessions_per_root<'a, K: Eq + std::hash::Hash>(
working: impl IntoIterator<Item = (K, &'a str)>,
) -> HashMap<String, u32> {
let mut by_root: HashMap<&str, HashSet<K>> = HashMap::new();
for (k, root) in working {
by_root.entry(root).or_default().insert(k);
}
by_root
.into_iter()
.map(|(r, s)| (r.to_string(), s.len() as u32))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn dir(key: &str, wt: Option<&str>) -> ProjectDir {
ProjectDir {
key: key.into(),
name: "shop".into(),
worktree: wt.map(str::to_string),
}
}
#[test]
fn a_worktree_is_named_by_its_dir_and_a_repeated_branch_is_not_shown() {
let d = dir("/w/shop", Some("/w/shop/.claude/worktrees/fix-1"));
let c = Checkout::of(
Some("/w/shop/.claude/worktrees/fix-1/src"),
Some(&d),
Some("worktree-fix-1".into()),
)
.unwrap();
assert_eq!(c.root, "/w/shop/.claude/worktrees/fix-1");
assert_eq!(c.label("shop"), "shop/fix-1");
assert_eq!(c.branch_to_show(), None);
let c = Checkout {
branch: Some("feat/pay".into()),
..c
};
assert_eq!(c.branch_to_show(), Some("feat/pay"));
let main = Checkout::of(
Some("/w/shop/src"),
Some(&dir("/w/shop", None)),
Some("main".into()),
)
.unwrap();
assert_eq!(
(main.root.as_str(), main.label("shop")),
("/w/shop", "shop".into())
);
assert_eq!(
main.branch_to_show(),
None,
"the usual branch of a main checkout says nothing"
);
let feat = Checkout {
branch: Some("feat/pay".into()),
..main.clone()
};
assert_eq!(feat.branch_to_show(), Some("feat/pay"));
assert_eq!(
Checkout::of(Some("/tmp/x"), None, None).unwrap().root,
"/tmp/x"
);
assert_eq!(Checkout::of(None, None, None), None);
}
#[test]
fn sessions_are_counted_per_checkout_once_each() {
let n = sessions_per_root([
("s1", "/w/shop"),
("s1", "/w/shop"),
("s2", "/w/shop"),
("s3", "/w/shop-wt/x"),
]);
assert_eq!(n.get("/w/shop"), Some(&2));
assert_eq!(n.get("/w/shop-wt/x"), Some(&1));
let c = Checkout {
sessions: n["/w/shop"],
..Default::default()
};
assert!(c.is_shared());
}
}