Skip to main content

lean_ctx/core/git/
mod.rs

1//! Native git support: remote-repo reading (cached shallow clone) and a shadow
2//! history of agent changes.
3//!
4//! * [`repo_url`] parses repository URLs into a [`repo_url::RepoRef`].
5//! * [`clone`] maintains a bounded, SSRF-guarded local clone cache.
6//! * [`shadow`] records agent edits in a git history kept *outside* the user's
7//!   own `.git`.
8//!
9//! All git invocations go through [`run_git`], which never uses a shell, always
10//! disables interactive credential prompts (so a private/auth-required remote
11//! fails fast instead of hanging), and enforces a wall-clock timeout.
12
13pub mod clone;
14pub mod decision_history;
15pub mod repo_url;
16pub mod shadow;
17
18use std::io::Read;
19use std::path::Path;
20use std::process::{Command, Stdio};
21use std::time::{Duration, Instant};
22
23/// Result of a single `git` invocation.
24#[derive(Debug, Clone)]
25pub struct GitOutput {
26    pub stdout: String,
27    pub stderr: String,
28    pub success: bool,
29}
30
31impl GitOutput {
32    /// Stdout if the command succeeded, else an error carrying trimmed stderr.
33    pub fn ok_stdout(self) -> Result<String, String> {
34        if self.success {
35            Ok(self.stdout)
36        } else {
37            let msg = self.stderr.trim();
38            Err(if msg.is_empty() {
39                "git command failed".to_string()
40            } else {
41                msg.to_string()
42            })
43        }
44    }
45}
46
47/// `true` if a `git` binary is callable.
48pub fn git_available() -> bool {
49    Command::new("git")
50        .arg("--version")
51        .stdin(Stdio::null())
52        .stdout(Stdio::null())
53        .stderr(Stdio::null())
54        .status()
55        .is_ok_and(|s| s.success())
56}
57
58/// Run `git <args>` in `cwd` with extra env vars and a wall-clock `timeout`.
59///
60/// No shell is involved (args are passed directly). Interactive credential
61/// prompts are disabled so an auth-required remote errors immediately rather
62/// than blocking. stdout/stderr are drained on dedicated threads to avoid
63/// pipe-buffer deadlock on chatty commands (e.g. `clone` progress).
64pub fn run_git(
65    args: &[&str],
66    cwd: &Path,
67    timeout: Duration,
68    env: &[(&str, &str)],
69) -> Result<GitOutput, String> {
70    let mut cmd = Command::new("git");
71    cmd.args(args)
72        .current_dir(cwd)
73        .stdin(Stdio::null())
74        .stdout(Stdio::piped())
75        .stderr(Stdio::piped())
76        // Fail fast instead of prompting for credentials / hanging.
77        .env("GIT_TERMINAL_PROMPT", "0")
78        .env("GCM_INTERACTIVE", "never")
79        .env("GIT_ASKPASS", "")
80        .env("SSH_ASKPASS", "");
81    for (k, v) in env {
82        cmd.env(k, v);
83    }
84
85    let mut child = cmd
86        .spawn()
87        .map_err(|e| format!("failed to start git (is it installed?): {e}"))?;
88
89    let mut out_pipe = child.stdout.take();
90    let mut err_pipe = child.stderr.take();
91    let out_handle = std::thread::spawn(move || drain(out_pipe.as_mut()));
92    let err_handle = std::thread::spawn(move || drain(err_pipe.as_mut()));
93
94    let start = Instant::now();
95    let status = loop {
96        match child.try_wait() {
97            Ok(Some(status)) => break status,
98            Ok(None) => {
99                if start.elapsed() >= timeout {
100                    let _ = child.kill();
101                    let _ = child.wait();
102                    return Err(format!("git timed out after {}s", timeout.as_secs()));
103                }
104                std::thread::sleep(Duration::from_millis(40));
105            }
106            Err(e) => return Err(format!("git wait failed: {e}")),
107        }
108    };
109
110    let stdout = out_handle.join().unwrap_or_default();
111    let stderr = err_handle.join().unwrap_or_default();
112    Ok(GitOutput {
113        stdout,
114        stderr,
115        success: status.success(),
116    })
117}
118
119fn drain(pipe: Option<&mut impl Read>) -> String {
120    let mut buf = String::new();
121    if let Some(p) = pipe {
122        let _ = p.read_to_string(&mut buf);
123    }
124    buf
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    /// These tests check what `run_git` reports, not how fast git is. A loaded
132    /// Windows runner has taken more than 5 s for a plain `rev-parse`.
133    const TEST_TIMEOUT: Duration = Duration::from_secs(30);
134
135    #[test]
136    fn git_version_runs() {
137        if !git_available() {
138            return; // CI without git — nothing to assert
139        }
140        let out =
141            run_git(&["--version"], Path::new("."), TEST_TIMEOUT, &[]).expect("git --version");
142        assert!(out.success);
143        assert!(out.stdout.to_lowercase().contains("git version"));
144    }
145
146    #[test]
147    fn failed_command_surfaces_stderr() {
148        if !git_available() {
149            return;
150        }
151        let out = run_git(
152            &["rev-parse", "--verify", "definitely-not-a-ref"],
153            Path::new("."),
154            TEST_TIMEOUT,
155            &[],
156        )
157        .expect("git should run");
158        assert!(!out.success);
159        assert!(out.ok_stdout().is_err());
160    }
161}