返回 CodeWhale
git_status.rs
根目录 / crates / engine / src / 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. One
7 //! `status --porcelain=v2 --branch -z` carries the branch, its upstream,
8 //! ahead/behind and every changed path, replacing the separate
9 //! `symbolic-ref`, `rev-list` and `status --porcelain` calls it used to make
10 //! (#6565). Around it: `rev-parse --show-toplevel`, one
11 //! `rev-parse --git-dir --git-common-dir` (repository name and linked
12 //! worktree), `log -5` for recent commits, `worktree list --porcelain`, and
13 //! `remote get-url origin` by way of
14 //! [`observed_git_repo`]. Git older than 2.11 has no
15 //! porcelain v2; the probe then falls back to the old three calls. There is
16 //! no `gix` dependency. Each read runs under a timeout, so a wedged git
17 //! fails its probe instead of holding the caller. All of these run with
18 //! `GIT_OPTIONAL_LOCKS=0` so a read never contends for `.git/index.lock` in
19 //! the user's repository.
20 //!
21 //! The same status call and parser back the composer's "branch | status"
22 //! badge ([`context_line`]) and the engine's per-turn git line
23 //! ([`probe_workspace_status`]), so the chrome, the Git view and the model
24 //! read one parser instead of three.
25 //!
26 //! This module owns capability and state outside the renderer so
27 //! `widgets/mod.rs` / `ui.rs` stay projection-only.
28
29 use codewhale_dependencies::{ExternalTool, Git, run_bounded_git_with_timeout};
30 use std::path::{Path, PathBuf};
31 use std::sync::atomic::{AtomicBool, Ordering};
32 use std::sync::{Mutex, OnceLock};
33 use std::time::{Duration, Instant};
34
35 /// Snapshot of repository status for chrome / worktree manager.
36 #[derive(Debug, Clone, Default, PartialEq, Eq)]
37 pub struct GitStatusSnapshot {
38 pub root: Option<PathBuf>,
39 pub repository_name: Option<String>,
40 pub branch: Option<String>,
41 /// `owner/name` when `origin` resolves to a recognised forge, from the
42 /// one normalizer that owns that judgement
43 /// ([`normalize_observed_git_repo`]): paths,
44 /// credentials, and unknown hosts are dropped rather than displayed.
45 /// Cached here so chrome can name the repository without probing on the
46 /// render path.
47 pub remote_slug: Option<String>,
48 pub dirty: bool,
49 pub ahead: u32,
50 pub behind: u32,
51 /// Whether the branch tracks an upstream; `ahead`/`behind` mean nothing
52 /// without one.
53 pub has_upstream: bool,
54 /// `branch` holds a short commit id because HEAD is detached.
55 pub detached: bool,
56 pub changes: ChangeCounts,
57 /// Total changed paths before the display list is capped.
58 pub changed_path_count: usize,
59 /// The first [`MAX_CHANGED_PATHS`] changed paths, in git's order.
60 pub changed_paths: Vec<ChangedPath>,
61 pub recent_commits: Vec<RecentCommit>,
62 /// This checkout is a linked worktree, not the main one.
63 pub is_linked_worktree: bool,
64 pub worktrees: Vec<WorktreeEntry>,
65 pub fetched_at: Option<Instant>,
66 pub error: Option<String>,
67 /// The workspace this snapshot was probed *from*, which is not the same
68 /// as [`Self::root`]: launching in a subdirectory gives a `root` of the
69 /// repository top level while the workspace stays the subdirectory.
70 /// Staleness must compare the probe's own input, not its result.
71 pub probed_workspace: Option<PathBuf>,
72 }
73
74 /// Changed paths by kind, classified exactly as the composer badge always
75 /// did: a path can be both staged and modified; `?` is untracked; `U` is a
76 /// conflict.
77 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
78 pub struct ChangeCounts {
79 pub staged: usize,
80 pub modified: usize,
81 pub untracked: usize,
82 pub conflicts: usize,
83 }
84
85 impl ChangeCounts {
86 #[must_use]
87 pub fn is_clean(&self) -> bool {
88 *self == Self::default()
89 }
90
91 /// `2 staged, 1 modified`, or `clean`.
92 #[must_use]
93 pub fn summary(&self) -> String {
94 let parts = [
95 (self.staged, "staged"),
96 (self.modified, "modified"),
97 (self.untracked, "untracked"),
98 (self.conflicts, "conflicts"),
99 ]
100 .into_iter()
101 .filter(|(count, _)| *count > 0)
102 .map(|(count, word)| format!("{count} {word}"))
103 .collect::<Vec<_>>();
104 if parts.is_empty() {
105 "clean".to_string()
106 } else {
107 parts.join(", ")
108 }
109 }
110
111 fn record(&mut self, x: char, y: char, unmerged: bool) {
112 if x == '?' && y == '?' {
113 self.untracked = self.untracked.saturating_add(1);
114 return;
115 }
116 // An unmerged path is a conflict and nothing else: its two letters
117 // name the merge sides, not a staged and a worktree change (U08-m2).
118 if unmerged {
119 self.conflicts = self.conflicts.saturating_add(1);
120 return;
121 }
122 if x != ' ' && x != '?' {
123 self.staged = self.staged.saturating_add(1);
124 }
125 if y != ' ' && y != '?' {
126 self.modified = self.modified.saturating_add(1);
127 }
128 }
129 }
130
131 /// One changed path with its two-letter status (`M `, ` M`, `??`, `UU`).
132 #[derive(Debug, Clone, PartialEq, Eq)]
133 pub struct ChangedPath {
134 pub code: String,
135 pub path: String,
136 }
137
138 #[derive(Debug, Clone, PartialEq, Eq)]
139 pub struct RecentCommit {
140 pub hash: String,
141 pub subject: String,
142 /// Relative commit time as git words it (`3 hours ago`).
143 pub when: String,
144 }
145
146 /// Changed paths kept for the Git view.
147 pub const MAX_CHANGED_PATHS: usize = 20;
148 /// Recent commits kept for the Git view.
149 const RECENT_COMMITS: &str = "-5";
150
151 /// What one `git status --porcelain=v2 --branch -z` says.
152 #[derive(Debug, Clone, Default, PartialEq, Eq)]
153 pub struct PorcelainStatus {
154 /// Branch name, or `None` for a detached HEAD.
155 pub head: Option<String>,
156 /// Commit id; `None` on an unborn branch.
157 pub oid: Option<String>,
158 pub upstream: Option<String>,
159 pub ahead: u32,
160 pub behind: u32,
161 pub changes: ChangeCounts,
162 pub changed_path_count: usize,
163 pub changed_paths: Vec<ChangedPath>,
164 }
165
166 impl PorcelainStatus {
167 /// The ref the badge shows: the branch, or `detached:<short id>`.
168 #[must_use]
169 pub fn branch_label(&self) -> Option<String> {
170 match (&self.head, &self.oid) {
171 (Some(head), _) => Some(head.clone()),
172 (None, Some(oid)) => Some(format!("detached:{}", short_oid(oid))),
173 (None, None) => None,
174 }
175 }
176 }
177
178 fn short_oid(oid: &str) -> &str {
179 oid.get(..7).unwrap_or(oid)
180 }
181
182 /// Parse `git status --porcelain=v2 --branch -z`. `None` when the output has
183 /// no `# branch.` header (a git too old for porcelain v2), so the caller can
184 /// fall back.
185 #[must_use]
186 pub fn parse_porcelain_v2(raw: &str) -> Option<PorcelainStatus> {
187 let mut status = PorcelainStatus::default();
188 let mut saw_branch_header = false;
189 let mut records = raw.split('\0').filter(|record| !record.is_empty());
190 while let Some(record) = records.next() {
191 if let Some(header) = record.strip_prefix("# branch.") {
192 saw_branch_header = true;
193 let (key, value) = header.split_once(' ').unwrap_or((header, ""));
194 match key {
195 "oid" if value != "(initial)" => status.oid = Some(value.to_string()),
196 "head" if value != "(detached)" => status.head = Some(value.to_string()),
197 "upstream" => status.upstream = Some(value.to_string()),
198 "ab" => {
199 for part in value.split_whitespace() {
200 if let Some(ahead) = part.strip_prefix('+') {
201 status.ahead = ahead.parse().unwrap_or(0);
202 } else if let Some(behind) = part.strip_prefix('-') {
203 status.behind = behind.parse().unwrap_or(0);
204 }
205 }
206 }
207 _ => {}
208 }
209 continue;
210 }
211 let (kind, rest) = record.split_at(record.len().min(2));
212 let (code, path) = match kind {
213 // `1 XY sub mH mI mW hH hI path`
214 "1 " => (rest.get(..2), rest.splitn(8, ' ').nth(7)),
215 // `2 XY sub mH mI mW hH hI Xscore path`, then the original path.
216 "2 " => {
217 let _original = records.next();
218 (rest.get(..2), rest.splitn(9, ' ').nth(8))
219 }
220 // `u XY sub m1 m2 m3 mW h1 h2 h3 path`
221 "u " => (rest.get(..2), rest.splitn(10, ' ').nth(9)),
222 "? " => (Some("??"), Some(rest)),
223 _ => continue,
224 };
225 let (Some(code), Some(path)) = (code, path) else {
226 continue;
227 };
228 let mut letters = code.chars().map(|c| if c == '.' { ' ' } else { c });
229 let x = letters.next().unwrap_or(' ');
230 let y = letters.next().unwrap_or(' ');
231 status.changes.record(x, y, kind == "u ");
232 status.changed_path_count += 1;
233 if status.changed_paths.len() < MAX_CHANGED_PATHS {
234 status.changed_paths.push(ChangedPath {
235 code: format!("{x}{y}"),
236 path: path.to_string(),
237 });
238 }
239 }
240 saw_branch_header.then_some(status)
241 }
242
243 /// Porcelain v1 entries (`git status --porcelain`), for git older than 2.11
244 /// and the `git_status` tool: counts and paths only, without the `-b` header.
245 pub(crate) fn parse_porcelain_v1(raw: &str) -> (ChangeCounts, Vec<ChangedPath>, usize) {
246 let mut counts = ChangeCounts::default();
247 let mut paths = Vec::new();
248 let mut path_count = 0;
249 for line in raw.lines() {
250 let mut chars = line.chars();
251 let (Some(x), Some(y)) = (chars.next(), chars.next()) else {
252 continue;
253 };
254 if x == ' ' && y == ' ' {
255 continue;
256 }
257 counts.record(
258 x,
259 y,
260 x == 'U' || y == 'U' || matches!((x, y), ('A', 'A') | ('D', 'D')),
261 );
262 path_count += 1;
263 if paths.len() < MAX_CHANGED_PATHS {
264 paths.push(ChangedPath {
265 code: format!("{x}{y}"),
266 path: line.get(3..).unwrap_or_default().to_string(),
267 });
268 }
269 }
270 (counts, paths, path_count)
271 }
272
273 /// Branch, upstream and changes for `workspace` from one git call (two on a
274 /// git without porcelain v2). Errors outside a repository or when status fails.
275 /// This is the whole cost of the engine's per-turn git line.
276 ///
277 /// # Errors
278 /// Returns the Git diagnostic if status cannot be read.
279 pub fn probe_workspace_status(workspace: &Path) -> Result<PorcelainStatus, String> {
280 crate::project_context::find_git_root(workspace).ok_or("not a git repository")?;
281 let raw = git_output(
282 workspace,
283 &[
284 "status",
285 "--porcelain=v2",
286 "--branch",
287 "-z",
288 "--untracked-files=normal",
289 "--ignore-submodules=dirty",
290 ],
291 )
292 .ok();
293 if let Some(status) = raw.as_deref().and_then(parse_porcelain_v2) {
294 return Ok(status);
295 }
296 legacy_workspace_status(workspace)
297 }
298
299 /// The pre-2.11 path: the three calls porcelain v2 replaced.
300 fn legacy_workspace_status(workspace: &Path) -> Result<PorcelainStatus, String> {
301 let raw = git_output(
302 workspace,
303 &[
304 "status",
305 "--porcelain",
306 "--untracked-files=normal",
307 "--ignore-submodules=dirty",
308 ],
309 )?;
310 let (changes, changed_paths, changed_path_count) = parse_porcelain_v1(&raw);
311 let head = git_output(workspace, &["symbolic-ref", "--short", "HEAD"])
312 .ok()
313 .map(|s| s.trim().to_string())
314 .filter(|s| !s.is_empty());
315 let oid = git_output(workspace, &["rev-parse", "HEAD"])
316 .ok()
317 .map(|s| s.trim().to_string())
318 .filter(|s| !s.is_empty());
319 let mut status = PorcelainStatus {
320 head,
321 oid,
322 changes,
323 changed_paths,
324 changed_path_count,
325 ..PorcelainStatus::default()
326 };
327 if let Ok(counts) = git_output(
328 workspace,
329 &["rev-list", "--left-right", "--count", "@{upstream}...HEAD"],
330 ) {
331 let mut parts = counts.split_whitespace();
332 if let (Some(behind), Some(ahead)) = (parts.next(), parts.next()) {
333 status.behind = behind.parse().unwrap_or(0);
334 status.ahead = ahead.parse().unwrap_or(0);
335 status.upstream = Some("@{upstream}".to_string());
336 }
337 }
338 Ok(status)
339 }
340
341 /// `branch | 2 staged, 1 modified` — the composer badge and the engine's
342 /// per-turn git line, from a status probe.
343 #[must_use]
344 pub fn status_line(status: &PorcelainStatus) -> Option<String> {
345 Some(format!(
346 "{} | {}",
347 status.branch_label()?,
348 status.changes.summary()
349 ))
350 }
351
352 /// [`status_line`] from a cached snapshot. `None` when the snapshot has not
353 /// found a repository.
354 #[must_use]
355 pub fn context_line(snap: &GitStatusSnapshot) -> Option<String> {
356 snap.root.as_ref()?;
357 if let Some(error) = &snap.error {
358 return Some(error.clone());
359 }
360 let branch = snap.branch.as_deref()?;
361 let branch = if snap.detached {
362 format!("detached:{branch}")
363 } else {
364 branch.to_string()
365 };
366 Some(format!("{branch} | {}", snap.changes.summary()))
367 }
368
369 fn parse_recent_commits(raw: &str) -> Vec<RecentCommit> {
370 raw.lines()
371 .filter_map(|line| {
372 let mut parts = line.splitn(3, '\u{1f}');
373 Some(RecentCommit {
374 hash: parts.next()?.trim().to_string(),
375 subject: parts.next()?.trim().to_string(),
376 when: parts.next().unwrap_or_default().trim().to_string(),
377 })
378 })
379 .filter(|commit| !commit.hash.is_empty())
380 .collect()
381 }
382
383 #[derive(Debug, Clone, PartialEq, Eq)]
384 pub struct WorktreeEntry {
385 pub path: PathBuf,
386 pub branch: Option<String>,
387 pub bare: bool,
388 pub locked: bool,
389 }
390
391 const CACHE_TTL: Duration = Duration::from_secs(2);
392
393 /// Probe cadence while the session is in use. One probe is about a dozen
394 /// `git` processes, none of them counted in the TUI's own CPU time.
395 pub const ACTIVE_PROBE_INTERVAL: Duration = CACHE_TTL;
396
397 /// How long a session must see no input and no engine event before the probe
398 /// backs off to [`QUIET_PROBE_INTERVAL`] (#6728).
399 pub const QUIET_PROBE_AFTER: Duration = Duration::from_secs(30);
400
401 /// Probe cadence of a session nobody is touching. Input or any engine event
402 /// (a tool finishing, a turn ending) ends the quiet and the next tick probes.
403 pub const QUIET_PROBE_INTERVAL: Duration = Duration::from_secs(15);
404
405 /// Cache lifetime while backed off. Just under [`QUIET_PROBE_INTERVAL`], so
406 /// the 15 s workspace-context refresh finds the loop's probe fresh instead of
407 /// adding a second one of its own.
408 const QUIET_CACHE_TTL: Duration = Duration::from_secs(14);
409
410 static PROBE_BACKED_OFF: AtomicBool = AtomicBool::new(false);
411
412 /// Whether a session quiet for `quiet_for` is on the slow probe schedule.
413 #[must_use]
414 pub fn probe_is_backed_off(quiet_for: Duration) -> bool {
415 quiet_for >= QUIET_PROBE_AFTER
416 }
417
418 /// The gap between probes for a session quiet for `quiet_for`.
419 #[must_use]
420 pub fn probe_interval(quiet_for: Duration) -> Duration {
421 if probe_is_backed_off(quiet_for) {
422 QUIET_PROBE_INTERVAL
423 } else {
424 ACTIVE_PROBE_INTERVAL
425 }
426 }
427
428 /// Whether a probe is due, `last_probe_age` after the previous one (`None`:
429 /// never probed). Fresh input shortens the interval, so a probe that is
430 /// older than the fast cadence fires on the very next tick.
431 #[must_use]
432 pub fn probe_due(last_probe_age: Option<Duration>, quiet_for: Duration) -> bool {
433 last_probe_age.is_none_or(|age| age >= probe_interval(quiet_for))
434 }
435
436 /// Tell the cache which schedule the loop is on, so [`refresh_if_stale`]
437 /// callers agree with it about what "fresh" means.
438 pub fn set_probe_backoff(backed_off: bool) {
439 PROBE_BACKED_OFF.store(backed_off, Ordering::Relaxed);
440 }
441
442 fn cache_ttl() -> Duration {
443 if PROBE_BACKED_OFF.load(Ordering::Relaxed) {
444 QUIET_CACHE_TTL
445 } else {
446 CACHE_TTL
447 }
448 }
449
450 static CACHE: OnceLock<Mutex<GitStatusSnapshot>> = OnceLock::new();
451
452 fn cache() -> &'static Mutex<GitStatusSnapshot> {
453 CACHE.get_or_init(|| Mutex::new(GitStatusSnapshot::default()))
454 }
455
456 /// Return the last known snapshot without blocking.
457 #[must_use]
458 pub fn cached_status() -> GitStatusSnapshot {
459 cache().lock().map(|g| g.clone()).unwrap_or_default()
460 }
461
462 /// Refresh status if the cache is stale. Safe to call from a background
463 /// worker; the render path should only read [`cached_status`].
464 /// Whether `snap` must be re-probed for `workspace`.
465 ///
466 /// Split out and pure so the cache contract is testable without spawning
467 /// git. The workspace comparison uses [`GitStatusSnapshot::probed_workspace`]
468 /// deliberately: comparing `root` instead meant that any session launched
469 /// below the repository top level saw `root != workspace` forever, so this
470 /// returned `true` on every call and `CACHE_TTL` never applied. That turned
471 /// the two-second chrome tick into an unconditional six-command probe —
472 /// including the `git status` that contends for `.git/index.lock` (#5617).
473 fn snapshot_is_stale(snap: &GitStatusSnapshot, workspace: &Path) -> bool {
474 snap.fetched_at.is_none_or(|t| t.elapsed() > cache_ttl())
475 || snap.probed_workspace.as_deref() != Some(workspace)
476 }
477
478 /// Returns the snapshot for `workspace`: the cached one while fresh, else a
479 /// new probe (which also becomes the cache).
480 pub fn refresh_if_stale(workspace: &Path) -> GitStatusSnapshot {
481 let cached = cache().lock().ok().map(|g| g.clone());
482 if let Some(snap) = cached.as_ref().filter(|g| !snapshot_is_stale(g, workspace)) {
483 return snap.clone();
484 }
485 // Backed off, with a healthy snapshot of this workspace in hand: re-read
486 // the status only (#6728).
487 if PROBE_BACKED_OFF.load(Ordering::Relaxed)
488 && let Some(prev) = cached.filter(|prev| can_probe_status_only(prev, workspace))
489 {
490 let snap = probe_status_only(&prev);
491 if let Ok(mut guard) = cache().lock() {
492 *guard = snap.clone();
493 }
494 return snap;
495 }
496 force_refresh(workspace)
497 }
498
499 /// Force a refresh (e.g. after checkout / worktree create).
500 pub fn force_refresh(workspace: &Path) -> GitStatusSnapshot {
501 let snap = probe_status(workspace);
502 if let Ok(mut guard) = cache().lock() {
503 *guard = snap.clone();
504 }
505 snap
506 }
507
508 pub fn probe_status(workspace: &Path) -> GitStatusSnapshot {
509 let mut snap = GitStatusSnapshot {
510 fetched_at: Some(Instant::now()),
511 probed_workspace: Some(workspace.to_path_buf()),
512 ..GitStatusSnapshot::default()
513 };
514
515 // Fast-fail outside a repository. Without this a non-git workspace
516 // spawns a doomed `git` process on every tick forever. `find_git_root`
517 // walks parents and understands the `gitdir:` pointer file, so linked
518 // worktrees and submodules are still recognised — a bare `.git`
519 // directory test would not be (#5617). The `rev-parse` below still runs
520 // for the cases this cannot see, such as bare repositories.
521 if crate::project_context::find_git_root(workspace).is_none() {
522 snap.error = Some("not a git repository".into());
523 return snap;
524 }
525
526 // Resolve git root.
527 let root = match git_output(workspace, &["rev-parse", "--show-toplevel"]) {
528 Ok(root) => PathBuf::from(root.trim()),
529 Err(error) => {
530 snap.error = Some(if error.contains("not a git repository") {
531 "not a git repository".into()
532 } else {
533 format!("git unavailable: {}", error.trim())
534 });
535 return snap;
536 }
537 };
538 snap.root = Some(root.clone());
539 let (repository_name, is_linked_worktree) = repository_identity(&root);
540 snap.repository_name = repository_name;
541 snap.is_linked_worktree = is_linked_worktree;
542
543 // Branch, upstream, ahead/behind and every changed path: one call.
544 match probe_workspace_status(&root) {
545 Ok(status) => apply_porcelain(&mut snap, status),
546 Err(error) => {
547 snap.error = Some(format!("git status failed: {}", error.trim()));
548 return snap;
549 }
550 }
551
552 // The forge slug (`owner/name`). Rides this cached probe so the topbar
553 // never shells out per frame.
554 snap.remote_slug = observed_git_repo(&root);
555
556 if let Ok(log) = git_output(&root, &["log", RECENT_COMMITS, "--format=%h%x1f%s%x1f%cr"]) {
557 snap.recent_commits = parse_recent_commits(&log);
558 }
559
560 // Worktrees.
561 if let Ok(list) = git_output(&root, &["worktree", "list", "--porcelain"]) {
562 snap.worktrees = parse_worktree_list(&list);
563 }
564
565 snap
566 }
567
568 /// Fold one `git status` reading into `snap`: branch, upstream, ahead/behind
569 /// and every changed path.
570 fn apply_porcelain(snap: &mut GitStatusSnapshot, status: PorcelainStatus) {
571 snap.detached = status.head.is_none();
572 snap.branch = status
573 .head
574 .clone()
575 .or_else(|| status.oid.as_deref().map(|oid| short_oid(oid).to_string()));
576 snap.has_upstream = status.upstream.is_some();
577 snap.ahead = status.ahead;
578 snap.behind = status.behind;
579 snap.dirty = !status.changes.is_clean();
580 snap.changes = status.changes;
581 snap.changed_paths = status.changed_paths;
582 snap.changed_path_count = status.changed_path_count;
583 }
584
585 /// Whether a backed-off refresh may re-read only `git status` on top of
586 /// `prev`. It needs a healthy earlier probe of the same workspace: the rest
587 /// (repository identity, forge slug, recent commits, worktrees) only changes
588 /// through something the person or the agent does, and that is activity,
589 /// which ends the back-off and brings the full probe back.
590 fn can_probe_status_only(prev: &GitStatusSnapshot, workspace: &Path) -> bool {
591 prev.probed_workspace.as_deref() == Some(workspace)
592 && prev.error.is_none()
593 && prev.root.is_some()
594 }
595
596 /// The back-off probe: one `git status` (two processes) instead of the dozen
597 /// the full probe starts, spliced into `prev`. Branch, dirty state and
598 /// ahead/behind still follow whatever happens in another terminal; the
599 /// commit list and worktree list wait for the next full probe (#6728).
600 ///
601 /// Known limits: while backed off, a commit or worktree change made in another
602 /// terminal shows in the branch and dirty state within [`QUIET_PROBE_INTERVAL`]
603 /// but not in the recent-commit and worktree lists, and the relative ages in
604 /// those lists stand still, until the next input or engine event brings the
605 /// full probe back.
606 fn probe_status_only(prev: &GitStatusSnapshot) -> GitStatusSnapshot {
607 let mut snap = prev.clone();
608 snap.fetched_at = Some(Instant::now());
609 let Some(root) = prev.root.as_deref() else {
610 return snap;
611 };
612 match probe_workspace_status(root) {
613 Ok(status) => apply_porcelain(&mut snap, status),
614 Err(error) => snap.error = Some(format!("git status failed: {}", error.trim())),
615 }
616 snap
617 }
618
619 fn parse_worktree_list(porcelain: &str) -> Vec<WorktreeEntry> {
620 let mut entries = Vec::new();
621 let mut current: Option<WorktreeEntry> = None;
622 for line in porcelain.lines() {
623 if let Some(path) = line.strip_prefix("worktree ") {
624 if let Some(entry) = current.take() {
625 entries.push(entry);
626 }
627 current = Some(WorktreeEntry {
628 path: PathBuf::from(path),
629 branch: None,
630 bare: false,
631 locked: false,
632 });
633 } else if let Some(entry) = current.as_mut() {
634 if let Some(branch) = line.strip_prefix("branch refs/heads/") {
635 entry.branch = Some(branch.to_string());
636 } else if line == "bare" {
637 entry.bare = true;
638 } else if line.starts_with("locked") {
639 entry.locked = true;
640 }
641 }
642 }
643 if let Some(entry) = current {
644 entries.push(entry);
645 }
646 entries
647 }
648
649 const GIT_READ_TIMEOUT: Duration = Duration::from_secs(60);
650
651 fn git_output(cwd: &Path, args: &[&str]) -> Result<String, String> {
652 // Shared read policy disables repository-selected helpers and lazy
653 // fetch while keeping the sanitized environment and optional locks off.
654 let mut command = Git::review_command(cwd).map_err(|e| format!("{e:#}"))?;
655 command.args(["-c", "log.showSignature=false"]).args(args);
656 let output = run_bounded_git_with_timeout(
657 &mut command,
658 args.first().copied().unwrap_or("git"),
659 GIT_READ_TIMEOUT,
660 )
661 .map_err(|e| e.to_string())?;
662 finish_git_output(output)
663 }
664
665 // Explicit writes keep the user's own configured behavior. The shared Git
666 // command still scrubs parent credentials and never opens a hidden prompt.
667 fn git_write(cwd: &Path, args: &[&str]) -> Result<String, String> {
668 finish_git_output(Git::output(args, cwd).map_err(|e| e.to_string())?)
669 }
670
671 fn finish_git_output(output: std::process::Output) -> Result<String, String> {
672 if !output.status.success() {
673 return Err(String::from_utf8_lossy(&output.stderr).into_owned());
674 }
675 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
676 }
677
678 /// The repository's name (from the common git directory, so a linked
679 /// worktree names its repository) and whether this checkout is a linked
680 /// worktree, from one `rev-parse`.
681 fn repository_identity(worktree_root: &Path) -> (Option<String>, bool) {
682 let Ok(paths) = git_output(
683 worktree_root,
684 &[
685 "rev-parse",
686 "--path-format=absolute",
687 "--git-dir",
688 "--git-common-dir",
689 ],
690 ) else {
691 return (None, false);
692 };
693 let mut lines = paths.lines().map(str::trim);
694 let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
695 return (None, false);
696 };
697 (
698 repository_name_from_common_dir(worktree_root, Path::new(common_dir)),
699 git_dir != common_dir,
700 )
701 }
702
703 fn repository_name_from_common_dir(worktree_root: &Path, common_dir: &Path) -> Option<String> {
704 let common_dir = if common_dir.is_absolute() {
705 common_dir.to_path_buf()
706 } else {
707 worktree_root.join(common_dir)
708 };
709 common_dir
710 .parent()
711 .and_then(Path::file_name)
712 .map(|name| name.to_string_lossy().into_owned())
713 }
714
715 /// Compact chrome label: `CodeWhale · main* ↑2` or
716 /// `CodeWhale/feature · feature*` for a linked worktree.
717 ///
718 /// Omits the segment when Git has not named a location or ref. A known
719 /// location without a branch still renders — the header must not invent a
720 /// ref to fill the slot.
721 #[cfg(any(test, feature = "test-support"))]
722 #[must_use]
723 pub fn chrome_label(snap: &GitStatusSnapshot) -> Option<String> {
724 let worktree_name = snap
725 .root
726 .as_deref()
727 .and_then(Path::file_name)
728 .map(|name| name.to_string_lossy());
729 let location = match (snap.repository_name.as_deref(), worktree_name.as_deref()) {
730 (Some(repository), Some(worktree)) if repository != worktree => {
731 Some(format!("{repository}/{worktree}"))
732 }
733 (Some(repository), _) => Some(repository.to_string()),
734 (None, Some(worktree)) => Some(worktree.to_string()),
735 (None, None) => None,
736 };
737 let mut label = match (location, snap.branch.as_deref()) {
738 (Some(location), Some(branch)) => format!("{location} · {branch}"),
739 (Some(location), None) => location,
740 (None, Some(branch)) => branch.to_string(),
741 (None, None) => return None,
742 };
743 if snap.dirty {
744 label.push('*');
745 }
746 if snap.ahead > 0 {
747 label.push_str(&format!(" ↑{}", snap.ahead));
748 }
749 if snap.behind > 0 {
750 label.push_str(&format!(" ↓{}", snap.behind));
751 }
752 Some(label)
753 }
754
755 /// Create a new worktree at `path` tracking `branch` (or a new branch name).
756 pub fn create_worktree(
757 repo: &Path,
758 path: &Path,
759 branch: &str,
760 new_branch: bool,
761 ) -> Result<(), String> {
762 let mut args = vec!["worktree", "add"];
763 if new_branch {
764 args.push("-b");
765 args.push(branch);
766 }
767 args.push("--");
768 args.push(path.to_str().ok_or("invalid path")?);
769 if !new_branch {
770 args.push(branch);
771 }
772 git_write(repo, &args).map(|_| ())
773 }
774
775 /// Build the human-readable workspace context string ("branch | status")
776 /// from one `git status --porcelain=v2 --branch` call, through the same
777 /// parser and formatter the Git view uses. Returns `None` if the workspace is
778 /// not a git repository or git itself is unavailable. The engine's per-turn
779 /// git line reads this.
780 pub fn collect(workspace: &Path) -> Option<String> {
781 probe_workspace_status(workspace)
782 .ok()
783 .as_ref()
784 .and_then(status_line)
785 }
786
787 /// Collapse a git remote to `owner/name`. Paths, credentials, and unknown
788 /// hosts are dropped so the control plane never receives a folder identity.
789 pub fn normalize_observed_git_repo(input: &str) -> Option<String> {
790 let raw = input.trim();
791 if raw.is_empty() {
792 return None;
793 }
794 let allowed_host = |host: &str| {
795 matches!(
796 host.to_ascii_lowercase().as_str(),
797 "github.com" | "www.github.com" | "gitee.com" | "cnb.cool"
798 )
799 };
800 let path = if let Some((authority, path)) = raw.split_once(':')
801 && !raw.contains("://")
802 && authority.starts_with("git@")
803 && allowed_host(authority.trim_start_matches("git@"))
804 {
805 path.to_string()
806 } else {
807 let url = reqwest::Url::parse(raw).ok()?;
808 if url.scheme() != "https"
809 || !url.username().is_empty()
810 || url.password().is_some()
811 || url.port().is_some()
812 || url.query().is_some()
813 || url.fragment().is_some()
814 || !allowed_host(url.host_str()?)
815 {
816 return None;
817 }
818 url.path().trim_start_matches('/').to_string()
819 };
820 let path = path.trim_end_matches('/').trim_end_matches(".git");
821 let mut parts = path.split('/');
822 let owner = parts.next()?;
823 let name = parts.next()?;
824 if parts.next().is_some() {
825 return None;
826 }
827 if owner.len() > 80 || name.len() > 80 {
828 return None;
829 }
830 if !owner
831 .chars()
832 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-'))
833 || !name
834 .chars()
835 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-'))
836 {
837 return None;
838 }
839 if matches!(owner, "." | "..") || matches!(name, "." | "..") {
840 return None;
841 }
842 Some(format!("{owner}/{name}"))
843 }
844
845 pub fn observed_git_repo(workspace: &Path) -> Option<String> {
846 let mut command = Git::review_base(workspace).ok()?;
847 command.args(["remote", "get-url", "origin"]);
848 let output = run_bounded_git_with_timeout(&mut command, "remote", GIT_READ_TIMEOUT).ok()?;
849 if !output.status.success() {
850 return None;
851 }
852 normalize_observed_git_repo(std::str::from_utf8(&output.stdout).ok()?)
853 }
854
855 #[cfg(test)]
856 mod tests {
857 use super::*;
858
859 fn probed(workspace: &Path, root: &Path) -> GitStatusSnapshot {
860 GitStatusSnapshot {
861 root: Some(root.to_path_buf()),
862 probed_workspace: Some(workspace.to_path_buf()),
863 fetched_at: Some(Instant::now()),
864 ..GitStatusSnapshot::default()
865 }
866 }
867
868 /// The cache TTL must actually apply when the session was launched below
869 /// the repository top level. Comparing `root` to the workspace made this
870 /// permanently stale, so the two-second chrome probe ran unconditionally
871 /// and `git status` contended for the user's index lock (#5617).
872 #[test]
873 fn fresh_snapshot_from_a_subdirectory_is_not_stale() {
874 let root = PathBuf::from("/repo");
875 let workspace = PathBuf::from("/repo/crates/tui");
876 let snap = probed(&workspace, &root);
877 assert_ne!(snap.root.as_deref(), Some(workspace.as_path()));
878 assert!(
879 !snapshot_is_stale(&snap, &workspace),
880 "a fresh probe from a subdirectory must satisfy the TTL"
881 );
882 }
883
884 /// The probe schedule of #6728: two seconds while the session is in use,
885 /// fifteen once nothing has touched it for thirty, and the fast cadence
886 /// back on the very next tick after any activity.
887 #[test]
888 fn the_probe_backs_off_only_after_thirty_quiet_seconds() {
889 let secs = Duration::from_secs;
890 assert_eq!(probe_interval(secs(0)), secs(2));
891 assert_eq!(probe_interval(secs(29)), secs(2));
892 assert!(!probe_is_backed_off(secs(29)));
893 assert_eq!(probe_interval(secs(30)), secs(15));
894 assert!(probe_is_backed_off(secs(30)));
895 assert_eq!(probe_interval(secs(3_600)), secs(15));
896 }
897
898 #[test]
899 fn a_probe_is_due_on_its_interval_and_at_once_after_activity() {
900 let secs = Duration::from_secs;
901 // Never probed: always due.
902 assert!(probe_due(None, secs(0)));
903 assert!(probe_due(None, secs(600)));
904 // In use: the 2 s cadence.
905 assert!(!probe_due(Some(secs(1)), secs(5)));
906 assert!(probe_due(Some(secs(2)), secs(5)));
907 // Quiet: nothing until 15 s.
908 assert!(!probe_due(Some(secs(2)), secs(60)));
909 assert!(!probe_due(Some(secs(14)), secs(60)));
910 assert!(probe_due(Some(secs(15)), secs(60)));
911 // The next input resets the quiet clock; a probe 9 s old is now due.
912 assert!(!probe_due(Some(secs(9)), secs(60)));
913 assert!(probe_due(Some(secs(9)), secs(0)));
914 }
915
916 #[test]
917 fn a_status_only_refresh_needs_a_healthy_snapshot_of_the_same_workspace() {
918 let workspace = PathBuf::from("/repo/crates/tui");
919 let healthy = probed(&workspace, Path::new("/repo"));
920 assert!(can_probe_status_only(&healthy, &workspace));
921 assert!(
922 !can_probe_status_only(&healthy, Path::new("/other")),
923 "another workspace gets the full probe"
924 );
925 let mut errored = healthy.clone();
926 errored.error = Some("git status failed: boom".into());
927 assert!(!can_probe_status_only(&errored, &workspace));
928 let mut rootless = healthy;
929 rootless.root = None;
930 assert!(!can_probe_status_only(&rootless, &workspace));
931 assert!(!can_probe_status_only(
932 &GitStatusSnapshot::default(),
933 &workspace
934 ));
935 }
936
937 /// The back-off probe runs one `git status` and leaves everything else
938 /// the full probe learned in place.
939 #[test]
940 fn a_status_only_refresh_keeps_identity_commits_and_worktrees() {
941 let dir = tempfile::tempdir().expect("tempdir");
942 let git = |args: &[&str]| {
943 let out = std::process::Command::new("git")
944 .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
945 .args(args)
946 .current_dir(dir.path())
947 .output()
948 .expect("git runs");
949 assert!(out.status.success(), "git {args:?}: {out:?}");
950 };
951 git(&["init", "-q", "-b", "main"]);
952 std::fs::write(dir.path().join("a.txt"), "a\n").expect("write");
953 git(&["add", "-A"]);
954 git(&["commit", "-q", "-m", "first"]);
955
956 let full = probe_status(dir.path());
957 assert!(full.error.is_none(), "{:?}", full.error);
958 assert!(!full.dirty);
959 assert_eq!(full.recent_commits.len(), 1);
960 assert!(can_probe_status_only(&full, dir.path()));
961
962 std::fs::write(dir.path().join("b.txt"), "b\n").expect("write");
963 let light = probe_status_only(&full);
964 assert!(light.error.is_none(), "{:?}", light.error);
965 assert!(light.dirty, "the new untracked file shows up");
966 assert_eq!(light.changes.untracked, 1);
967 assert_eq!(light.branch.as_deref(), Some("main"));
968 assert_eq!(light.recent_commits, full.recent_commits);
969 assert_eq!(light.worktrees, full.worktrees);
970 assert_eq!(light.repository_name, full.repository_name);
971 assert_eq!(light.root, full.root);
972 assert_eq!(light.probed_workspace, full.probed_workspace);
973 assert!(light.fetched_at >= full.fetched_at);
974 }
975
976 #[test]
977 fn the_quiet_cache_lifetime_stays_below_the_quiet_probe_interval() {
978 // Otherwise the loop's own probe would find its previous result
979 // fresh and skip, and the cadence would silently double.
980 assert!(QUIET_CACHE_TTL < QUIET_PROBE_INTERVAL);
981 assert!(QUIET_CACHE_TTL > CACHE_TTL);
982 }
983
984 #[test]
985 fn a_different_workspace_is_always_stale() {
986 let snap = probed(Path::new("/repo/crates/tui"), Path::new("/repo"));
987 assert!(snapshot_is_stale(&snap, Path::new("/other")));
988 }
989
990 #[test]
991 fn an_unprobed_snapshot_is_stale() {
992 assert!(snapshot_is_stale(
993 &GitStatusSnapshot::default(),
994 Path::new("/repo")
995 ));
996 }
997
998 /// A workspace outside any repository must resolve without spawning git,
999 /// and must record its own input so the TTL suppresses the next tick.
1000 #[test]
1001 fn non_git_workspace_fast_fails_and_caches_its_workspace() {
1002 let dir = tempfile::tempdir().expect("tempdir");
1003 let snap = probe_status(dir.path());
1004 assert_eq!(snap.error.as_deref(), Some("not a git repository"));
1005 assert_eq!(snap.root, None);
1006 assert_eq!(snap.probed_workspace.as_deref(), Some(dir.path()));
1007 assert!(
1008 !snapshot_is_stale(&snap, dir.path()),
1009 "the negative result must be cached, not re-probed every tick"
1010 );
1011 }
1012
1013 #[test]
1014 fn parse_worktree_porcelain() {
1015 let raw = "\
1016 worktree /repo
1017 HEAD abc
1018 branch refs/heads/main
1019
1020 worktree /repo/.cw-worktrees/feat
1021 HEAD def
1022 branch refs/heads/feat
1023 locked
1024 ";
1025 let entries = parse_worktree_list(raw);
1026 assert_eq!(entries.len(), 2);
1027 assert_eq!(entries[0].branch.as_deref(), Some("main"));
1028 assert!(entries[1].locked);
1029 assert_eq!(entries[1].branch.as_deref(), Some("feat"));
1030 }
1031
1032 #[test]
1033 fn chrome_label_marks_dirty_and_divergence() {
1034 let snap = GitStatusSnapshot {
1035 root: Some("/repo".into()),
1036 repository_name: Some("repo".into()),
1037 branch: Some("main".into()),
1038 dirty: true,
1039 ahead: 2,
1040 behind: 1,
1041 ..GitStatusSnapshot::default()
1042 };
1043 assert_eq!(chrome_label(&snap).as_deref(), Some("repo · main* ↑2 ↓1"));
1044 }
1045
1046 #[test]
1047 fn chrome_label_identifies_a_linked_worktree() {
1048 let snap = GitStatusSnapshot {
1049 root: Some("/repo/.cw-worktrees/feature".into()),
1050 repository_name: Some("repo".into()),
1051 branch: Some("feature".into()),
1052 dirty: true,
1053 ..GitStatusSnapshot::default()
1054 };
1055
1056 assert_eq!(
1057 chrome_label(&snap).as_deref(),
1058 Some("repo/feature · feature*")
1059 );
1060 }
1061
1062 #[test]
1063 fn chrome_label_omits_dirty_marker_when_clean() {
1064 let snap = GitStatusSnapshot {
1065 root: Some("/repo".into()),
1066 repository_name: Some("repo".into()),
1067 branch: Some("main".into()),
1068 dirty: false,
1069 ..GitStatusSnapshot::default()
1070 };
1071 assert_eq!(chrome_label(&snap).as_deref(), Some("repo · main"));
1072 }
1073
1074 #[test]
1075 fn chrome_label_keeps_location_when_the_ref_is_unknown() {
1076 let snap = GitStatusSnapshot {
1077 root: Some("/repo/.cw-worktrees/feature".into()),
1078 repository_name: Some("repo".into()),
1079 branch: None,
1080 dirty: true,
1081 ..GitStatusSnapshot::default()
1082 };
1083 assert_eq!(chrome_label(&snap).as_deref(), Some("repo/feature*"));
1084 }
1085
1086 #[test]
1087 fn chrome_label_is_absent_without_a_repo_or_ref() {
1088 assert_eq!(
1089 chrome_label(&GitStatusSnapshot {
1090 error: Some("not a git repository".into()),
1091 ..GitStatusSnapshot::default()
1092 }),
1093 None
1094 );
1095 }
1096
1097 #[test]
1098 fn repository_name_uses_the_common_git_directory_for_worktrees() {
1099 assert_eq!(
1100 repository_name_from_common_dir(
1101 Path::new("/repo/.cw-worktrees/feature"),
1102 Path::new("/repo/.git")
1103 )
1104 .as_deref(),
1105 Some("repo")
1106 );
1107 assert_eq!(
1108 repository_name_from_common_dir(Path::new("/repo"), Path::new(".git")).as_deref(),
1109 Some("repo")
1110 );
1111 }
1112
1113 #[test]
1114 fn porcelain_v2_carries_branch_upstream_divergence_and_every_change() {
1115 let raw = [
1116 "# branch.oid 1234567890abcdef1234567890abcdef12345678",
1117 "# branch.head main",
1118 "# branch.upstream origin/main",
1119 "# branch.ab +2 -1",
1120 "1 M. N... 100644 100644 100644 aaa bbb src/lib.rs",
1121 "1 .M N... 100644 100644 100644 aaa bbb docs/a file.md",
1122 "2 R. N... 100644 100644 100644 aaa bbb R100 new.rs",
1123 "old.rs",
1124 "u UU N... 100644 100644 100644 100644 aaa bbb ccc conflict.rs",
1125 "? scratch.txt",
1126 "! target",
1127 "",
1128 ]
1129 .join("\0");
1130 let status = parse_porcelain_v2(&raw).expect("porcelain v2");
1131 assert_eq!(status.head.as_deref(), Some("main"));
1132 assert_eq!(status.upstream.as_deref(), Some("origin/main"));
1133 assert_eq!((status.ahead, status.behind), (2, 1));
1134 assert_eq!(
1135 status.changes,
1136 ChangeCounts {
1137 // The UU record is a conflict only, not also staged and
1138 // modified (U08-m2).
1139 staged: 2,
1140 modified: 1,
1141 untracked: 1,
1142 conflicts: 1,
1143 }
1144 );
1145 let paths = status
1146 .changed_paths
1147 .iter()
1148 .map(|path| (path.code.as_str(), path.path.as_str()))
1149 .collect::<Vec<_>>();
1150 assert_eq!(
1151 paths,
1152 [
1153 ("M ", "src/lib.rs"),
1154 (" M", "docs/a file.md"),
1155 ("R ", "new.rs"),
1156 ("UU", "conflict.rs"),
1157 ("??", "scratch.txt"),
1158 ]
1159 );
1160 assert_eq!(
1161 status_line(&status).as_deref(),
1162 Some("main | 2 staged, 1 modified, 1 untracked, 1 conflicts")
1163 );
1164 }
1165
1166 #[test]
1167 fn all_unmerged_records_are_conflicts() {
1168 for code in ["AA", "DD", "AU", "UA", "DU", "UD", "UU"] {
1169 let raw = format!(
1170 "# branch.head main\0u {code} N... 100644 100644 100644 100644 aaa bbb ccc conflict.rs\0"
1171 );
1172 let status = parse_porcelain_v2(&raw).unwrap();
1173 assert_eq!(status.changes.conflicts, 1, "{code}");
1174 assert_eq!(
1175 (status.changes.staged, status.changes.modified),
1176 (0, 0),
1177 "{code} is not also staged or modified"
1178 );
1179 assert!(status_line(&status).unwrap().contains("1 conflicts"));
1180 let (legacy, _, _) = parse_porcelain_v1(&format!("{code} conflict.rs\n"));
1181 assert_eq!(legacy.conflicts, 1, "legacy {code}");
1182 assert_eq!((legacy.staged, legacy.modified), (0, 0), "legacy {code}");
1183 }
1184 }
1185
1186 #[test]
1187 fn changed_path_count_survives_the_display_cap() {
1188 for count in [1, MAX_CHANGED_PATHS, MAX_CHANGED_PATHS + 1] {
1189 let mut raw = "# branch.head main\0".to_string();
1190 let mut legacy = String::new();
1191 for index in 0..count {
1192 raw.push_str(&format!(
1193 "1 MM N... 100644 100644 100644 aaa bbb file-{index}\0"
1194 ));
1195 legacy.push_str(&format!("MM file-{index}\n"));
1196 }
1197 let status = parse_porcelain_v2(&raw).unwrap();
1198 assert_eq!(status.changed_path_count, count);
1199 assert_eq!(status.changed_paths.len(), count.min(MAX_CHANGED_PATHS));
1200 let (_, paths, path_count) = parse_porcelain_v1(&legacy);
1201 assert_eq!(path_count, count);
1202 assert_eq!(paths.len(), count.min(MAX_CHANGED_PATHS));
1203 }
1204 }
1205
1206 #[test]
1207 fn porcelain_v2_detached_and_unborn_heads() {
1208 let detached =
1209 parse_porcelain_v2("# branch.oid 1234567890abcdef\0# branch.head (detached)\0")
1210 .expect("v2");
1211 assert_eq!(detached.head, None);
1212 assert_eq!(
1213 status_line(&detached).as_deref(),
1214 Some("detached:1234567 | clean")
1215 );
1216 let unborn =
1217 parse_porcelain_v2("# branch.oid (initial)\0# branch.head main\0").expect("v2");
1218 assert_eq!(unborn.oid, None);
1219 assert_eq!(status_line(&unborn).as_deref(), Some("main | clean"));
1220 // Porcelain v1 (a git too old for v2) has no branch header: the
1221 // caller falls back to the old calls.
1222 assert_eq!(parse_porcelain_v2(" M src/lib.rs\n?? new.rs\n"), None);
1223 let (counts, paths, _) = parse_porcelain_v1(" M src/lib.rs\n?? new.rs\n");
1224 assert_eq!((counts.modified, counts.untracked), (1, 1));
1225 assert_eq!(paths[1].path, "new.rs");
1226 }
1227
1228 #[test]
1229 fn recent_commits_parse_the_unit_separated_log() {
1230 let commits = parse_recent_commits("abc1234\u{1f}fix: a thing\u{1f}3 hours ago\nbad\n");
1231 assert_eq!(
1232 commits,
1233 [RecentCommit {
1234 hash: "abc1234".to_string(),
1235 subject: "fix: a thing".to_string(),
1236 when: "3 hours ago".to_string(),
1237 }]
1238 );
1239 }
1240
1241 fn git(dir: &Path, args: &[&str]) {
1242 let mut all = vec![
1243 "-c",
1244 "user.name=Fixture",
1245 "-c",
1246 "user.email=fixture@example.invalid",
1247 "-c",
1248 "commit.gpgsign=false",
1249 ];
1250 all.extend_from_slice(args);
1251 git_write(dir, &all).expect("git");
1252 }
1253
1254 /// Even status may run repository-selected fsmonitor or clean-filter
1255 /// code. A background read must neither run it nor expose parent env.
1256 #[cfg(unix)]
1257 #[test]
1258 fn automatic_git_status_does_not_execute_repository_helpers() {
1259 use std::os::unix::fs::PermissionsExt;
1260 let _lock = crate::test_support::lock_test_env();
1261 let _sentinel = crate::test_support::EnvVarGuard::set(
1262 "CODEWHALE_TEST_GIT_POLL_SECRET",
1263 "git-poll-sentinel",
1264 );
1265 let dir = tempfile::tempdir().expect("repo");
1266 let hooks = tempfile::tempdir().expect("private hooks");
1267 let repo = dir.path();
1268 git(repo, &["init", "--initial-branch=main"]);
1269 std::fs::write(repo.join("tracked.txt"), "one\n").unwrap();
1270 std::fs::write(repo.join(".gitattributes"), "*.txt filter=fixture\n").unwrap();
1271 git(repo, &["add", "."]);
1272 git(repo, &["commit", "-m", "first commit"]);
1273 let fsmonitor_seen = hooks.path().join("fsmonitor-seen");
1274 let filter_seen = hooks.path().join("filter-seen");
1275 for (name, marker, ending) in [
1276 ("fsmonitor.sh", &fsmonitor_seen, "exit 1"),
1277 ("clean.sh", &filter_seen, "cat"),
1278 ] {
1279 let script = hooks.path().join(name);
1280 std::fs::write(
1281 &script,
1282 format!(
1283 "#!/bin/sh\nprintf 'leak=%s\\n' \"${{CODEWHALE_TEST_GIT_POLL_SECRET-unset}}\" >> '{}'\n{ending}\n",
1284 marker.display(),
1285 ),
1286 )
1287 .unwrap();
1288 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
1289 }
1290 git(
1291 repo,
1292 &[
1293 "config",
1294 "core.fsmonitor",
1295 &hooks.path().join("fsmonitor.sh").to_string_lossy(),
1296 ],
1297 );
1298 git(
1299 repo,
1300 &[
1301 "config",
1302 "filter.fixture.clean",
1303 &hooks.path().join("clean.sh").to_string_lossy(),
1304 ],
1305 );
1306 git(repo, &["config", "filter.fixture.required", "true"]);
1307 // Same length forces content comparison instead of the cheap size check.
1308 std::fs::write(repo.join("tracked.txt"), "two\n").unwrap();
1309 let snapshot = probe_status(repo);
1310 assert_eq!(snapshot.error, None);
1311 assert_eq!(snapshot.branch.as_deref(), Some("main"));
1312 assert!(
1313 snapshot.dirty && snapshot.changes.modified >= 1,
1314 "{snapshot:?}"
1315 );
1316 for marker in [&fsmonitor_seen, &filter_seen] {
1317 assert!(
1318 !marker.exists(),
1319 "automatic read ran a repository helper: {}",
1320 std::fs::read_to_string(marker).unwrap_or_default(),
1321 );
1322 }
1323 }
1324
1325 /// log.showSignature can run the repository's gpg.program even with
1326 /// captured stdout. Recent-commit polling never requests verification.
1327 #[cfg(unix)]
1328 #[test]
1329 fn automatic_git_log_does_not_execute_a_signature_helper() {
1330 use std::io::Write as _;
1331 use std::os::unix::fs::PermissionsExt;
1332 use std::process::Stdio;
1333 let _lock = crate::test_support::lock_test_env();
1334 let _sentinel = crate::test_support::EnvVarGuard::set(
1335 "CODEWHALE_TEST_GIT_POLL_SECRET",
1336 "git-poll-sentinel",
1337 );
1338 let dir = tempfile::tempdir().expect("repo");
1339 let hooks = tempfile::tempdir().expect("private hooks");
1340 let repo = dir.path();
1341 git(repo, &["init", "--initial-branch=main"]);
1342 std::fs::write(repo.join("tracked.txt"), "one\n").unwrap();
1343 git(repo, &["add", "."]);
1344 git(repo, &["commit", "-m", "first commit"]);
1345 let unsigned = git_write(repo, &["cat-file", "commit", "HEAD"]).unwrap();
1346 let (headers, message) = unsigned.split_once("\n\n").unwrap();
1347 let signed = format!(
1348 "{headers}\ngpgsig -----BEGIN PGP SIGNATURE-----\n fixture\n -----END PGP SIGNATURE-----\n\n{message}"
1349 );
1350 let mut child = Git::command()
1351 .expect("git available")
1352 .args(["hash-object", "-t", "commit", "-w", "--stdin"])
1353 .current_dir(repo)
1354 .stdin(Stdio::piped())
1355 .stdout(Stdio::piped())
1356 .spawn()
1357 .unwrap();
1358 child
1359 .stdin
1360 .take()
1361 .unwrap()
1362 .write_all(signed.as_bytes())
1363 .unwrap();
1364 let object = child.wait_with_output().unwrap();
1365 assert!(object.status.success());
1366 let oid = String::from_utf8(object.stdout).unwrap();
1367 git(repo, &["update-ref", "HEAD", oid.trim()]);
1368 let marker = hooks.path().join("signature-seen");
1369 let script = hooks.path().join("signature.sh");
1370 std::fs::write(
1371 &script,
1372 format!(
1373 "#!/bin/sh\nprintf 'leak=%s\\n' \"${{CODEWHALE_TEST_GIT_POLL_SECRET-unset}}\" >> '{}'\nexit 1\n",
1374 marker.display(),
1375 ),
1376 )
1377 .unwrap();
1378 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
1379 git(repo, &["config", "gpg.program", &script.to_string_lossy()]);
1380 git(
1381 repo,
1382 &["config", "gpg.openpgp.program", &script.to_string_lossy()],
1383 );
1384 git(repo, &["config", "log.showSignature", "true"]);
1385 let log = git_output(repo, &["log", "-1", "--format=%s"]).unwrap();
1386 assert!(log.contains("first commit"), "{log}");
1387 assert!(
1388 !marker.exists(),
1389 "automatic log ran a signature helper: {}",
1390 std::fs::read_to_string(marker).unwrap_or_default(),
1391 );
1392 }
1393
1394 /// One probe of a real repository: branch, changes, commits, and the
1395 /// badge string, through the single porcelain v2 status call.
1396 #[test]
1397 fn a_probe_of_a_real_repository_fills_the_git_view() {
1398 let dir = tempfile::tempdir().expect("tempdir");
1399 let repo = dir.path();
1400 git(repo, &["init", "--initial-branch=main"]);
1401 std::fs::write(repo.join("tracked.txt"), "one\n").unwrap();
1402 git(repo, &["add", "tracked.txt"]);
1403 git(repo, &["commit", "-m", "first commit"]);
1404 std::fs::write(repo.join("tracked.txt"), "two\n").unwrap();
1405 std::fs::write(repo.join("new.txt"), "new\n").unwrap();
1406
1407 let snap = probe_status(repo);
1408 assert_eq!(snap.error, None);
1409 assert_eq!(snap.branch.as_deref(), Some("main"));
1410 assert!(!snap.detached && !snap.has_upstream && !snap.is_linked_worktree);
1411 assert_eq!((snap.changes.modified, snap.changes.untracked), (1, 1));
1412 assert!(snap.dirty);
1413 assert_eq!(snap.changed_path_count, 2);
1414 assert_eq!(snap.recent_commits.len(), 1);
1415 assert_eq!(snap.recent_commits[0].subject, "first commit");
1416 assert_eq!(
1417 context_line(&snap).as_deref(),
1418 Some("main | 1 modified, 1 untracked")
1419 );
1420 // The engine's per-turn line reads the same parser and formatter.
1421 assert_eq!(
1422 crate::git_status::collect(repo).as_deref(),
1423 Some("main | 1 modified, 1 untracked")
1424 );
1425 }
1426 }
1427
1427 lines RUST