git_perf/git/
git_lowlevel.rs

1use super::{
2    git_definitions::EXPECTED_VERSION,
3    git_types::{GitError, GitOutput},
4};
5
6use std::{
7    env::current_dir,
8    io::{self, BufWriter, Write},
9    path::{Path, PathBuf},
10    process::{self, Child, Stdio},
11};
12
13use log::{debug, trace};
14
15use anyhow::{anyhow, bail, Context, Result};
16use itertools::Itertools;
17
18pub(super) fn spawn_git_command(
19    args: &[&str],
20    working_dir: &Option<&Path>,
21    stdin: Option<Stdio>,
22) -> Result<Child, io::Error> {
23    let working_dir = working_dir.map(PathBuf::from).unwrap_or(current_dir()?);
24    // Disable Git's automatic maintenance to prevent interference with concurrent operations
25    let default_pre_args = [
26        "-c",
27        "gc.auto=0",
28        "-c",
29        "maintenance.auto=0",
30        "-c",
31        "fetch.fsckObjects=false",
32    ];
33    let stdin = stdin.unwrap_or(Stdio::null());
34    let all_args: Vec<_> = default_pre_args.iter().chain(args.iter()).collect();
35    debug!("execute: git {}", all_args.iter().join(" "));
36    process::Command::new("git")
37        .env("LANG", "C.UTF-8")
38        .env("LC_ALL", "C.UTF-8")
39        .env("LANGUAGE", "C.UTF-8")
40        .stdin(stdin)
41        .stdout(Stdio::piped())
42        .stderr(Stdio::piped())
43        .current_dir(working_dir)
44        .args(all_args)
45        .spawn()
46}
47
48pub(super) fn capture_git_output(
49    args: &[&str],
50    working_dir: &Option<&Path>,
51) -> Result<GitOutput, GitError> {
52    feed_git_command(args, working_dir, None)
53}
54
55pub(super) fn feed_git_command(
56    args: &[&str],
57    working_dir: &Option<&Path>,
58    input: Option<&str>,
59) -> Result<GitOutput, GitError> {
60    let stdin = input.map(|_| Stdio::piped());
61
62    let child = spawn_git_command(args, working_dir, stdin)?;
63
64    debug!("input: {}", input.unwrap_or(""));
65
66    let output = match child.stdin {
67        Some(ref stdin) => {
68            let mut writer = BufWriter::new(stdin);
69            writer.write_all(input.unwrap().as_bytes())?;
70            drop(writer);
71            child.wait_with_output()
72        }
73        None => child.wait_with_output(),
74    }?;
75
76    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
77    trace!("stdout: {stdout}");
78
79    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
80    trace!("stderr: {stderr}");
81
82    let git_output = GitOutput { stdout, stderr };
83
84    if output.status.success() {
85        trace!("exec succeeded");
86        Ok(git_output)
87    } else {
88        trace!("exec failed");
89        Err(GitError::ExecError {
90            command: args.join(" "),
91            output: git_output,
92        })
93    }
94}
95
96pub(super) fn map_git_error(err: GitError) -> GitError {
97    // Parsing error messasges is not a very good idea, but(!) there are no consistent + documented error code for these cases.
98    // This is tested by the git compatibility check and we add an explicit LANG to the git invocation.
99    match err {
100        GitError::ExecError { command: _, output } if output.stderr.contains("cannot lock ref") => {
101            GitError::RefFailedToLock { output }
102        }
103        GitError::ExecError { command: _, output } if output.stderr.contains("but expected") => {
104            GitError::RefConcurrentModification { output }
105        }
106        GitError::ExecError { command: _, output } if output.stderr.contains("find remote ref") => {
107            GitError::NoRemoteMeasurements { output }
108        }
109        GitError::ExecError { command: _, output } if output.stderr.contains("bad object") => {
110            GitError::BadObject { output }
111        }
112        _ => err,
113    }
114}
115
116pub(super) fn get_git_perf_remote(remote: &str) -> Option<String> {
117    capture_git_output(&["remote", "get-url", remote], &None)
118        .ok()
119        .map(|s| s.stdout.trim().to_owned())
120}
121
122pub(super) fn set_git_perf_remote(remote: &str, url: &str) -> Result<(), GitError> {
123    capture_git_output(&["remote", "add", remote, url], &None).map(|_| ())
124}
125
126pub(super) fn git_update_ref(commands: impl AsRef<str>) -> Result<(), GitError> {
127    feed_git_command(
128        &[
129            "update-ref",
130            // When updating existing symlinks, we want to update the source symlink and not its target
131            "--no-deref",
132            "--stdin",
133        ],
134        &None,
135        Some(commands.as_ref()),
136    )
137    .map_err(map_git_error)
138    .map(|_| ())
139}
140
141pub fn get_head_revision() -> Result<String> {
142    Ok(internal_get_head_revision()?)
143}
144
145pub(super) fn internal_get_head_revision() -> Result<String, GitError> {
146    git_rev_parse("HEAD")
147}
148
149pub(super) fn git_rev_parse(reference: &str) -> Result<String, GitError> {
150    capture_git_output(&["rev-parse", "--verify", "-q", reference], &None)
151        .map_err(|_e| GitError::MissingHead {
152            reference: reference.into(),
153        })
154        .map(|s| s.stdout.trim().to_owned())
155}
156
157pub(super) fn git_rev_parse_symbolic_ref(reference: &str) -> Option<String> {
158    capture_git_output(&["symbolic-ref", "-q", reference], &None)
159        .ok()
160        .map(|s| s.stdout.trim().to_owned())
161}
162
163pub(super) fn git_symbolic_ref_create_or_update(
164    reference: &str,
165    target: &str,
166) -> Result<(), GitError> {
167    capture_git_output(&["symbolic-ref", reference, target], &None)
168        .map_err(map_git_error)
169        .map(|_| ())
170}
171
172pub fn is_shallow_repo() -> Result<bool, GitError> {
173    let output = capture_git_output(&["rev-parse", "--is-shallow-repository"], &None)?;
174
175    Ok(output.stdout.starts_with("true"))
176}
177
178pub(super) fn parse_git_version(version: &str) -> Result<(i32, i32, i32)> {
179    let version = version
180        .split_whitespace()
181        .nth(2)
182        .ok_or(anyhow!("Could not find git version in string {version}"))?;
183    match version.split('.').collect_vec()[..] {
184        [major, minor, patch] => Ok((major.parse()?, minor.parse()?, patch.parse()?)),
185        _ => Err(anyhow!("Failed determine semantic version from {version}")),
186    }
187}
188
189fn get_git_version() -> Result<(i32, i32, i32)> {
190    let version = capture_git_output(&["--version"], &None)
191        .context("Determine git version")?
192        .stdout;
193    parse_git_version(&version)
194}
195
196fn concat_version(version_tuple: (i32, i32, i32)) -> String {
197    format!(
198        "{}.{}.{}",
199        version_tuple.0, version_tuple.1, version_tuple.2
200    )
201}
202
203pub fn check_git_version() -> Result<()> {
204    let version_tuple = get_git_version().context("Determining compatible git version")?;
205    if version_tuple < EXPECTED_VERSION {
206        bail!(
207            "Version {} is smaller than {}",
208            concat_version(version_tuple),
209            concat_version(EXPECTED_VERSION)
210        )
211    }
212    Ok(())
213}
214
215/// Get the repository root directory using git
216pub fn get_repository_root() -> Result<String, String> {
217    let output = capture_git_output(&["rev-parse", "--show-toplevel"], &None)
218        .map_err(|e| format!("Failed to get repository root: {}", e))?;
219    Ok(output.stdout.trim().to_string())
220}
221
222#[cfg(test)]
223mod test {
224    use super::*;
225    use crate::test_helpers::dir_with_repo;
226    use std::env::set_current_dir;
227
228    #[test]
229    fn test_get_head_revision() {
230        let repo_dir = dir_with_repo();
231        set_current_dir(repo_dir.path()).expect("Failed to change dir");
232        let revision = internal_get_head_revision().unwrap();
233        assert!(
234            &revision.chars().all(|c| c.is_ascii_alphanumeric()),
235            "'{}' contained non alphanumeric or non ASCII characters",
236            &revision
237        )
238    }
239
240    #[test]
241    fn test_parse_git_version() {
242        let version = parse_git_version("git version 2.52.0");
243        assert_eq!(version.unwrap(), (2, 52, 0));
244
245        let version = parse_git_version("git version 2.52.0\n");
246        assert_eq!(version.unwrap(), (2, 52, 0));
247    }
248
249    #[test]
250    fn test_map_git_error_ref_failed_to_lock() {
251        let output = GitOutput {
252            stdout: String::new(),
253            stderr: "fatal: cannot lock ref 'refs/heads/main': Unable to create lock".to_string(),
254        };
255        let error = GitError::ExecError {
256            command: "update-ref".to_string(),
257            output,
258        };
259
260        let mapped = map_git_error(error);
261        assert!(matches!(mapped, GitError::RefFailedToLock { .. }));
262    }
263
264    #[test]
265    fn test_map_git_error_ref_concurrent_modification() {
266        let output = GitOutput {
267            stdout: String::new(),
268            stderr: "fatal: ref updates forbidden, but expected commit abc123".to_string(),
269        };
270        let error = GitError::ExecError {
271            command: "update-ref".to_string(),
272            output,
273        };
274
275        let mapped = map_git_error(error);
276        assert!(matches!(mapped, GitError::RefConcurrentModification { .. }));
277    }
278
279    #[test]
280    fn test_map_git_error_no_remote_measurements() {
281        let output = GitOutput {
282            stdout: String::new(),
283            stderr: "fatal: couldn't find remote ref refs/notes/measurements".to_string(),
284        };
285        let error = GitError::ExecError {
286            command: "fetch".to_string(),
287            output,
288        };
289
290        let mapped = map_git_error(error);
291        assert!(matches!(mapped, GitError::NoRemoteMeasurements { .. }));
292    }
293
294    #[test]
295    fn test_map_git_error_bad_object() {
296        let output = GitOutput {
297            stdout: String::new(),
298            stderr: "error: bad object abc123def456".to_string(),
299        };
300        let error = GitError::ExecError {
301            command: "cat-file".to_string(),
302            output,
303        };
304
305        let mapped = map_git_error(error);
306        assert!(matches!(mapped, GitError::BadObject { .. }));
307    }
308
309    #[test]
310    fn test_map_git_error_unmapped() {
311        let output = GitOutput {
312            stdout: String::new(),
313            stderr: "fatal: some other error".to_string(),
314        };
315        let error = GitError::ExecError {
316            command: "status".to_string(),
317            output,
318        };
319
320        let mapped = map_git_error(error);
321        // Should remain as ExecError for unrecognized patterns
322        assert!(matches!(mapped, GitError::ExecError { .. }));
323    }
324
325    #[test]
326    fn test_map_git_error_false_positive_avoidance() {
327        // Test that partial matches don't trigger false positives
328        let output = GitOutput {
329            stdout: String::new(),
330            stderr: "this message mentions 'lock' without the full pattern".to_string(),
331        };
332        let error = GitError::ExecError {
333            command: "test".to_string(),
334            output,
335        };
336
337        let mapped = map_git_error(error);
338        // Should NOT be mapped to RefFailedToLock
339        assert!(matches!(mapped, GitError::ExecError { .. }));
340    }
341
342    #[test]
343    fn test_map_git_error_cannot_lock_ref_pattern_must_match() {
344        // Test that "cannot lock ref" must be present (not just "lock")
345        let test_cases = vec![
346            ("fatal: cannot lock ref 'refs/heads/main'", true),
347            ("error: cannot lock ref update", true),
348            ("fatal: failed to lock something", false),
349            ("error: lock failed", false),
350        ];
351
352        for (stderr_msg, should_map) in test_cases {
353            let output = GitOutput {
354                stdout: String::new(),
355                stderr: stderr_msg.to_string(),
356            };
357            let error = GitError::ExecError {
358                command: "test".to_string(),
359                output,
360            };
361
362            let mapped = map_git_error(error);
363            if should_map {
364                assert!(
365                    matches!(mapped, GitError::RefFailedToLock { .. }),
366                    "Expected RefFailedToLock for: {}",
367                    stderr_msg
368                );
369            } else {
370                assert!(
371                    matches!(mapped, GitError::ExecError { .. }),
372                    "Expected ExecError for: {}",
373                    stderr_msg
374                );
375            }
376        }
377    }
378
379    #[test]
380    fn test_map_git_error_but_expected_pattern_must_match() {
381        // Test that "but expected" must be present
382        let test_cases = vec![
383            ("fatal: but expected commit abc123", true),
384            ("error: ref update failed but expected something", true),
385            ("fatal: expected something", false),
386            ("error: only mentioned the word but", false),
387        ];
388
389        for (stderr_msg, should_map) in test_cases {
390            let output = GitOutput {
391                stdout: String::new(),
392                stderr: stderr_msg.to_string(),
393            };
394            let error = GitError::ExecError {
395                command: "test".to_string(),
396                output,
397            };
398
399            let mapped = map_git_error(error);
400            if should_map {
401                assert!(
402                    matches!(mapped, GitError::RefConcurrentModification { .. }),
403                    "Expected RefConcurrentModification for: {}",
404                    stderr_msg
405                );
406            } else {
407                assert!(
408                    matches!(mapped, GitError::ExecError { .. }),
409                    "Expected ExecError for: {}",
410                    stderr_msg
411                );
412            }
413        }
414    }
415}