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 is_shallow_repo() -> Result<bool, GitError> {
164    let output = capture_git_output(&["rev-parse", "--is-shallow-repository"], &None)?;
165
166    Ok(output.stdout.starts_with("true"))
167}
168
169pub(super) fn parse_git_version(version: &str) -> Result<(i32, i32, i32)> {
170    let version = version
171        .split_whitespace()
172        .nth(2)
173        .ok_or(anyhow!("Could not find git version in string {version}"))?;
174    match version.split('.').collect_vec()[..] {
175        [major, minor, patch] => Ok((major.parse()?, minor.parse()?, patch.parse()?)),
176        _ => Err(anyhow!("Failed determine semantic version from {version}")),
177    }
178}
179
180fn get_git_version() -> Result<(i32, i32, i32)> {
181    let version = capture_git_output(&["--version"], &None)
182        .context("Determine git version")?
183        .stdout;
184    parse_git_version(&version)
185}
186
187fn concat_version(version_tuple: (i32, i32, i32)) -> String {
188    format!(
189        "{}.{}.{}",
190        version_tuple.0, version_tuple.1, version_tuple.2
191    )
192}
193
194pub fn check_git_version() -> Result<()> {
195    let version_tuple = get_git_version().context("Determining compatible git version")?;
196    if version_tuple < EXPECTED_VERSION {
197        bail!(
198            "Version {} is smaller than {}",
199            concat_version(version_tuple),
200            concat_version(EXPECTED_VERSION)
201        )
202    }
203    Ok(())
204}
205
206#[cfg(test)]
207mod test {
208    use super::*;
209    use std::env::set_current_dir;
210
211    use serial_test::serial;
212    use tempfile::{tempdir, TempDir};
213
214    fn run_git_command(args: &[&str], dir: &Path) {
215        assert!(process::Command::new("git")
216            .args(args)
217            .envs([
218                ("GIT_CONFIG_NOSYSTEM", "true"),
219                ("GIT_CONFIG_GLOBAL", "/dev/null"),
220                ("GIT_AUTHOR_NAME", "testuser"),
221                ("GIT_AUTHOR_EMAIL", "testuser@example.com"),
222                ("GIT_COMMITTER_NAME", "testuser"),
223                ("GIT_COMMITTER_EMAIL", "testuser@example.com"),
224            ])
225            .current_dir(dir)
226            .stdout(Stdio::null())
227            .stderr(Stdio::null())
228            .status()
229            .expect("Failed to spawn git command")
230            .success());
231    }
232
233    fn init_repo(dir: &Path) {
234        run_git_command(&["init", "--initial-branch", "master"], dir);
235        run_git_command(&["commit", "--allow-empty", "-m", "Initial commit"], dir);
236    }
237
238    fn dir_with_repo() -> TempDir {
239        let tempdir = tempdir().unwrap();
240        init_repo(tempdir.path());
241        tempdir
242    }
243
244    #[test]
245    #[serial]
246    fn test_get_head_revision() {
247        let repo_dir = dir_with_repo();
248        set_current_dir(repo_dir.path()).expect("Failed to change dir");
249        let revision = internal_get_head_revision().unwrap();
250        assert!(
251            &revision.chars().all(|c| c.is_ascii_alphanumeric()),
252            "'{}' contained non alphanumeric or non ASCII characters",
253            &revision
254        )
255    }
256
257    #[test]
258    fn test_parse_git_version() {
259        let version = parse_git_version("git version 2.52.0");
260        assert_eq!(version.unwrap(), (2, 52, 0));
261
262        let version = parse_git_version("git version 2.52.0\n");
263        assert_eq!(version.unwrap(), (2, 52, 0));
264    }
265}