use serde::Serialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
pub struct SessionGit {
pub workspace_id: String,
pub instance_id: u64,
pub provider: String,
pub branch: String,
pub head: String,
pub dirty: u32,
pub root: String,
}
#[derive(Clone, Debug)]
struct Live {
pid: u32,
provider: String,
}
static LIVE: OnceLock<Mutex<BTreeMap<(String, u64), Live>>> = OnceLock::new();
fn live() -> std::sync::MutexGuard<'static, BTreeMap<(String, u64), Live>> {
LIVE.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner())
}
pub fn running(workspace: &str, instance: u64, provider: &str, pid: u32) {
live().insert((workspace.to_owned(), instance), Live { pid, provider: provider.to_owned() });
}
pub fn provider_hint(workspace: &str, instance: u64, provider: &str) {
if let Some(l) = live().get_mut(&(workspace.to_owned(), instance)) {
if l.provider != provider {
l.provider = provider.to_owned();
}
}
}
pub fn exited(workspace: &str, instance: u64) {
live().remove(&(workspace.to_owned(), instance));
}
fn cwd_of(pid: u32) -> Option<PathBuf> {
if cfg!(unix) {
std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
} else {
None
}
}
fn git(dir: &Path, args: &[&str]) -> Option<String> {
let mut cmd = std::process::Command::new("git");
cmd.arg("-C").arg(dir).args(args).stdin(std::process::Stdio::null()).stderr(std::process::Stdio::null());
crate::windows_process::hide_console(&mut cmd);
let out = cmd.output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}
pub fn read_repo(dir: &Path) -> Option<(String, String, u32, String)> {
let root = git(dir, &["rev-parse", "--show-toplevel"])?.trim().to_owned();
let branch = git(dir, &["rev-parse", "--abbrev-ref", "HEAD"]).map(|s| s.trim().to_owned()).unwrap_or_default();
let head = git(dir, &["rev-parse", "--short=12", "HEAD"]).map(|s| s.trim().to_owned()).unwrap_or_default();
let dirty = git(dir, &["status", "--porcelain", "--untracked-files=normal"]).map(|s| s.lines().take(10_000).count() as u32).unwrap_or(0);
Some((branch, head, dirty, root))
}
pub fn snapshot() -> Vec<SessionGit> {
let sessions: Vec<_> = live().iter().map(|(k, v)| (k.clone(), v.clone())).collect();
sessions
.into_iter()
.filter_map(|((ws, inst), l)| {
let dir = cwd_of(l.pid)?;
let (branch, head, dirty, root) = read_repo(&dir)?;
Some(SessionGit { workspace_id: ws, instance_id: inst, provider: l.provider, branch, head, dirty, root })
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_branch_and_dirty() {
let d = std::env::temp_dir().join(format!("gw-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let run = |a: &[&str]| assert!(std::process::Command::new("git").arg("-C").arg(&d).args(a).output().unwrap().status.success());
run(&["init", "-q", "-b", "feat-x"]);
run(&["-c", "core.hooksPath=/dev/null", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"]);
std::fs::write(d.join("a.txt"), "x").unwrap();
let (branch, head, dirty, _) = read_repo(&d).unwrap();
assert_eq!(branch, "feat-x");
assert_eq!(head.len(), 12);
assert_eq!(dirty, 1);
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn live_session_snapshot() {
running("w", 77, "claude", std::process::id());
let here = std::env::current_dir().unwrap();
let in_repo = read_repo(&here).is_some();
assert_eq!(snapshot().iter().any(|s| s.instance_id == 77), in_repo && cfg!(target_os = "linux"));
exited("w", 77);
assert!(!snapshot().iter().any(|s| s.instance_id == 77));
}
}