git-perf 0.20.0

Track, plot, and statistically validate simple measurements using git-notes for storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use super::{
    git_definitions::EXPECTED_VERSION,
    git_types::{GitError, GitOutput},
};

use std::{
    env::current_dir,
    io::{self, BufWriter, Write},
    path::{Path, PathBuf},
    process::{self, Child, Stdio},
};

use log::{debug, trace};

use anyhow::{anyhow, bail, Context, Result};
use itertools::Itertools;

pub(super) fn spawn_git_command(
    args: &[&str],
    working_dir: &Option<&Path>,
    stdin: Option<Stdio>,
) -> Result<Child, io::Error> {
    let working_dir = working_dir.map(PathBuf::from).unwrap_or(current_dir()?);
    // Disable Git's automatic maintenance to prevent interference with concurrent operations
    let default_pre_args = [
        "-c",
        "gc.auto=0",
        "-c",
        "maintenance.auto=0",
        "-c",
        "fetch.fsckObjects=false",
    ];
    let stdin = stdin.unwrap_or(Stdio::null());
    let all_args: Vec<_> = default_pre_args.iter().chain(args.iter()).collect();
    debug!("execute: git {}", all_args.iter().join(" "));
    process::Command::new("git")
        .env("LANG", "C.UTF-8")
        .env("LC_ALL", "C.UTF-8")
        .env("LANGUAGE", "C.UTF-8")
        .stdin(stdin)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .current_dir(working_dir)
        .args(all_args)
        .spawn()
}

pub(super) fn capture_git_output(
    args: &[&str],
    working_dir: &Option<&Path>,
) -> Result<GitOutput, GitError> {
    feed_git_command(args, working_dir, None)
}

pub(super) fn feed_git_command(
    args: &[&str],
    working_dir: &Option<&Path>,
    input: Option<&str>,
) -> Result<GitOutput, GitError> {
    let stdin = input.map(|_| Stdio::piped());

    let child = spawn_git_command(args, working_dir, stdin)?;

    debug!("input: {}", input.unwrap_or(""));

    let output = match child.stdin {
        Some(ref stdin) => {
            let mut writer = BufWriter::new(stdin);
            writer.write_all(input.unwrap().as_bytes())?;
            drop(writer);
            child.wait_with_output()
        }
        None => child.wait_with_output(),
    }?;

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    trace!("stdout: {stdout}");

    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    trace!("stderr: {stderr}");

    let git_output = GitOutput { stdout, stderr };

    if output.status.success() {
        trace!("exec succeeded");
        Ok(git_output)
    } else {
        trace!("exec failed");
        Err(GitError::ExecError {
            command: args.join(" "),
            output: git_output,
        })
    }
}

pub(super) fn map_git_error(err: GitError) -> GitError {
    // Parsing error messasges is not a very good idea, but(!) there are no consistent + documented error code for these cases.
    // This is tested by the git compatibility check and we add an explicit LANG to the git invocation.
    match err {
        GitError::ExecError { output, .. } if output.stderr.contains("cannot lock ref") => {
            GitError::RefFailedToLock { output }
        }
        GitError::ExecError { output, .. } if output.stderr.contains("but expected") => {
            GitError::RefConcurrentModification { output }
        }
        GitError::ExecError { output, .. } if output.stderr.contains("find remote ref") => {
            GitError::NoRemoteMeasurements { output }
        }
        GitError::ExecError { output, .. } if output.stderr.contains("bad object") => {
            GitError::BadObject { output }
        }
        GitError::ExecError { .. }
        | GitError::RefFailedToPush { .. }
        | GitError::MissingHead { .. }
        | GitError::RefFailedToLock { .. }
        | GitError::ShallowRepository
        | GitError::MissingMeasurements
        | GitError::RefConcurrentModification { .. }
        | GitError::NoRemoteMeasurements { .. }
        | GitError::NoUpstream {}
        | GitError::BadObject { .. }
        | GitError::IoError(_) => err,
    }
}

pub(super) fn get_git_perf_remote(remote: &str) -> Option<String> {
    capture_git_output(&["remote", "get-url", remote], &None)
        .ok()
        .map(|s| s.stdout.trim().to_owned())
}

pub(super) fn set_git_perf_remote(remote: &str, url: &str) -> Result<(), GitError> {
    capture_git_output(&["remote", "add", remote, url], &None).map(|_| ())
}

pub(super) fn git_update_ref(commands: impl AsRef<str>) -> Result<(), GitError> {
    feed_git_command(
        &[
            "update-ref",
            // When updating existing symlinks, we want to update the source symlink and not its target
            "--no-deref",
            "--stdin",
        ],
        &None,
        Some(commands.as_ref()),
    )
    .map_err(map_git_error)
    .map(|_| ())
}

pub fn get_head_revision() -> Result<String> {
    Ok(internal_get_head_revision()?)
}

pub(super) fn internal_get_head_revision() -> Result<String, GitError> {
    git_rev_parse("HEAD")
}

pub(super) fn git_rev_parse(reference: &str) -> Result<String, GitError> {
    capture_git_output(&["rev-parse", "--verify", "-q", reference], &None)
        .map_err(|_e| GitError::MissingHead {
            reference: reference.into(),
        })
        .map(|s| s.stdout.trim().to_owned())
}

/// Resolves a committish reference to a full SHA-1 hash and verifies the commit exists.
///
/// This function takes any valid Git committish (commit hash, branch name, tag, or
/// relative reference like `HEAD~3`) and resolves it to the full 40-character SHA-1
/// hash of the underlying commit object. It also validates that the commit object
/// actually exists in the repository.
///
/// # Arguments
///
/// * `committish` - A Git committish reference (e.g., "HEAD", "main", "a1b2c3d", "HEAD~3")
///
/// # Returns
///
/// * `Ok(String)` - The full SHA-1 hash of the resolved commit
/// * `Err` - If the committish cannot be resolved or the commit does not exist
///
/// # Examples
///
/// ```no_run
/// # use git_perf::git::git_lowlevel::resolve_committish;
/// let sha = resolve_committish("HEAD").unwrap();
/// assert_eq!(sha.len(), 40); // Full SHA-1 hash
/// ```
pub fn resolve_committish(committish: &str) -> Result<String> {
    let resolved = git_rev_parse(committish).map_err(|e| anyhow!(e))?;

    // Verify the resolved commit actually exists using git cat-file
    capture_git_output(&["cat-file", "-e", &resolved], &None)
        .map_err(|e| anyhow!("Commit '{}' does not exist: {}", committish, e))?;

    Ok(resolved)
}

pub(super) fn git_rev_parse_symbolic_ref(reference: &str) -> Option<String> {
    capture_git_output(&["symbolic-ref", "-q", reference], &None)
        .ok()
        .map(|s| s.stdout.trim().to_owned())
}

pub(super) fn git_symbolic_ref_create_or_update(
    reference: &str,
    target: &str,
) -> Result<(), GitError> {
    capture_git_output(&["symbolic-ref", reference, target], &None)
        .map_err(map_git_error)
        .map(|_| ())
}

pub fn is_shallow_repo() -> Result<bool, GitError> {
    let output = capture_git_output(&["rev-parse", "--is-shallow-repository"], &None)?;

    Ok(output.stdout.starts_with("true"))
}

pub(super) fn parse_git_version(version: &str) -> Result<(i32, i32, i32)> {
    let version = version
        .split_whitespace()
        .nth(2)
        .ok_or(anyhow!("Could not find git version in string {version}"))?;
    match version.split('.').collect_vec()[..] {
        [major, minor, patch] => Ok((major.parse()?, minor.parse()?, patch.parse()?)),
        _ => Err(anyhow!("Failed determine semantic version from {version}")),
    }
}

fn get_git_version() -> Result<(i32, i32, i32)> {
    let version = capture_git_output(&["--version"], &None)
        .context("Determine git version")?
        .stdout;
    parse_git_version(&version)
}

fn concat_version(version_tuple: (i32, i32, i32)) -> String {
    format!(
        "{}.{}.{}",
        version_tuple.0, version_tuple.1, version_tuple.2
    )
}

pub fn check_git_version() -> Result<()> {
    let version_tuple = get_git_version().context("Determining compatible git version")?;
    if version_tuple < EXPECTED_VERSION {
        bail!(
            "Version {} is smaller than {}",
            concat_version(version_tuple),
            concat_version(EXPECTED_VERSION)
        )
    }
    Ok(())
}

/// Get the repository root directory using git
pub fn get_repository_root() -> Result<String, String> {
    let output = capture_git_output(&["rev-parse", "--show-toplevel"], &None)
        .map_err(|e| format!("Failed to get repository root: {}", e))?;
    Ok(output.stdout.trim().to_string())
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test_helpers::with_isolated_cwd_git;

    #[test]
    fn test_get_head_revision() {
        with_isolated_cwd_git(|_git_dir| {
            let revision = internal_get_head_revision().unwrap();
            assert!(
                &revision.chars().all(|c| c.is_ascii_alphanumeric()),
                "'{}' contained non alphanumeric or non ASCII characters",
                &revision
            )
        });
    }

    #[test]
    fn test_parse_git_version() {
        let version = parse_git_version("git version 2.52.0");
        assert_eq!(version.unwrap(), (2, 52, 0));

        let version = parse_git_version("git version 2.52.0\n");
        assert_eq!(version.unwrap(), (2, 52, 0));
    }

    #[test]
    fn test_map_git_error_ref_failed_to_lock() {
        let output = GitOutput {
            stdout: String::new(),
            stderr: "fatal: cannot lock ref 'refs/heads/main': Unable to create lock".to_string(),
        };
        let error = GitError::ExecError {
            command: "update-ref".to_string(),
            output,
        };

        let mapped = map_git_error(error);
        assert!(matches!(mapped, GitError::RefFailedToLock { .. }));
    }

    #[test]
    fn test_map_git_error_ref_concurrent_modification() {
        let output = GitOutput {
            stdout: String::new(),
            stderr: "fatal: ref updates forbidden, but expected commit abc123".to_string(),
        };
        let error = GitError::ExecError {
            command: "update-ref".to_string(),
            output,
        };

        let mapped = map_git_error(error);
        assert!(matches!(mapped, GitError::RefConcurrentModification { .. }));
    }

    #[test]
    fn test_map_git_error_no_remote_measurements() {
        let output = GitOutput {
            stdout: String::new(),
            stderr: "fatal: couldn't find remote ref refs/notes/measurements".to_string(),
        };
        let error = GitError::ExecError {
            command: "fetch".to_string(),
            output,
        };

        let mapped = map_git_error(error);
        assert!(matches!(mapped, GitError::NoRemoteMeasurements { .. }));
    }

    #[test]
    fn test_map_git_error_bad_object() {
        let output = GitOutput {
            stdout: String::new(),
            stderr: "error: bad object abc123def456".to_string(),
        };
        let error = GitError::ExecError {
            command: "cat-file".to_string(),
            output,
        };

        let mapped = map_git_error(error);
        assert!(matches!(mapped, GitError::BadObject { .. }));
    }

    #[test]
    fn test_map_git_error_unmapped() {
        let output = GitOutput {
            stdout: String::new(),
            stderr: "fatal: some other error".to_string(),
        };
        let error = GitError::ExecError {
            command: "status".to_string(),
            output,
        };

        let mapped = map_git_error(error);
        // Should remain as ExecError for unrecognized patterns
        assert!(matches!(mapped, GitError::ExecError { .. }));
    }

    #[test]
    fn test_map_git_error_false_positive_avoidance() {
        // Test that partial matches don't trigger false positives
        let output = GitOutput {
            stdout: String::new(),
            stderr: "this message mentions 'lock' without the full pattern".to_string(),
        };
        let error = GitError::ExecError {
            command: "test".to_string(),
            output,
        };

        let mapped = map_git_error(error);
        // Should NOT be mapped to RefFailedToLock
        assert!(matches!(mapped, GitError::ExecError { .. }));
    }

    #[test]
    fn test_map_git_error_cannot_lock_ref_pattern_must_match() {
        // Test that "cannot lock ref" must be present (not just "lock")
        let test_cases = vec![
            ("fatal: cannot lock ref 'refs/heads/main'", true),
            ("error: cannot lock ref update", true),
            ("fatal: failed to lock something", false),
            ("error: lock failed", false),
        ];

        for (stderr_msg, should_map) in test_cases {
            let output = GitOutput {
                stdout: String::new(),
                stderr: stderr_msg.to_string(),
            };
            let error = GitError::ExecError {
                command: "test".to_string(),
                output,
            };

            let mapped = map_git_error(error);
            if should_map {
                assert!(
                    matches!(mapped, GitError::RefFailedToLock { .. }),
                    "Expected RefFailedToLock for: {}",
                    stderr_msg
                );
            } else {
                assert!(
                    matches!(mapped, GitError::ExecError { .. }),
                    "Expected ExecError for: {}",
                    stderr_msg
                );
            }
        }
    }

    #[test]
    fn test_map_git_error_but_expected_pattern_must_match() {
        // Test that "but expected" must be present
        let test_cases = vec![
            ("fatal: but expected commit abc123", true),
            ("error: ref update failed but expected something", true),
            ("fatal: expected something", false),
            ("error: only mentioned the word but", false),
        ];

        for (stderr_msg, should_map) in test_cases {
            let output = GitOutput {
                stdout: String::new(),
                stderr: stderr_msg.to_string(),
            };
            let error = GitError::ExecError {
                command: "test".to_string(),
                output,
            };

            let mapped = map_git_error(error);
            if should_map {
                assert!(
                    matches!(mapped, GitError::RefConcurrentModification { .. }),
                    "Expected RefConcurrentModification for: {}",
                    stderr_msg
                );
            } else {
                assert!(
                    matches!(mapped, GitError::ExecError { .. }),
                    "Expected ExecError for: {}",
                    stderr_msg
                );
            }
        }
    }
}