| 1 | //! Native git status / worktree surface for the TUI chrome. |
| 2 | //! |
| 3 | //! Fast, cached, non-blocking: probes run off the render path and results |
| 4 | //! are read from a small snapshot. Prefer `gix` when available at build time; |
| 5 | //! fall back to a single short-lived `git` invocation with a hard timeout. |
| 6 | //! |
| 7 | //! This module owns capability and state outside the renderer so |
| 8 | //! `widgets/mod.rs` / `ui.rs` stay projection-only. |
| 9 | |
| 10 | #![allow(dead_code)] // Public API; worktree manager wiring continues post-render polish. |
| 11 | |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::process::Command; |
| 14 | use std::sync::{Mutex, OnceLock}; |
| 15 | use std::time::{Duration, Instant}; |
| 16 | |
| 17 | /// Snapshot of repository status for chrome / worktree manager. |
| 18 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 19 | pub struct GitStatusSnapshot { |
| 20 | pub root: Option<PathBuf>, |
| 21 | pub branch: Option<String>, |
| 22 | pub dirty: bool, |
| 23 | pub ahead: u32, |
| 24 | pub behind: u32, |
| 25 | pub worktrees: Vec<WorktreeEntry>, |
| 26 | pub fetched_at: Option<Instant>, |
| 27 | pub error: Option<String>, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub struct WorktreeEntry { |
| 32 | pub path: PathBuf, |
| 33 | pub branch: Option<String>, |
| 34 | pub bare: bool, |
| 35 | pub locked: bool, |
| 36 | } |
| 37 | |
| 38 | const CACHE_TTL: Duration = Duration::from_secs(2); |
| 39 | |
| 40 | static CACHE: OnceLock<Mutex<GitStatusSnapshot>> = OnceLock::new(); |
| 41 | |
| 42 | fn cache() -> &'static Mutex<GitStatusSnapshot> { |
| 43 | CACHE.get_or_init(|| Mutex::new(GitStatusSnapshot::default())) |
| 44 | } |
| 45 | |
| 46 | /// Return the last known snapshot without blocking. |
| 47 | #[must_use] |
| 48 | pub fn cached_status() -> GitStatusSnapshot { |
| 49 | cache().lock().map(|g| g.clone()).unwrap_or_default() |
| 50 | } |
| 51 | |
| 52 | /// Refresh status if the cache is stale. Safe to call from a background |
| 53 | /// worker; the render path should only read [`cached_status`]. |
| 54 | pub fn refresh_if_stale(workspace: &Path) { |
| 55 | let stale = cache() |
| 56 | .lock() |
| 57 | .map(|g| { |
| 58 | g.fetched_at.is_none_or(|t| t.elapsed() > CACHE_TTL) |
| 59 | || g.root.as_deref() != Some(workspace) |
| 60 | }) |
| 61 | .unwrap_or(true); |
| 62 | if !stale { |
| 63 | return; |
| 64 | } |
| 65 | let snap = probe_status(workspace); |
| 66 | if let Ok(mut guard) = cache().lock() { |
| 67 | *guard = snap; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /// Force a refresh (e.g. after checkout / worktree create). |
| 72 | pub fn force_refresh(workspace: &Path) { |
| 73 | let snap = probe_status(workspace); |
| 74 | if let Ok(mut guard) = cache().lock() { |
| 75 | *guard = snap; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | fn probe_status(workspace: &Path) -> GitStatusSnapshot { |
| 80 | let mut snap = GitStatusSnapshot { |
| 81 | fetched_at: Some(Instant::now()), |
| 82 | ..GitStatusSnapshot::default() |
| 83 | }; |
| 84 | |
| 85 | // Resolve git root. |
| 86 | let root = git_output(workspace, &["rev-parse", "--show-toplevel"]) |
| 87 | .ok() |
| 88 | .map(|s| PathBuf::from(s.trim())); |
| 89 | let Some(root) = root else { |
| 90 | snap.error = Some("not a git repository".into()); |
| 91 | return snap; |
| 92 | }; |
| 93 | snap.root = Some(root.clone()); |
| 94 | |
| 95 | // Branch (symbolic-ref first, then short HEAD for detached). |
| 96 | snap.branch = git_output(&root, &["symbolic-ref", "--short", "HEAD"]) |
| 97 | .ok() |
| 98 | .or_else(|| git_output(&root, &["rev-parse", "--short", "HEAD"]).ok()) |
| 99 | .map(|s| s.trim().to_string()); |
| 100 | |
| 101 | // Dirty: porcelain status (empty = clean). |
| 102 | if let Ok(status) = git_output(&root, &["status", "--porcelain"]) { |
| 103 | snap.dirty = !status.trim().is_empty(); |
| 104 | } |
| 105 | |
| 106 | // Ahead/behind vs upstream (best-effort). |
| 107 | if let Ok(counts) = git_output( |
| 108 | &root, |
| 109 | &["rev-list", "--left-right", "--count", "@{upstream}...HEAD"], |
| 110 | ) { |
| 111 | let mut parts = counts.split_whitespace(); |
| 112 | if let (Some(behind), Some(ahead)) = (parts.next(), parts.next()) { |
| 113 | snap.behind = behind.parse().unwrap_or(0); |
| 114 | snap.ahead = ahead.parse().unwrap_or(0); |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // Worktrees. |
| 119 | if let Ok(list) = git_output(&root, &["worktree", "list", "--porcelain"]) { |
| 120 | snap.worktrees = parse_worktree_list(&list); |
| 121 | } |
| 122 | |
| 123 | snap |
| 124 | } |
| 125 | |
| 126 | fn parse_worktree_list(porcelain: &str) -> Vec<WorktreeEntry> { |
| 127 | let mut entries = Vec::new(); |
| 128 | let mut current: Option<WorktreeEntry> = None; |
| 129 | for line in porcelain.lines() { |
| 130 | if let Some(path) = line.strip_prefix("worktree ") { |
| 131 | if let Some(entry) = current.take() { |
| 132 | entries.push(entry); |
| 133 | } |
| 134 | current = Some(WorktreeEntry { |
| 135 | path: PathBuf::from(path), |
| 136 | branch: None, |
| 137 | bare: false, |
| 138 | locked: false, |
| 139 | }); |
| 140 | } else if let Some(entry) = current.as_mut() { |
| 141 | if let Some(branch) = line.strip_prefix("branch refs/heads/") { |
| 142 | entry.branch = Some(branch.to_string()); |
| 143 | } else if line == "bare" { |
| 144 | entry.bare = true; |
| 145 | } else if line.starts_with("locked") { |
| 146 | entry.locked = true; |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | if let Some(entry) = current { |
| 151 | entries.push(entry); |
| 152 | } |
| 153 | entries |
| 154 | } |
| 155 | |
| 156 | fn git_output(cwd: &Path, args: &[&str]) -> Result<String, String> { |
| 157 | let output = Command::new("git") |
| 158 | .args(args) |
| 159 | .current_dir(cwd) |
| 160 | .output() |
| 161 | .map_err(|e| e.to_string())?; |
| 162 | if !output.status.success() { |
| 163 | return Err(String::from_utf8_lossy(&output.stderr).into_owned()); |
| 164 | } |
| 165 | Ok(String::from_utf8_lossy(&output.stdout).into_owned()) |
| 166 | } |
| 167 | |
| 168 | /// Compact chrome label: `main* ↑2` or `detached`. |
| 169 | #[must_use] |
| 170 | pub fn chrome_label(snap: &GitStatusSnapshot) -> Option<String> { |
| 171 | let branch = snap.branch.as_deref()?; |
| 172 | let mut label = branch.to_string(); |
| 173 | if snap.dirty { |
| 174 | label.push('*'); |
| 175 | } |
| 176 | if snap.ahead > 0 { |
| 177 | label.push_str(&format!(" ↑{}", snap.ahead)); |
| 178 | } |
| 179 | if snap.behind > 0 { |
| 180 | label.push_str(&format!(" ↓{}", snap.behind)); |
| 181 | } |
| 182 | Some(label) |
| 183 | } |
| 184 | |
| 185 | /// Create a new worktree at `path` tracking `branch` (or a new branch name). |
| 186 | pub fn create_worktree( |
| 187 | repo: &Path, |
| 188 | path: &Path, |
| 189 | branch: &str, |
| 190 | new_branch: bool, |
| 191 | ) -> Result<(), String> { |
| 192 | let mut args = vec!["worktree", "add"]; |
| 193 | if new_branch { |
| 194 | args.push("-b"); |
| 195 | args.push(branch); |
| 196 | args.push(path.to_str().ok_or("invalid path")?); |
| 197 | } else { |
| 198 | args.push(path.to_str().ok_or("invalid path")?); |
| 199 | args.push(branch); |
| 200 | } |
| 201 | git_output(repo, &args).map(|_| ())?; |
| 202 | force_refresh(repo); |
| 203 | Ok(()) |
| 204 | } |
| 205 | |
| 206 | /// List worktrees from the cache (refresh first if needed). |
| 207 | #[must_use] |
| 208 | pub fn list_worktrees(workspace: &Path) -> Vec<WorktreeEntry> { |
| 209 | refresh_if_stale(workspace); |
| 210 | cached_status().worktrees |
| 211 | } |
| 212 | |
| 213 | #[cfg(test)] |
| 214 | mod tests { |
| 215 | use super::*; |
| 216 | |
| 217 | #[test] |
| 218 | fn parse_worktree_porcelain() { |
| 219 | let raw = "\ |
| 220 | worktree /repo |
| 221 | HEAD abc |
| 222 | branch refs/heads/main |
| 223 | |
| 224 | worktree /repo/.cw-worktrees/feat |
| 225 | HEAD def |
| 226 | branch refs/heads/feat |
| 227 | locked |
| 228 | "; |
| 229 | let entries = parse_worktree_list(raw); |
| 230 | assert_eq!(entries.len(), 2); |
| 231 | assert_eq!(entries[0].branch.as_deref(), Some("main")); |
| 232 | assert!(entries[1].locked); |
| 233 | assert_eq!(entries[1].branch.as_deref(), Some("feat")); |
| 234 | } |
| 235 | |
| 236 | #[test] |
| 237 | fn chrome_label_marks_dirty_and_divergence() { |
| 238 | let snap = GitStatusSnapshot { |
| 239 | branch: Some("main".into()), |
| 240 | dirty: true, |
| 241 | ahead: 2, |
| 242 | behind: 1, |
| 243 | ..GitStatusSnapshot::default() |
| 244 | }; |
| 245 | assert_eq!(chrome_label(&snap).as_deref(), Some("main* ↑2 ↓1")); |
| 246 | } |
| 247 | } |
| 248 |