Skip to main content

reflex/
git.rs

1//! Git repository utilities for branch tracking
2//!
3//! This module provides helper functions for interacting with git repositories
4//! to track branch state, detect uncommitted changes, and capture git metadata
5//! for branch-aware indexing.
6
7use anyhow::{Context, Result};
8use std::collections::HashSet;
9use std::path::Path;
10use std::process::Command;
11use std::sync::OnceLock;
12
13/// Git repository state
14#[derive(Debug, Clone)]
15pub struct GitState {
16    /// Current branch name (e.g., "main", "feature-x")
17    pub branch: String,
18    /// Current commit SHA (full 40-character hash)
19    pub commit: String,
20    /// Whether there are uncommitted changes (modified/added/deleted files)
21    pub dirty: bool,
22    /// Every path `git status` lists (modified, added, deleted, untracked),
23    /// uncapped. The indexer records these as `dirty_at_index`.
24    pub dirty_paths: HashSet<String>,
25}
26
27/// Check if the current directory is inside a git repository
28pub fn is_git_repo(root: impl AsRef<Path>) -> bool {
29    root.as_ref().join(".git").exists()
30}
31
32/// Check whether the `git` binary is available on PATH.
33///
34/// Probes `git --version` once per process and caches the result.
35/// Returns `false` only when the OS reports the binary doesn't exist
36/// (`io::ErrorKind::NotFound`). A `git` that spawns but exits non-zero
37/// still counts as "available" so legitimate git errors propagate normally.
38pub fn is_git_available() -> bool {
39    static AVAILABLE: OnceLock<bool> = OnceLock::new();
40    *AVAILABLE.get_or_init(|| match Command::new("git").arg("--version").output() {
41        Ok(_) => true,
42        Err(e) => e.kind() != std::io::ErrorKind::NotFound,
43    })
44}
45
46/// Get the current git branch name
47///
48/// Returns the branch name (e.g., "main", "feature-x") or "HEAD" if in detached HEAD state.
49pub fn get_current_branch(root: impl AsRef<Path>) -> Result<String> {
50    let output = Command::new("git")
51        .arg("-C")
52        .arg(root.as_ref())
53        .args(["rev-parse", "--abbrev-ref", "HEAD"])
54        .output()
55        .context("Failed to execute git rev-parse")?;
56
57    if !output.status.success() {
58        anyhow::bail!(
59            "git rev-parse failed: {}",
60            String::from_utf8_lossy(&output.stderr)
61        );
62    }
63
64    let branch = String::from_utf8(output.stdout)
65        .context("Invalid UTF-8 in branch name")?
66        .trim()
67        .to_string();
68
69    Ok(branch)
70}
71
72/// The current branch, read from `.git/HEAD` without spawning `git`.
73///
74/// `git rev-parse --abbrev-ref HEAD` costs a process spawn (2–5 ms) and ran on
75/// every `--symbols` query. The answer is one small file: `ref: refs/heads/<name>`
76/// on a branch, or a bare SHA when detached (`HEAD`, matching `--abbrev-ref`).
77/// Worktrees and submodules keep a `.git` *file* holding `gitdir: <path>`, which is
78/// followed one level. `None` when there is no readable HEAD, in which case the
79/// caller falls back to what the indexer recorded (`_default`).
80pub fn read_head_branch(root: impl AsRef<Path>) -> Option<String> {
81    let mut git_dir = root.as_ref().join(".git");
82    if git_dir.is_file() {
83        let text = std::fs::read_to_string(&git_dir).ok()?;
84        let target = text.strip_prefix("gitdir:")?.trim();
85        let target = Path::new(target);
86        git_dir = if target.is_absolute() {
87            target.to_path_buf()
88        } else {
89            root.as_ref().join(target)
90        };
91    }
92    let head = std::fs::read_to_string(git_dir.join("HEAD")).ok()?;
93    let head = head.trim();
94    if let Some(reference) = head.strip_prefix("ref:") {
95        let reference = reference.trim();
96        let name = reference.strip_prefix("refs/heads/").unwrap_or(reference);
97        return Some(name.to_string());
98    }
99    if !head.is_empty() && head.bytes().all(|b| b.is_ascii_hexdigit()) {
100        return Some("HEAD".to_string());
101    }
102    None
103}
104
105/// Get the current commit SHA
106///
107/// Returns the full 40-character commit hash for HEAD.
108pub fn get_current_commit(root: impl AsRef<Path>) -> Result<String> {
109    let output = Command::new("git")
110        .arg("-C")
111        .arg(root.as_ref())
112        .args(["rev-parse", "HEAD"])
113        .output()
114        .context("Failed to execute git rev-parse HEAD")?;
115
116    if !output.status.success() {
117        anyhow::bail!(
118            "git rev-parse HEAD failed: {}",
119            String::from_utf8_lossy(&output.stderr)
120        );
121    }
122
123    let commit = String::from_utf8(output.stdout)
124        .context("Invalid UTF-8 in commit SHA")?
125        .trim()
126        .to_string();
127
128    Ok(commit)
129}
130
131/// Check if there are uncommitted changes in the working tree
132///
133/// Returns true if there are any modified, added, or deleted files.
134/// Uses `git status --porcelain` which is designed for scripting.
135pub fn has_uncommitted_changes(root: impl AsRef<Path>) -> Result<bool> {
136    let output = Command::new("git")
137        .arg("-C")
138        .arg(root.as_ref())
139        .args(["status", "--porcelain"])
140        .output()
141        .context("Failed to execute git status")?;
142
143    if !output.status.success() {
144        anyhow::bail!(
145            "git status failed: {}",
146            String::from_utf8_lossy(&output.stderr)
147        );
148    }
149
150    // If output is empty, working tree is clean
151    // If output has any content, there are uncommitted changes
152    let has_changes = !output.stdout.is_empty();
153
154    Ok(has_changes)
155}
156
157/// Files that differ between the working tree and the last commit.
158///
159/// Lists are capped (see [`MAX_REPORTED_PATHS`]) so a fresh checkout cannot produce a
160/// megabyte of JSON in an MCP response; `truncated` says when that happened and the
161/// `*_count` fields carry the real totals.
162#[derive(Debug, Clone, Default, PartialEq, Eq)]
163pub struct WorktreeChanges {
164    /// Tracked files with edits.
165    pub modified: Vec<String>,
166    /// Untracked files, and files staged as new.
167    pub added: Vec<String>,
168    /// Files removed from disk.
169    pub deleted: Vec<String>,
170    pub modified_count: usize,
171    pub added_count: usize,
172    pub deleted_count: usize,
173    /// Whether any list was cut short.
174    pub truncated: bool,
175}
176
177impl WorktreeChanges {
178    /// Whether the working tree differs from the commit the index was built at.
179    pub fn is_empty(&self) -> bool {
180        self.modified_count == 0 && self.added_count == 0 && self.deleted_count == 0
181    }
182
183    /// Total changed paths, counting every category.
184    pub fn total(&self) -> usize {
185        self.modified_count + self.added_count + self.deleted_count
186    }
187
188    /// Whether any changed path is one the caller cares about.
189    pub fn any<F: Fn(&str) -> bool>(&self, pred: F) -> bool {
190        self.modified
191            .iter()
192            .chain(&self.added)
193            .chain(&self.deleted)
194            .any(|p| pred(p))
195    }
196}
197
198/// How many paths per category a [`WorktreeChanges`] will name.
199pub const MAX_REPORTED_PATHS: usize = 100;
200
201impl WorktreeChanges {
202    /// Count a path in a category, keeping the named list under the cap.
203    pub fn push_modified(&mut self, path: &str) {
204        self.modified_count += 1;
205        if self.modified.len() < MAX_REPORTED_PATHS {
206            self.modified.push(path.to_string());
207        } else {
208            self.truncated = true;
209        }
210    }
211
212    pub fn push_added(&mut self, path: &str) {
213        self.added_count += 1;
214        if self.added.len() < MAX_REPORTED_PATHS {
215            self.added.push(path.to_string());
216        } else {
217            self.truncated = true;
218        }
219    }
220
221    pub fn push_deleted(&mut self, path: &str) {
222        self.deleted_count += 1;
223        if self.deleted.len() < MAX_REPORTED_PATHS {
224            self.deleted.push(path.to_string());
225        } else {
226            self.truncated = true;
227        }
228    }
229
230    /// Sort every list so the response is deterministic whatever order the
231    /// candidates arrived in.
232    pub fn sort(&mut self) {
233        self.modified.sort();
234        self.added.sort();
235        self.deleted.sort();
236    }
237}
238
239/// One `git status --porcelain=v1 -z` record: the two status columns and the path.
240fn porcelain_records(root: &Path) -> Result<Vec<(u8, u8, String)>> {
241    porcelain_records_in(root, &[])
242}
243
244/// [`porcelain_records`] limited to `pathspecs` (literal paths; a directory covers
245/// everything under it). An empty list means the whole tree.
246fn porcelain_records_in(root: &Path, pathspecs: &[&str]) -> Result<Vec<(u8, u8, String)>> {
247    let mut command = Command::new("git");
248    if !pathspecs.is_empty() {
249        command.arg("--literal-pathspecs");
250    }
251    command.arg("-C").arg(root).args([
252        "status",
253        "--porcelain=v1",
254        "-z",
255        "--untracked-files=all",
256        "--no-renames",
257        "--ignored=no",
258    ]);
259    if !pathspecs.is_empty() {
260        command.arg("--").args(pathspecs);
261    }
262    let output = command.output().context("Failed to execute git status")?;
263
264    if !output.status.success() {
265        anyhow::bail!(
266            "git status failed: {}",
267            String::from_utf8_lossy(&output.stderr)
268        );
269    }
270
271    let mut records = Vec::new();
272    // Records are NUL-terminated: "XY <path>\0". With --no-renames there is never a
273    // second path in a record, so a plain split is safe.
274    for record in output.stdout.split(|b| *b == 0) {
275        if record.len() < 4 {
276            continue;
277        }
278        let text = String::from_utf8_lossy(record);
279        let (status, path) = text.split_at(3);
280        let path = path.trim();
281        if path.is_empty() {
282            continue;
283        }
284        let mut bytes = status.bytes();
285        let x = bytes.next().unwrap_or(b' ');
286        let y = bytes.next().unwrap_or(b' ');
287        records.push((x, y, path.to_string()));
288    }
289    Ok(records)
290}
291
292/// Every path `git status` lists, uncapped and unfiltered.
293///
294/// The content-based freshness check uses this only as a CANDIDATE set: each path
295/// is then confirmed against the indexed fingerprint, so a file git calls modified
296/// whose bytes the index already holds is not stale.
297pub fn changed_paths(root: impl AsRef<Path>) -> Result<HashSet<String>> {
298    Ok(porcelain_records(root.as_ref())?
299        .into_iter()
300        .map(|(_, _, p)| p)
301        .collect())
302}
303
304/// The paths `git status` lists among `pathspecs` (see [`changed_paths`]). Costs
305/// what the named paths cost, not what the whole tree costs.
306pub fn changed_paths_in(root: impl AsRef<Path>, pathspecs: &[&str]) -> Result<HashSet<String>> {
307    if pathspecs.is_empty() {
308        return Ok(HashSet::new());
309    }
310    Ok(porcelain_records_in(root.as_ref(), pathspecs)?
311        .into_iter()
312        .map(|(_, _, p)| p)
313        .collect())
314}
315
316/// HEAD's commit and branch name (`HEAD` when detached), from one `git rev-parse`:
317/// the same values [`get_current_commit`] and [`get_current_branch`] return.
318pub fn head_commit_and_branch(root: impl AsRef<Path>) -> Result<(String, String)> {
319    let output = Command::new("git")
320        .arg("-C")
321        .arg(root.as_ref())
322        .args(["rev-parse", "HEAD", "--abbrev-ref", "HEAD"])
323        .output()
324        .context("Failed to execute git rev-parse")?;
325    if !output.status.success() {
326        anyhow::bail!(
327            "git rev-parse failed: {}",
328            String::from_utf8_lossy(&output.stderr)
329        );
330    }
331    let text = String::from_utf8(output.stdout).context("Invalid UTF-8 from git rev-parse")?;
332    let mut lines = text.lines().map(str::trim);
333    match (lines.next(), lines.next()) {
334        (Some(commit), Some(branch)) if !commit.is_empty() && !branch.is_empty() => {
335            Ok((commit.to_string(), branch.to_string()))
336        }
337        _ => anyhow::bail!("git rev-parse printed {:?}", text),
338    }
339}
340
341/// Paths that differ between two commits (`git diff --name-only`).
342///
343/// When HEAD has moved since indexing, these are the tracked paths whose content
344/// may differ from what was indexed; each is then confirmed by fingerprint, so a
345/// commit of already-indexed content does not make the index stale.
346pub fn diff_names(root: impl AsRef<Path>, from: &str, to: &str) -> Result<Vec<String>> {
347    let output = Command::new("git")
348        .arg("-C")
349        .arg(root.as_ref())
350        .args(["diff", "--name-only", "-z", "--no-renames", from, to])
351        .output()
352        .context("Failed to execute git diff")?;
353    if !output.status.success() {
354        anyhow::bail!(
355            "git diff {}..{} failed: {}",
356            from,
357            to,
358            String::from_utf8_lossy(&output.stderr)
359        );
360    }
361    Ok(output
362        .stdout
363        .split(|b| *b == 0)
364        .filter(|p| !p.is_empty())
365        .map(|p| String::from_utf8_lossy(p).into_owned())
366        .collect())
367}
368
369/// List working-tree changes against HEAD.
370///
371/// This is what makes freshness honest. Before 1.7.2 the check compared
372/// `git rev-parse HEAD` to the indexed commit and then sampled the mtimes of the
373/// first TEN indexed files — so an edit to any other file, any untracked file, and
374/// any deletion all reported `fresh` with `can_trust_results: true`. That is the
375/// primary agent workflow: edit, then search, before committing.
376///
377/// Flags, each load-bearing:
378/// * `-z` — porcelain v1 C-quotes paths containing spaces, non-ASCII or backslashes.
379///   `-z` emits raw NUL-separated paths and never quotes, so no unescaping is needed.
380/// * `--untracked-files=all` — list new files individually rather than just their
381///   directory, otherwise a new file inside an existing directory is invisible.
382/// * `--no-renames` — decompose `R old -> new` into a delete plus an add, which is
383///   exactly what an index must do with a rename, and removes all rename parsing.
384/// * `--ignored=no` — `.gitignore`d paths are not indexed, so they cannot make the
385///   index stale.
386///
387/// `keep` filters paths down to those the indexer would actually index. Without it,
388/// editing `README.md` or anything under `target/` would mark the index permanently
389/// stale, and the cure would be worse than the disease.
390pub fn get_worktree_changes<F>(root: impl AsRef<Path>, keep: F) -> Result<WorktreeChanges>
391where
392    F: Fn(&str) -> bool,
393{
394    let mut changes = WorktreeChanges::default();
395
396    for (x, y, path) in porcelain_records(root.as_ref())? {
397        if !keep(&path) {
398            continue;
399        }
400        // A delete in either column wins: the indexed row must go regardless of
401        // whatever else the file did on the way there.
402        if x == b'D' || y == b'D' {
403            changes.push_deleted(&path);
404        } else if x == b'?' || x == b'A' {
405            changes.push_added(&path);
406        } else {
407            changes.push_modified(&path);
408        }
409    }
410
411    Ok(changes)
412}
413
414/// Whether `git check-ignore` says `path` (workspace-relative) is ignored.
415///
416/// `None` outside a git repository or when git cannot answer. Used only to explain
417/// a zero result, so a process spawn is acceptable here.
418pub fn is_ignored(root: impl AsRef<Path>, path: &str) -> Option<bool> {
419    let root = root.as_ref();
420    if !is_git_repo(root) || !is_git_available() {
421        return None;
422    }
423    let status = Command::new("git")
424        .arg("-C")
425        .arg(root)
426        .args(["check-ignore", "-q", "--", path])
427        .status()
428        .ok()?;
429    match status.code() {
430        Some(0) => Some(true),
431        Some(1) => Some(false),
432        _ => None,
433    }
434}
435
436/// Get complete git state for the current repository
437///
438/// This is a convenience function that captures branch, commit, and dirty state
439/// in one call, which is more efficient than calling each function separately.
440pub fn get_git_state(root: impl AsRef<Path>) -> Result<GitState> {
441    let root = root.as_ref();
442
443    if !is_git_repo(root) {
444        anyhow::bail!("Not a git repository");
445    }
446
447    let branch = get_current_branch(root)?;
448    let commit = get_current_commit(root)?;
449    let dirty_paths = changed_paths(root)?;
450
451    Ok(GitState {
452        branch,
453        commit,
454        dirty: !dirty_paths.is_empty(),
455        dirty_paths,
456    })
457}
458
459/// Get git state, or return None if not in a git repository
460///
461/// This is useful for indexing non-git projects where we fall back to a default branch.
462pub fn get_git_state_optional(root: impl AsRef<Path>) -> Result<Option<GitState>> {
463    if !is_git_repo(&root) {
464        return Ok(None);
465    }
466
467    match get_git_state(root) {
468        Ok(state) => Ok(Some(state)),
469        Err(e) => {
470            log::warn!("Failed to get git state: {}", e);
471            Ok(None)
472        }
473    }
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479
480    #[test]
481    fn test_is_git_repo() {
482        // This test project should be a git repo
483        assert!(is_git_repo("."));
484
485        // /tmp should not be a git repo
486        assert!(!is_git_repo("/tmp"));
487    }
488
489    #[test]
490    fn test_get_current_branch() {
491        // Should return a branch name (or HEAD if detached)
492        let branch = get_current_branch(".").unwrap();
493        assert!(!branch.is_empty());
494        log::info!("Current branch: {}", branch);
495    }
496
497    #[test]
498    fn test_get_current_commit() {
499        // Should return a 40-character SHA
500        let commit = get_current_commit(".").unwrap();
501        assert_eq!(commit.len(), 40);
502        assert!(commit.chars().all(|c| c.is_ascii_hexdigit()));
503        log::info!("Current commit: {}", commit);
504    }
505
506    #[test]
507    fn test_has_uncommitted_changes() {
508        // Can't predict if there are changes, but function should not error
509        let has_changes = has_uncommitted_changes(".").unwrap();
510        log::info!("Has uncommitted changes: {}", has_changes);
511    }
512
513    #[test]
514    fn test_get_git_state() {
515        let state = get_git_state(".").unwrap();
516        assert!(!state.branch.is_empty());
517        assert_eq!(state.commit.len(), 40);
518        log::info!("Git state: {:?}", state);
519    }
520}