Skip to main content

git_cli/
commit_shared.rs

1use anyhow::{Context, Result, anyhow};
2use nils_common::git as common_git;
3use std::process::Output;
4
5pub(crate) fn trim_trailing_newlines(input: &str) -> String {
6    common_git::trim_trailing_newlines(input)
7}
8
9pub(crate) fn git_output(args: &[&str]) -> Result<Output> {
10    let output = run_git_output(args).with_context(|| format!("spawn git {:?}", args))?;
11    if !output.status.success() {
12        return Err(anyhow!(
13            "git {:?} failed: {}{}",
14            args,
15            String::from_utf8_lossy(&output.stderr),
16            String::from_utf8_lossy(&output.stdout),
17        ));
18    }
19    Ok(output)
20}
21
22pub(crate) fn git_output_optional(args: &[&str]) -> Option<Output> {
23    let output = run_git_output(args).ok()?;
24    if !output.status.success() {
25        return None;
26    }
27    Some(output)
28}
29
30pub(crate) fn git_status_success(args: &[&str]) -> bool {
31    common_git::run_status_quiet(args)
32        .map(|status| status.success())
33        .unwrap_or(false)
34}
35
36pub(crate) fn git_status_code(args: &[&str]) -> Option<i32> {
37    common_git::run_status_quiet(args)
38        .ok()
39        .map(|status| status.code().unwrap_or(1))
40}
41
42pub(crate) fn git_stdout_trimmed(args: &[&str]) -> Result<String> {
43    let output = git_output(args)?;
44    Ok(trim_trailing_newlines(&String::from_utf8_lossy(
45        &output.stdout,
46    )))
47}
48
49pub(crate) fn git_stdout_trimmed_optional(args: &[&str]) -> Option<String> {
50    let output = git_output_optional(args)?;
51    let out = trim_trailing_newlines(&String::from_utf8_lossy(&output.stdout));
52    if out.is_empty() { None } else { Some(out) }
53}
54
55fn run_git_output(args: &[&str]) -> std::io::Result<Output> {
56    common_git::run_output(args)
57}
58
59#[derive(Debug, Clone)]
60pub(crate) struct NameStatusEntry {
61    pub status_raw: String,
62    pub path: String,
63    pub old_path: Option<String>,
64}
65
66pub(crate) fn parse_name_status_z(bytes: &[u8]) -> Result<Vec<NameStatusEntry>> {
67    let parsed = common_git::parse_name_status_z(bytes).map_err(|err| anyhow!("{err}"))?;
68    Ok(parsed
69        .into_iter()
70        .map(|entry| NameStatusEntry {
71            status_raw: String::from_utf8_lossy(entry.status_raw).to_string(),
72            path: String::from_utf8_lossy(entry.path).to_string(),
73            old_path: entry
74                .old_path
75                .map(|old_path| String::from_utf8_lossy(old_path).to_string()),
76        })
77        .collect())
78}
79
80#[derive(Debug, Clone, Copy)]
81pub(crate) struct DiffNumstat {
82    pub added: Option<i64>,
83    pub deleted: Option<i64>,
84    pub binary: bool,
85}
86
87pub(crate) fn diff_numstat(path: &str) -> Result<DiffNumstat> {
88    let output = git_stdout_trimmed(&[
89        "-c",
90        "core.quotepath=false",
91        "diff",
92        "--cached",
93        "--numstat",
94        "--",
95        path,
96    ])?;
97
98    let line = output.lines().next().unwrap_or("");
99    if line.trim().is_empty() {
100        return Ok(DiffNumstat {
101            added: None,
102            deleted: None,
103            binary: false,
104        });
105    }
106
107    let mut parts = line.split('\t');
108    let added = parts.next().unwrap_or("");
109    let deleted = parts.next().unwrap_or("");
110
111    if added == "-" || deleted == "-" {
112        return Ok(DiffNumstat {
113            added: None,
114            deleted: None,
115            binary: true,
116        });
117    }
118
119    let added_num = added.parse::<i64>().ok();
120    let deleted_num = deleted.parse::<i64>().ok();
121
122    Ok(DiffNumstat {
123        added: added_num,
124        deleted: deleted_num,
125        binary: false,
126    })
127}
128
129pub(crate) fn is_lockfile(path: &str) -> bool {
130    common_git::is_lockfile_path(path)
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use nils_test_support::git::{InitRepoOptions, commit_file, git, init_repo_with};
137    use nils_test_support::{CwdGuard, GlobalStateLock};
138    use pretty_assertions::assert_eq;
139    use std::fs;
140
141    #[test]
142    fn parse_name_status_z_handles_rename_and_copy() {
143        let bytes = b"R100\0old.txt\0new.txt\0C90\0src.rs\0dst.rs\0M\0file.txt\0";
144        let entries = parse_name_status_z(bytes).expect("parse name-status");
145
146        assert_eq!(entries.len(), 3);
147        assert_eq!(entries[0].status_raw, "R100");
148        assert_eq!(entries[0].path, "new.txt");
149        assert_eq!(entries[0].old_path.as_deref(), Some("old.txt"));
150        assert_eq!(entries[1].status_raw, "C90");
151        assert_eq!(entries[1].path, "dst.rs");
152        assert_eq!(entries[1].old_path.as_deref(), Some("src.rs"));
153        assert_eq!(entries[2].status_raw, "M");
154        assert_eq!(entries[2].path, "file.txt");
155        assert_eq!(entries[2].old_path, None);
156    }
157
158    #[test]
159    fn parse_name_status_z_errors_on_malformed_input() {
160        let err = parse_name_status_z(b"R100\0old.txt\0").expect_err("expected parse failure");
161        assert!(
162            err.to_string().contains("malformed name-status output"),
163            "unexpected error: {err}"
164        );
165    }
166
167    #[test]
168    fn diff_numstat_reports_counts_for_text_changes() {
169        let lock = GlobalStateLock::new();
170        let repo = init_repo_with(InitRepoOptions::new().with_initial_commit());
171        commit_file(repo.path(), "file.txt", "one\n", "add file");
172        fs::write(repo.path().join("file.txt"), "one\ntwo\nthree\n").expect("write file");
173        git(repo.path(), &["add", "file.txt"]);
174
175        let _cwd = CwdGuard::set(&lock, repo.path()).expect("cwd");
176        let diff = diff_numstat("file.txt").expect("diff numstat");
177
178        assert_eq!(diff.added, Some(2));
179        assert_eq!(diff.deleted, Some(0));
180        assert!(!diff.binary);
181    }
182
183    #[test]
184    fn diff_numstat_reports_binary_for_binary_file() {
185        let lock = GlobalStateLock::new();
186        let repo = init_repo_with(InitRepoOptions::new().with_initial_commit());
187        fs::write(repo.path().join("bin.dat"), b"\x00\x01binary\x00").expect("write bin");
188        git(repo.path(), &["add", "bin.dat"]);
189
190        let _cwd = CwdGuard::set(&lock, repo.path()).expect("cwd");
191        let diff = diff_numstat("bin.dat").expect("diff numstat");
192
193        assert!(diff.binary);
194        assert_eq!(diff.added, None);
195        assert_eq!(diff.deleted, None);
196    }
197
198    #[test]
199    fn diff_numstat_reports_none_when_no_changes() {
200        let lock = GlobalStateLock::new();
201        let repo = init_repo_with(InitRepoOptions::new().with_initial_commit());
202        commit_file(repo.path(), "file.txt", "one\n", "add file");
203
204        let _cwd = CwdGuard::set(&lock, repo.path()).expect("cwd");
205        let diff = diff_numstat("file.txt").expect("diff numstat");
206
207        assert_eq!(diff.added, None);
208        assert_eq!(diff.deleted, None);
209        assert!(!diff.binary);
210    }
211
212    #[test]
213    fn is_lockfile_detects_known_names() {
214        for name in [
215            "yarn.lock",
216            "package-lock.json",
217            "pnpm-lock.yaml",
218            "bun.lockb",
219            "bun.lock",
220            "npm-shrinkwrap.json",
221            "path/to/yarn.lock",
222        ] {
223            assert!(is_lockfile(name), "expected {name} to be a lockfile");
224        }
225
226        assert!(!is_lockfile("Cargo.lock"));
227        assert!(!is_lockfile("README.md"));
228    }
229}