lean_ctx_ext/core/git_util.rs
1// SPDX-License-Identifier: Apache-2.0
2//! Minimal, dependency-free git shell-outs shared by the context-artifact and
3//! analysis tools (`ctx_impact`, `ctx_architecture`, `context_artifacts`).
4//!
5//! These intentionally stay tiny and best-effort: a missing or failing git
6//! never aborts a tool, it just yields `false`/`None` so callers degrade
7//! gracefully.
8
9use std::path::Path;
10use std::process::{Command, Stdio};
11
12/// Returns `true` when the working tree at `project_root` has uncommitted
13/// changes. Any git failure (not a repo, git absent) reports `false`.
14pub fn git_dirty(project_root: &Path) -> bool {
15 let out = Command::new("git")
16 .args(["status", "--porcelain"])
17 .current_dir(project_root)
18 .stdout(Stdio::piped())
19 .stderr(Stdio::null())
20 .output();
21 match out {
22 Ok(o) if o.status.success() => !o.stdout.is_empty(),
23 _ => false,
24 }
25}
26
27/// Runs `git <args>` in `project_root` and returns trimmed stdout, or `None`
28/// on non-zero exit, non-UTF-8 output, empty output, or spawn failure.
29pub fn git_out(project_root: &Path, args: &[&str]) -> Option<String> {
30 let out = Command::new("git")
31 .args(args)
32 .current_dir(project_root)
33 .stdout(Stdio::piped())
34 .stderr(Stdio::null())
35 .output()
36 .ok()?;
37 if !out.status.success() {
38 return None;
39 }
40 let s = String::from_utf8(out.stdout).ok()?;
41 let s = s.trim().to_string();
42 if s.is_empty() { None } else { Some(s) }
43}