返回 CodeWhale
git_status.rs
根目录 / crates / tui / src / tui / git_status.rs
1 //! Native git status / worktree surface for the TUI chrome.
2 //!
3 //! Cached and non-blocking: probes run off the render path on a background
4 //! thread and the renderer only ever reads [`cached_status`].
5 //!
6 //! A probe shells out to the real `git` binary — up to seven invocations
7 //! (`rev-parse --show-toplevel`, `rev-parse --git-common-dir`,
8 //! `symbolic-ref --short HEAD` or its `rev-parse --short HEAD` fallback,
9 //! `status --porcelain`, `rev-list --left-right --count`,
10 //! `worktree list --porcelain`, and `remote get-url origin` by way of
11 //! [`crate::remote_control::observed_git_repo`]). There is no `gix`
12 //! dependency and no
13 //! per-invocation timeout; the earlier claim of both here was wrong, and it
14 //! misled a contributor reasoning about probe cost in #5617. All of these
15 //! run with `GIT_OPTIONAL_LOCKS=0` so a read never contends for
16 //! `.git/index.lock` in the user's repository.
17 //!
18 //! This module owns capability and state outside the renderer so
19 //! `widgets/mod.rs` / `ui.rs` stay projection-only.
20
21 #![allow(dead_code)] // Public API; worktree manager wiring continues post-render polish.
22
23 use std::path::{Path, PathBuf};
24 use std::process::Command;
25 use std::sync::{Mutex, OnceLock};
26 use std::time::{Duration, Instant};
27
28 /// Snapshot of repository status for chrome / worktree manager.
29 #[derive(Debug, Clone, Default, PartialEq, Eq)]
30 pub struct GitStatusSnapshot {
31 pub root: Option<PathBuf>,
32 pub repository_name: Option<String>,
33 pub branch: Option<String>,
34 /// `owner/name` when `origin` resolves to a recognised forge, from the
35 /// one normalizer that owns that judgement
36 /// ([`crate::remote_control::normalize_observed_git_repo`]): paths,
37 /// credentials, and unknown hosts are dropped rather than displayed.
38 /// Cached here so chrome can name the repository without probing on the
39 /// render path.
40 pub remote_slug: Option<String>,
41 pub dirty: bool,
42 pub ahead: u32,
43 pub behind: u32,
44 pub worktrees: Vec<WorktreeEntry>,
45 pub fetched_at: Option<Instant>,
46 pub error: Option<String>,
47 /// The workspace this snapshot was probed *from*, which is not the same
48 /// as [`Self::root`]: launching in a subdirectory gives a `root` of the
49 /// repository top level while the workspace stays the subdirectory.
50 /// Staleness must compare the probe's own input, not its result.
51 pub probed_workspace: Option<PathBuf>,
52 }
53
54 #[derive(Debug, Clone, PartialEq, Eq)]
55 pub struct WorktreeEntry {
56 pub path: PathBuf,
57 pub branch: Option<String>,
58 pub bare: bool,
59 pub locked: bool,
60 }
61
62 const CACHE_TTL: Duration = Duration::from_secs(2);
63
64 static CACHE: OnceLock<Mutex<GitStatusSnapshot>> = OnceLock::new();
65
66 fn cache() -> &'static Mutex<GitStatusSnapshot> {
67 CACHE.get_or_init(|| Mutex::new(GitStatusSnapshot::default()))
68 }
69
70 /// Return the last known snapshot without blocking.
71 #[must_use]
72 pub fn cached_status() -> GitStatusSnapshot {
73 cache().lock().map(|g| g.clone()).unwrap_or_default()
74 }
75
76 /// Refresh status if the cache is stale. Safe to call from a background
77 /// worker; the render path should only read [`cached_status`].
78 /// Whether `snap` must be re-probed for `workspace`.
79 ///
80 /// Split out and pure so the cache contract is testable without spawning
81 /// git. The workspace comparison uses [`GitStatusSnapshot::probed_workspace`]
82 /// deliberately: comparing `root` instead meant that any session launched
83 /// below the repository top level saw `root != workspace` forever, so this
84 /// returned `true` on every call and `CACHE_TTL` never applied. That turned
85 /// the two-second chrome tick into an unconditional six-command probe —
86 /// including the `git status` that contends for `.git/index.lock` (#5617).
87 fn snapshot_is_stale(snap: &GitStatusSnapshot, workspace: &Path) -> bool {
88 snap.fetched_at.is_none_or(|t| t.elapsed() > CACHE_TTL)
89 || snap.probed_workspace.as_deref() != Some(workspace)
90 }
91
92 pub fn refresh_if_stale(workspace: &Path) {
93 let stale = cache()
94 .lock()
95 .map(|g| snapshot_is_stale(&g, workspace))
96 .unwrap_or(true);
97 if !stale {
98 return;
99 }
100 let snap = probe_status(workspace);
101 if let Ok(mut guard) = cache().lock() {
102 *guard = snap;
103 }
104 }
105
106 /// Force a refresh (e.g. after checkout / worktree create).
107 pub fn force_refresh(workspace: &Path) {
108 let snap = probe_status(workspace);
109 if let Ok(mut guard) = cache().lock() {
110 *guard = snap;
111 }
112 }
113
114 fn probe_status(workspace: &Path) -> GitStatusSnapshot {
115 let mut snap = GitStatusSnapshot {
116 fetched_at: Some(Instant::now()),
117 probed_workspace: Some(workspace.to_path_buf()),
118 ..GitStatusSnapshot::default()
119 };
120
121 // Fast-fail outside a repository. Without this a non-git workspace
122 // spawns a doomed `git` process on every tick forever. `find_git_root`
123 // walks parents and understands the `gitdir:` pointer file, so linked
124 // worktrees and submodules are still recognised — a bare `.git`
125 // directory test would not be (#5617). The `rev-parse` below still runs
126 // for the cases this cannot see, such as bare repositories.
127 if crate::project_context::find_git_root(workspace).is_none() {
128 snap.error = Some("not a git repository".into());
129 return snap;
130 }
131
132 // Resolve git root.
133 let root = git_output(workspace, &["rev-parse", "--show-toplevel"])
134 .ok()
135 .map(|s| PathBuf::from(s.trim()));
136 let Some(root) = root else {
137 snap.error = Some("not a git repository".into());
138 return snap;
139 };
140 snap.root = Some(root.clone());
141 snap.repository_name = repository_name(&root);
142
143 // Branch (symbolic-ref first, then short HEAD for detached).
144 snap.branch = git_output(&root, &["symbolic-ref", "--short", "HEAD"])
145 .ok()
146 .or_else(|| git_output(&root, &["rev-parse", "--short", "HEAD"]).ok())
147 .map(|s| s.trim().to_string());
148
149 // The forge slug (`owner/name`), reusing the remote-control probe rather
150 // than parsing `origin` a second time. Rides this cached probe so the
151 // topbar never shells out per frame.
152 snap.remote_slug = crate::remote_control::observed_git_repo(&root);
153
154 // Dirty: porcelain status (empty = clean).
155 if let Ok(status) = git_output(&root, &["status", "--porcelain"]) {
156 snap.dirty = !status.trim().is_empty();
157 }
158
159 // Ahead/behind vs upstream (best-effort).
160 if let Ok(counts) = git_output(
161 &root,
162 &["rev-list", "--left-right", "--count", "@{upstream}...HEAD"],
163 ) {
164 let mut parts = counts.split_whitespace();
165 if let (Some(behind), Some(ahead)) = (parts.next(), parts.next()) {
166 snap.behind = behind.parse().unwrap_or(0);
167 snap.ahead = ahead.parse().unwrap_or(0);
168 }
169 }
170
171 // Worktrees.
172 if let Ok(list) = git_output(&root, &["worktree", "list", "--porcelain"]) {
173 snap.worktrees = parse_worktree_list(&list);
174 }
175
176 snap
177 }
178
179 fn parse_worktree_list(porcelain: &str) -> Vec<WorktreeEntry> {
180 let mut entries = Vec::new();
181 let mut current: Option<WorktreeEntry> = None;
182 for line in porcelain.lines() {
183 if let Some(path) = line.strip_prefix("worktree ") {
184 if let Some(entry) = current.take() {
185 entries.push(entry);
186 }
187 current = Some(WorktreeEntry {
188 path: PathBuf::from(path),
189 branch: None,
190 bare: false,
191 locked: false,
192 });
193 } else if let Some(entry) = current.as_mut() {
194 if let Some(branch) = line.strip_prefix("branch refs/heads/") {
195 entry.branch = Some(branch.to_string());
196 } else if line == "bare" {
197 entry.bare = true;
198 } else if line.starts_with("locked") {
199 entry.locked = true;
200 }
201 }
202 }
203 if let Some(entry) = current {
204 entries.push(entry);
205 }
206 entries
207 }
208
209 fn git_output(cwd: &Path, args: &[&str]) -> Result<String, String> {
210 let output = Command::new("git")
211 .args(args)
212 // This probe runs against the user's own repository every two
213 // seconds. `git status` opportunistically refreshes the index, and
214 // that refresh takes `.git/index.lock` — colliding with a `git
215 // commit` the user runs in their own shell (#5617). Optional locks
216 // are exactly what we do not want here: we only ever read.
217 .env("GIT_OPTIONAL_LOCKS", "0")
218 .current_dir(cwd)
219 .output()
220 .map_err(|e| e.to_string())?;
221 if !output.status.success() {
222 return Err(String::from_utf8_lossy(&output.stderr).into_owned());
223 }
224 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
225 }
226
227 fn repository_name(worktree_root: &Path) -> Option<String> {
228 let common_dir = git_output(worktree_root, &["rev-parse", "--git-common-dir"]).ok()?;
229 repository_name_from_common_dir(worktree_root, Path::new(common_dir.trim()))
230 }
231
232 fn repository_name_from_common_dir(worktree_root: &Path, common_dir: &Path) -> Option<String> {
233 let common_dir = if common_dir.is_absolute() {
234 common_dir.to_path_buf()
235 } else {
236 worktree_root.join(common_dir)
237 };
238 common_dir
239 .parent()
240 .and_then(Path::file_name)
241 .map(|name| name.to_string_lossy().into_owned())
242 }
243
244 /// Compact chrome label: `CodeWhale · main* ↑2` or
245 /// `CodeWhale/feature · feature*` for a linked worktree.
246 ///
247 /// Omits the segment when Git has not named a location or ref. A known
248 /// location without a branch still renders — the header must not invent a
249 /// ref to fill the slot.
250 #[must_use]
251 pub fn chrome_label(snap: &GitStatusSnapshot) -> Option<String> {
252 let worktree_name = snap
253 .root
254 .as_deref()
255 .and_then(Path::file_name)
256 .map(|name| name.to_string_lossy());
257 let location = match (snap.repository_name.as_deref(), worktree_name.as_deref()) {
258 (Some(repository), Some(worktree)) if repository != worktree => {
259 Some(format!("{repository}/{worktree}"))
260 }
261 (Some(repository), _) => Some(repository.to_string()),
262 (None, Some(worktree)) => Some(worktree.to_string()),
263 (None, None) => None,
264 };
265 let mut label = match (location, snap.branch.as_deref()) {
266 (Some(location), Some(branch)) => format!("{location} · {branch}"),
267 (Some(location), None) => location,
268 (None, Some(branch)) => branch.to_string(),
269 (None, None) => return None,
270 };
271 if snap.dirty {
272 label.push('*');
273 }
274 if snap.ahead > 0 {
275 label.push_str(&format!(" ↑{}", snap.ahead));
276 }
277 if snap.behind > 0 {
278 label.push_str(&format!(" ↓{}", snap.behind));
279 }
280 Some(label)
281 }
282
283 /// Status-bar ink for repository chrome. Location is metadata, not a
284 /// failure — dirtiness is the `*` on the same gray string.
285 #[must_use]
286 pub fn chrome_ink() -> codewhale_palette::ChromeInk {
287 codewhale_palette::ChromeInk::Metadata
288 }
289
290 /// Create a new worktree at `path` tracking `branch` (or a new branch name).
291 pub fn create_worktree(
292 repo: &Path,
293 path: &Path,
294 branch: &str,
295 new_branch: bool,
296 ) -> Result<(), String> {
297 let mut args = vec!["worktree", "add"];
298 if new_branch {
299 args.push("-b");
300 args.push(branch);
301 args.push(path.to_str().ok_or("invalid path")?);
302 } else {
303 args.push(path.to_str().ok_or("invalid path")?);
304 args.push(branch);
305 }
306 git_output(repo, &args).map(|_| ())?;
307 force_refresh(repo);
308 Ok(())
309 }
310
311 #[cfg(test)]
312 mod tests {
313 use super::*;
314
315 fn probed(workspace: &Path, root: &Path) -> GitStatusSnapshot {
316 GitStatusSnapshot {
317 root: Some(root.to_path_buf()),
318 probed_workspace: Some(workspace.to_path_buf()),
319 fetched_at: Some(Instant::now()),
320 ..GitStatusSnapshot::default()
321 }
322 }
323
324 /// The cache TTL must actually apply when the session was launched below
325 /// the repository top level. Comparing `root` to the workspace made this
326 /// permanently stale, so the two-second chrome probe ran unconditionally
327 /// and `git status` contended for the user's index lock (#5617).
328 #[test]
329 fn fresh_snapshot_from_a_subdirectory_is_not_stale() {
330 let root = PathBuf::from("/repo");
331 let workspace = PathBuf::from("/repo/crates/tui");
332 let snap = probed(&workspace, &root);
333 assert_ne!(snap.root.as_deref(), Some(workspace.as_path()));
334 assert!(
335 !snapshot_is_stale(&snap, &workspace),
336 "a fresh probe from a subdirectory must satisfy the TTL"
337 );
338 }
339
340 #[test]
341 fn a_different_workspace_is_always_stale() {
342 let snap = probed(Path::new("/repo/crates/tui"), Path::new("/repo"));
343 assert!(snapshot_is_stale(&snap, Path::new("/other")));
344 }
345
346 #[test]
347 fn an_unprobed_snapshot_is_stale() {
348 assert!(snapshot_is_stale(
349 &GitStatusSnapshot::default(),
350 Path::new("/repo")
351 ));
352 }
353
354 /// A workspace outside any repository must resolve without spawning git,
355 /// and must record its own input so the TTL suppresses the next tick.
356 #[test]
357 fn non_git_workspace_fast_fails_and_caches_its_workspace() {
358 let dir = tempfile::tempdir().expect("tempdir");
359 let snap = probe_status(dir.path());
360 assert_eq!(snap.error.as_deref(), Some("not a git repository"));
361 assert_eq!(snap.root, None);
362 assert_eq!(snap.probed_workspace.as_deref(), Some(dir.path()));
363 assert!(
364 !snapshot_is_stale(&snap, dir.path()),
365 "the negative result must be cached, not re-probed every tick"
366 );
367 }
368
369 #[test]
370 fn parse_worktree_porcelain() {
371 let raw = "\
372 worktree /repo
373 HEAD abc
374 branch refs/heads/main
375
376 worktree /repo/.cw-worktrees/feat
377 HEAD def
378 branch refs/heads/feat
379 locked
380 ";
381 let entries = parse_worktree_list(raw);
382 assert_eq!(entries.len(), 2);
383 assert_eq!(entries[0].branch.as_deref(), Some("main"));
384 assert!(entries[1].locked);
385 assert_eq!(entries[1].branch.as_deref(), Some("feat"));
386 }
387
388 #[test]
389 fn chrome_label_marks_dirty_and_divergence() {
390 let snap = GitStatusSnapshot {
391 root: Some("/repo".into()),
392 repository_name: Some("repo".into()),
393 branch: Some("main".into()),
394 dirty: true,
395 ahead: 2,
396 behind: 1,
397 ..GitStatusSnapshot::default()
398 };
399 assert_eq!(chrome_label(&snap).as_deref(), Some("repo · main* ↑2 ↓1"));
400 }
401
402 #[test]
403 fn chrome_label_identifies_a_linked_worktree() {
404 let snap = GitStatusSnapshot {
405 root: Some("/repo/.cw-worktrees/feature".into()),
406 repository_name: Some("repo".into()),
407 branch: Some("feature".into()),
408 dirty: true,
409 ..GitStatusSnapshot::default()
410 };
411
412 assert_eq!(
413 chrome_label(&snap).as_deref(),
414 Some("repo/feature · feature*")
415 );
416 }
417
418 #[test]
419 fn chrome_label_omits_dirty_marker_when_clean() {
420 let snap = GitStatusSnapshot {
421 root: Some("/repo".into()),
422 repository_name: Some("repo".into()),
423 branch: Some("main".into()),
424 dirty: false,
425 ..GitStatusSnapshot::default()
426 };
427 assert_eq!(chrome_label(&snap).as_deref(), Some("repo · main"));
428 }
429
430 #[test]
431 fn chrome_label_keeps_location_when_the_ref_is_unknown() {
432 let snap = GitStatusSnapshot {
433 root: Some("/repo/.cw-worktrees/feature".into()),
434 repository_name: Some("repo".into()),
435 branch: None,
436 dirty: true,
437 ..GitStatusSnapshot::default()
438 };
439 assert_eq!(chrome_label(&snap).as_deref(), Some("repo/feature*"));
440 }
441
442 #[test]
443 fn chrome_label_is_absent_without_a_repo_or_ref() {
444 assert_eq!(
445 chrome_label(&GitStatusSnapshot {
446 error: Some("not a git repository".into()),
447 ..GitStatusSnapshot::default()
448 }),
449 None
450 );
451 }
452
453 #[test]
454 fn chrome_ink_is_metadata_not_failure() {
455 assert_eq!(chrome_ink(), codewhale_palette::ChromeInk::Metadata);
456 assert_eq!(
457 chrome_ink().family(),
458 codewhale_palette::SemanticFamily::Neutral
459 );
460 }
461
462 #[test]
463 fn repository_name_uses_the_common_git_directory_for_worktrees() {
464 assert_eq!(
465 repository_name_from_common_dir(
466 Path::new("/repo/.cw-worktrees/feature"),
467 Path::new("/repo/.git")
468 )
469 .as_deref(),
470 Some("repo")
471 );
472 assert_eq!(
473 repository_name_from_common_dir(Path::new("/repo"), Path::new(".git")).as_deref(),
474 Some("repo")
475 );
476 }
477 }
478
478 lines RUST