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    let output = Command::new("git")
242        .arg("-C")
243        .arg(root)
244        .args([
245            "status",
246            "--porcelain=v1",
247            "-z",
248            "--untracked-files=all",
249            "--no-renames",
250            "--ignored=no",
251        ])
252        .output()
253        .context("Failed to execute git status")?;
254
255    if !output.status.success() {
256        anyhow::bail!(
257            "git status failed: {}",
258            String::from_utf8_lossy(&output.stderr)
259        );
260    }
261
262    let mut records = Vec::new();
263    // Records are NUL-terminated: "XY <path>\0". With --no-renames there is never a
264    // second path in a record, so a plain split is safe.
265    for record in output.stdout.split(|b| *b == 0) {
266        if record.len() < 4 {
267            continue;
268        }
269        let text = String::from_utf8_lossy(record);
270        let (status, path) = text.split_at(3);
271        let path = path.trim();
272        if path.is_empty() {
273            continue;
274        }
275        let mut bytes = status.bytes();
276        let x = bytes.next().unwrap_or(b' ');
277        let y = bytes.next().unwrap_or(b' ');
278        records.push((x, y, path.to_string()));
279    }
280    Ok(records)
281}
282
283/// Every path `git status` lists, uncapped and unfiltered.
284///
285/// The content-based freshness check uses this only as a CANDIDATE set: each path
286/// is then confirmed against the indexed fingerprint, so a file git calls modified
287/// whose bytes the index already holds is not stale.
288pub fn changed_paths(root: impl AsRef<Path>) -> Result<HashSet<String>> {
289    Ok(porcelain_records(root.as_ref())?
290        .into_iter()
291        .map(|(_, _, p)| p)
292        .collect())
293}
294
295/// Paths that differ between two commits (`git diff --name-only`).
296///
297/// When HEAD has moved since indexing, these are the tracked paths whose content
298/// may differ from what was indexed; each is then confirmed by fingerprint, so a
299/// commit of already-indexed content does not make the index stale.
300pub fn diff_names(root: impl AsRef<Path>, from: &str, to: &str) -> Result<Vec<String>> {
301    let output = Command::new("git")
302        .arg("-C")
303        .arg(root.as_ref())
304        .args(["diff", "--name-only", "-z", "--no-renames", from, to])
305        .output()
306        .context("Failed to execute git diff")?;
307    if !output.status.success() {
308        anyhow::bail!(
309            "git diff {}..{} failed: {}",
310            from,
311            to,
312            String::from_utf8_lossy(&output.stderr)
313        );
314    }
315    Ok(output
316        .stdout
317        .split(|b| *b == 0)
318        .filter(|p| !p.is_empty())
319        .map(|p| String::from_utf8_lossy(p).into_owned())
320        .collect())
321}
322
323/// List working-tree changes against HEAD.
324///
325/// This is what makes freshness honest. Before 1.7.2 the check compared
326/// `git rev-parse HEAD` to the indexed commit and then sampled the mtimes of the
327/// first TEN indexed files — so an edit to any other file, any untracked file, and
328/// any deletion all reported `fresh` with `can_trust_results: true`. That is the
329/// primary agent workflow: edit, then search, before committing.
330///
331/// Flags, each load-bearing:
332/// * `-z` — porcelain v1 C-quotes paths containing spaces, non-ASCII or backslashes.
333///   `-z` emits raw NUL-separated paths and never quotes, so no unescaping is needed.
334/// * `--untracked-files=all` — list new files individually rather than just their
335///   directory, otherwise a new file inside an existing directory is invisible.
336/// * `--no-renames` — decompose `R old -> new` into a delete plus an add, which is
337///   exactly what an index must do with a rename, and removes all rename parsing.
338/// * `--ignored=no` — `.gitignore`d paths are not indexed, so they cannot make the
339///   index stale.
340///
341/// `keep` filters paths down to those the indexer would actually index. Without it,
342/// editing `README.md` or anything under `target/` would mark the index permanently
343/// stale, and the cure would be worse than the disease.
344pub fn get_worktree_changes<F>(root: impl AsRef<Path>, keep: F) -> Result<WorktreeChanges>
345where
346    F: Fn(&str) -> bool,
347{
348    let mut changes = WorktreeChanges::default();
349
350    for (x, y, path) in porcelain_records(root.as_ref())? {
351        if !keep(&path) {
352            continue;
353        }
354        // A delete in either column wins: the indexed row must go regardless of
355        // whatever else the file did on the way there.
356        if x == b'D' || y == b'D' {
357            changes.push_deleted(&path);
358        } else if x == b'?' || x == b'A' {
359            changes.push_added(&path);
360        } else {
361            changes.push_modified(&path);
362        }
363    }
364
365    Ok(changes)
366}
367
368/// Whether `git check-ignore` says `path` (workspace-relative) is ignored.
369///
370/// `None` outside a git repository or when git cannot answer. Used only to explain
371/// a zero result, so a process spawn is acceptable here.
372pub fn is_ignored(root: impl AsRef<Path>, path: &str) -> Option<bool> {
373    let root = root.as_ref();
374    if !is_git_repo(root) || !is_git_available() {
375        return None;
376    }
377    let status = Command::new("git")
378        .arg("-C")
379        .arg(root)
380        .args(["check-ignore", "-q", "--", path])
381        .status()
382        .ok()?;
383    match status.code() {
384        Some(0) => Some(true),
385        Some(1) => Some(false),
386        _ => None,
387    }
388}
389
390/// Get complete git state for the current repository
391///
392/// This is a convenience function that captures branch, commit, and dirty state
393/// in one call, which is more efficient than calling each function separately.
394pub fn get_git_state(root: impl AsRef<Path>) -> Result<GitState> {
395    let root = root.as_ref();
396
397    if !is_git_repo(root) {
398        anyhow::bail!("Not a git repository");
399    }
400
401    let branch = get_current_branch(root)?;
402    let commit = get_current_commit(root)?;
403    let dirty_paths = changed_paths(root)?;
404
405    Ok(GitState {
406        branch,
407        commit,
408        dirty: !dirty_paths.is_empty(),
409        dirty_paths,
410    })
411}
412
413/// Get git state, or return None if not in a git repository
414///
415/// This is useful for indexing non-git projects where we fall back to a default branch.
416pub fn get_git_state_optional(root: impl AsRef<Path>) -> Result<Option<GitState>> {
417    if !is_git_repo(&root) {
418        return Ok(None);
419    }
420
421    match get_git_state(root) {
422        Ok(state) => Ok(Some(state)),
423        Err(e) => {
424            log::warn!("Failed to get git state: {}", e);
425            Ok(None)
426        }
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    #[test]
435    fn test_is_git_repo() {
436        // This test project should be a git repo
437        assert!(is_git_repo("."));
438
439        // /tmp should not be a git repo
440        assert!(!is_git_repo("/tmp"));
441    }
442
443    #[test]
444    fn test_get_current_branch() {
445        // Should return a branch name (or HEAD if detached)
446        let branch = get_current_branch(".").unwrap();
447        assert!(!branch.is_empty());
448        log::info!("Current branch: {}", branch);
449    }
450
451    #[test]
452    fn test_get_current_commit() {
453        // Should return a 40-character SHA
454        let commit = get_current_commit(".").unwrap();
455        assert_eq!(commit.len(), 40);
456        assert!(commit.chars().all(|c| c.is_ascii_hexdigit()));
457        log::info!("Current commit: {}", commit);
458    }
459
460    #[test]
461    fn test_has_uncommitted_changes() {
462        // Can't predict if there are changes, but function should not error
463        let has_changes = has_uncommitted_changes(".").unwrap();
464        log::info!("Has uncommitted changes: {}", has_changes);
465    }
466
467    #[test]
468    fn test_get_git_state() {
469        let state = get_git_state(".").unwrap();
470        assert!(!state.branch.is_empty());
471        assert_eq!(state.commit.len(), 40);
472        log::info!("Git state: {:?}", state);
473    }
474}