Skip to main content

nils_common/
git.rs

1use std::error::Error;
2use std::fmt;
3use std::io;
4use std::path::{Path, PathBuf};
5use std::process::{Command, ExitStatus, Output, Stdio};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum GitContextError {
9    GitNotFound,
10    NotRepository,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum NameStatusParseError {
15    MalformedOutput,
16}
17
18impl fmt::Display for NameStatusParseError {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            NameStatusParseError::MalformedOutput => {
22                write!(f, "error: malformed name-status output")
23            }
24        }
25    }
26}
27
28impl Error for NameStatusParseError {}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct NameStatusZEntry<'a> {
32    pub status_raw: &'a [u8],
33    pub path: &'a [u8],
34    pub old_path: Option<&'a [u8]>,
35}
36
37pub fn parse_name_status_z(buf: &[u8]) -> Result<Vec<NameStatusZEntry<'_>>, NameStatusParseError> {
38    let parts: Vec<&[u8]> = buf
39        .split(|b| *b == 0)
40        .filter(|part| !part.is_empty())
41        .collect();
42    let mut out: Vec<NameStatusZEntry<'_>> = Vec::new();
43    let mut i = 0;
44
45    while i < parts.len() {
46        let status_raw = parts[i];
47        i += 1;
48
49        if matches!(status_raw.first(), Some(b'R' | b'C')) {
50            let old = *parts.get(i).ok_or(NameStatusParseError::MalformedOutput)?;
51            let new = *parts
52                .get(i + 1)
53                .ok_or(NameStatusParseError::MalformedOutput)?;
54            i += 2;
55            out.push(NameStatusZEntry {
56                status_raw,
57                path: new,
58                old_path: Some(old),
59            });
60        } else {
61            let file = *parts.get(i).ok_or(NameStatusParseError::MalformedOutput)?;
62            i += 1;
63            out.push(NameStatusZEntry {
64                status_raw,
65                path: file,
66                old_path: None,
67            });
68        }
69    }
70
71    Ok(out)
72}
73
74pub fn is_lockfile_path(path: &str) -> bool {
75    let name = Path::new(path)
76        .file_name()
77        .and_then(|segment| segment.to_str())
78        .unwrap_or("");
79    matches!(
80        name,
81        "yarn.lock"
82            | "package-lock.json"
83            | "pnpm-lock.yaml"
84            | "bun.lockb"
85            | "bun.lock"
86            | "npm-shrinkwrap.json"
87    )
88}
89
90pub fn run_output(args: &[&str]) -> io::Result<Output> {
91    run_output_inner(None, args)
92}
93
94pub fn run_output_in(cwd: &Path, args: &[&str]) -> io::Result<Output> {
95    run_output_inner(Some(cwd), args)
96}
97
98pub fn run_status_quiet(args: &[&str]) -> io::Result<ExitStatus> {
99    run_status_quiet_inner(None, args)
100}
101
102pub fn run_status_quiet_in(cwd: &Path, args: &[&str]) -> io::Result<ExitStatus> {
103    run_status_quiet_inner(Some(cwd), args)
104}
105
106pub fn run_status_inherit(args: &[&str]) -> io::Result<ExitStatus> {
107    run_status_inherit_inner(None, args)
108}
109
110pub fn run_status_inherit_in(cwd: &Path, args: &[&str]) -> io::Result<ExitStatus> {
111    run_status_inherit_inner(Some(cwd), args)
112}
113
114pub fn is_git_available() -> bool {
115    run_status_quiet(&["--version"])
116        .map(|status| status.success())
117        .unwrap_or(false)
118}
119
120pub fn require_repo() -> Result<(), GitContextError> {
121    require_context(None, &["rev-parse", "--git-dir"])
122}
123
124pub fn require_repo_in(cwd: &Path) -> Result<(), GitContextError> {
125    require_context(Some(cwd), &["rev-parse", "--git-dir"])
126}
127
128pub fn require_work_tree() -> Result<(), GitContextError> {
129    require_context(None, &["rev-parse", "--is-inside-work-tree"])
130}
131
132pub fn require_work_tree_in(cwd: &Path) -> Result<(), GitContextError> {
133    require_context(Some(cwd), &["rev-parse", "--is-inside-work-tree"])
134}
135
136pub fn is_inside_work_tree() -> io::Result<bool> {
137    Ok(run_status_quiet(&["rev-parse", "--is-inside-work-tree"])?.success())
138}
139
140pub fn is_inside_work_tree_in(cwd: &Path) -> io::Result<bool> {
141    Ok(run_status_quiet_in(cwd, &["rev-parse", "--is-inside-work-tree"])?.success())
142}
143
144pub fn is_git_repo() -> io::Result<bool> {
145    Ok(run_status_quiet(&["rev-parse", "--git-dir"])?.success())
146}
147
148pub fn is_git_repo_in(cwd: &Path) -> io::Result<bool> {
149    Ok(run_status_quiet_in(cwd, &["rev-parse", "--git-dir"])?.success())
150}
151
152pub fn repo_root() -> io::Result<Option<PathBuf>> {
153    let output = run_output(&["rev-parse", "--show-toplevel"])?;
154    Ok(trimmed_stdout_if_success(&output).map(PathBuf::from))
155}
156
157pub fn repo_root_in(cwd: &Path) -> io::Result<Option<PathBuf>> {
158    let output = run_output_in(cwd, &["rev-parse", "--show-toplevel"])?;
159    Ok(trimmed_stdout_if_success(&output).map(PathBuf::from))
160}
161
162pub fn rev_parse(args: &[&str]) -> io::Result<Option<String>> {
163    let output = run_output(&rev_parse_args(args))?;
164    Ok(trimmed_stdout_if_success(&output))
165}
166
167pub fn rev_parse_in(cwd: &Path, args: &[&str]) -> io::Result<Option<String>> {
168    let output = run_output_in(cwd, &rev_parse_args(args))?;
169    Ok(trimmed_stdout_if_success(&output))
170}
171
172fn run_output_inner(cwd: Option<&Path>, args: &[&str]) -> io::Result<Output> {
173    let mut cmd = Command::new("git");
174    cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
175    if let Some(cwd) = cwd {
176        cmd.current_dir(cwd);
177    }
178    cmd.output()
179}
180
181fn run_status_quiet_inner(cwd: Option<&Path>, args: &[&str]) -> io::Result<ExitStatus> {
182    let mut cmd = Command::new("git");
183    cmd.args(args).stdout(Stdio::null()).stderr(Stdio::null());
184    if let Some(cwd) = cwd {
185        cmd.current_dir(cwd);
186    }
187    cmd.status()
188}
189
190fn run_status_inherit_inner(cwd: Option<&Path>, args: &[&str]) -> io::Result<ExitStatus> {
191    let mut cmd = Command::new("git");
192    cmd.args(args)
193        .stdout(Stdio::inherit())
194        .stderr(Stdio::inherit());
195    if let Some(cwd) = cwd {
196        cmd.current_dir(cwd);
197    }
198    cmd.status()
199}
200
201fn require_context(cwd: Option<&Path>, probe_args: &[&str]) -> Result<(), GitContextError> {
202    if !is_git_available() {
203        return Err(GitContextError::GitNotFound);
204    }
205
206    let in_context = match cwd {
207        Some(cwd) => run_status_quiet_in(cwd, probe_args),
208        None => run_status_quiet(probe_args),
209    }
210    .map(|status| status.success())
211    .unwrap_or(false);
212
213    if in_context {
214        Ok(())
215    } else {
216        Err(GitContextError::NotRepository)
217    }
218}
219
220fn rev_parse_args<'a>(args: &'a [&'a str]) -> Vec<&'a str> {
221    let mut full = Vec::with_capacity(args.len() + 1);
222    full.push("rev-parse");
223    full.extend_from_slice(args);
224    full
225}
226
227fn trimmed_stdout_if_success(output: &Output) -> Option<String> {
228    if !output.status.success() {
229        return None;
230    }
231
232    let trimmed = String::from_utf8_lossy(&output.stdout).trim().to_string();
233    if trimmed.is_empty() {
234        None
235    } else {
236        Some(trimmed)
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243    use nils_test_support::git::{InitRepoOptions, git as run_git, init_repo_with};
244    use nils_test_support::{CwdGuard, EnvGuard, GlobalStateLock};
245    use pretty_assertions::assert_eq;
246    use tempfile::TempDir;
247
248    #[test]
249    fn run_output_in_preserves_nonzero_status() {
250        let repo = init_repo_with(InitRepoOptions::new());
251
252        let output = run_output_in(repo.path(), &["rev-parse", "--verify", "HEAD"])
253            .expect("run output in repo");
254
255        assert!(!output.status.success());
256        assert!(!output.stderr.is_empty());
257    }
258
259    #[test]
260    fn run_status_quiet_in_returns_success_and_failure_statuses() {
261        let repo = init_repo_with(InitRepoOptions::new());
262
263        let ok =
264            run_status_quiet_in(repo.path(), &["rev-parse", "--git-dir"]).expect("status success");
265        let bad = run_status_quiet_in(repo.path(), &["rev-parse", "--verify", "HEAD"])
266            .expect("status failure");
267
268        assert!(ok.success());
269        assert!(!bad.success());
270    }
271
272    #[test]
273    fn is_git_repo_in_and_is_inside_work_tree_in_match_repo_context() {
274        let repo = init_repo_with(InitRepoOptions::new());
275        let outside = TempDir::new().expect("tempdir");
276
277        assert!(is_git_repo_in(repo.path()).expect("is_git_repo in repo"));
278        assert!(is_inside_work_tree_in(repo.path()).expect("is_inside_work_tree in repo"));
279        assert!(!is_git_repo_in(outside.path()).expect("is_git_repo outside repo"));
280        assert!(!is_inside_work_tree_in(outside.path()).expect("is_inside_work_tree outside repo"));
281    }
282
283    #[test]
284    fn repo_root_in_returns_root_or_none() {
285        let repo = init_repo_with(InitRepoOptions::new());
286        let outside = TempDir::new().expect("tempdir");
287        let expected_root = run_git(repo.path(), &["rev-parse", "--show-toplevel"])
288            .trim()
289            .to_string();
290
291        assert_eq!(
292            repo_root_in(repo.path()).expect("repo_root_in repo"),
293            Some(expected_root.into())
294        );
295        assert_eq!(
296            repo_root_in(outside.path()).expect("repo_root_in outside"),
297            None
298        );
299    }
300
301    #[test]
302    fn rev_parse_in_returns_value_or_none() {
303        let repo = init_repo_with(InitRepoOptions::new().with_initial_commit());
304        let head = run_git(repo.path(), &["rev-parse", "HEAD"])
305            .trim()
306            .to_string();
307
308        assert_eq!(
309            rev_parse_in(repo.path(), &["HEAD"]).expect("rev_parse head"),
310            Some(head)
311        );
312        assert_eq!(
313            rev_parse_in(repo.path(), &["--verify", "refs/heads/does-not-exist"])
314                .expect("rev_parse missing ref"),
315            None
316        );
317    }
318
319    #[test]
320    fn cwd_wrappers_delegate_to_in_variants() {
321        let lock = GlobalStateLock::new();
322        let repo = init_repo_with(InitRepoOptions::new().with_initial_commit());
323        let _cwd = CwdGuard::set(&lock, repo.path()).expect("set cwd");
324        let head = run_git(repo.path(), &["rev-parse", "HEAD"])
325            .trim()
326            .to_string();
327        let root = run_git(repo.path(), &["rev-parse", "--show-toplevel"])
328            .trim()
329            .to_string();
330
331        assert!(is_git_repo().expect("is_git_repo"));
332        assert!(is_inside_work_tree().expect("is_inside_work_tree"));
333        assert_eq!(require_repo(), Ok(()));
334        assert_eq!(require_work_tree(), Ok(()));
335        assert_eq!(repo_root().expect("repo_root"), Some(root.into()));
336        assert_eq!(rev_parse(&["HEAD"]).expect("rev_parse"), Some(head));
337    }
338
339    #[test]
340    fn require_work_tree_in_reports_missing_git_or_repo_state() {
341        let lock = GlobalStateLock::new();
342        let outside = TempDir::new().expect("tempdir");
343        let empty = TempDir::new().expect("tempdir");
344        let _path = EnvGuard::set(&lock, "PATH", &empty.path().to_string_lossy());
345
346        assert_eq!(
347            require_work_tree_in(outside.path()),
348            Err(GitContextError::GitNotFound)
349        );
350    }
351
352    #[test]
353    fn require_repo_and_work_tree_in_report_context_readiness() {
354        let repo = init_repo_with(InitRepoOptions::new());
355        let outside = TempDir::new().expect("tempdir");
356
357        assert_eq!(require_repo_in(repo.path()), Ok(()));
358        assert_eq!(require_work_tree_in(repo.path()), Ok(()));
359        assert_eq!(
360            require_repo_in(outside.path()),
361            Err(GitContextError::NotRepository)
362        );
363        assert_eq!(
364            require_work_tree_in(outside.path()),
365            Err(GitContextError::NotRepository)
366        );
367    }
368
369    #[test]
370    fn parse_name_status_z_handles_rename_copy_and_modify() {
371        let bytes = b"R100\0old.txt\0new.txt\0C90\0src.rs\0dst.rs\0M\0file.txt\0";
372        let entries = parse_name_status_z(bytes).expect("parse name-status");
373
374        assert_eq!(entries.len(), 3);
375        assert_eq!(entries[0].status_raw, b"R100");
376        assert_eq!(entries[0].path, b"new.txt");
377        assert_eq!(entries[0].old_path, Some(&b"old.txt"[..]));
378        assert_eq!(entries[1].status_raw, b"C90");
379        assert_eq!(entries[1].path, b"dst.rs");
380        assert_eq!(entries[1].old_path, Some(&b"src.rs"[..]));
381        assert_eq!(entries[2].status_raw, b"M");
382        assert_eq!(entries[2].path, b"file.txt");
383        assert_eq!(entries[2].old_path, None);
384    }
385
386    #[test]
387    fn parse_name_status_z_errors_on_malformed_output() {
388        let err = parse_name_status_z(b"R100\0old.txt\0").expect_err("expected parse error");
389        assert_eq!(err, NameStatusParseError::MalformedOutput);
390        assert_eq!(err.to_string(), "error: malformed name-status output");
391    }
392
393    #[test]
394    fn is_lockfile_path_matches_known_package_manager_lockfiles() {
395        for path in [
396            "yarn.lock",
397            "frontend/package-lock.json",
398            "subdir/pnpm-lock.yaml",
399            "bun.lockb",
400            "bun.lock",
401            "npm-shrinkwrap.json",
402        ] {
403            assert!(is_lockfile_path(path), "expected {path} to be a lockfile");
404        }
405
406        assert!(!is_lockfile_path("Cargo.lock"));
407        assert!(!is_lockfile_path("package-lock.json.bak"));
408    }
409}