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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! Centralized test helpers for git-perf
//!
//! This module provides common test utilities used across unit tests and benchmarks,
//! including hermetic git environment setup and repository initialization helpers.

use std::env;
use std::path::Path;
use std::process::{Command, Stdio};
use tempfile::{tempdir, TempDir};

/// Sets up a hermetic git environment by configuring environment variables
/// to isolate git operations from the user's global git configuration.
///
/// This function sets:
/// - `GIT_CONFIG_NOSYSTEM`: Disables system-wide git config
/// - `GIT_CONFIG_GLOBAL`: Points to /dev/null to ignore global config
/// - `GIT_AUTHOR_NAME`, `GIT_AUTHOR_EMAIL`: Test user identity
/// - `GIT_COMMITTER_NAME`, `GIT_COMMITTER_EMAIL`: Test committer identity
pub fn hermetic_git_env() {
    env::set_var("GIT_CONFIG_NOSYSTEM", "true");
    env::set_var("GIT_CONFIG_GLOBAL", "/dev/null");
    env::set_var("GIT_AUTHOR_NAME", "testuser");
    env::set_var("GIT_AUTHOR_EMAIL", "testuser@example.com");
    env::set_var("GIT_COMMITTER_NAME", "testuser");
    env::set_var("GIT_COMMITTER_EMAIL", "testuser@example.com");
}

/// Returns hermetic git environment variables as an array of tuples.
///
/// This is useful for passing to `Command::envs()` when spawning processes
/// that need isolated git environment.
///
/// # Returns
/// Array of (key, value) tuples for hermetic git environment variables
#[must_use]
pub fn hermetic_git_env_vars() -> [(&'static str, &'static str); 6] {
    [
        ("GIT_CONFIG_NOSYSTEM", "true"),
        ("GIT_CONFIG_GLOBAL", "/dev/null"),
        ("GIT_AUTHOR_NAME", "testuser"),
        ("GIT_AUTHOR_EMAIL", "testuser@example.com"),
        ("GIT_COMMITTER_NAME", "testuser"),
        ("GIT_COMMITTER_EMAIL", "testuser@example.com"),
    ]
}

/// Runs a git command in a hermetic environment with the specified directory.
///
/// # Arguments
/// * `args` - Git command arguments
/// * `dir` - Directory to run the command in
///
/// # Panics
/// Panics if the git command fails or returns a non-zero exit status.
pub fn run_git_command(args: &[&str], dir: &Path) {
    assert!(Command::new("git")
        .args(args)
        .envs([
            ("GIT_CONFIG_NOSYSTEM", "true"),
            ("GIT_CONFIG_GLOBAL", "/dev/null"),
            ("GIT_AUTHOR_NAME", "testuser"),
            ("GIT_AUTHOR_EMAIL", "testuser@example.com"),
            ("GIT_COMMITTER_NAME", "testuser"),
            ("GIT_COMMITTER_EMAIL", "testuser@example.com"),
        ])
        .current_dir(dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("Failed to spawn git command")
        .success());
}

/// Initializes a git repository in the specified directory with an initial empty commit.
///
/// # Arguments
/// * `dir` - Directory to initialize the repository in
///
/// # Panics
/// Panics if git initialization or the initial commit fails.
pub fn init_repo(dir: &Path) {
    run_git_command(&["init", "--initial-branch", "master"], dir);
    run_git_command(&["commit", "--allow-empty", "-m", "Initial commit"], dir);
}

/// Creates a temporary directory with an initialized git repository.
///
/// The repository will have:
/// - A master branch as the initial branch
/// - An initial empty commit
///
/// # Returns
/// A `TempDir` that will be automatically cleaned up when dropped.
///
/// # Panics
/// Panics if the temporary directory cannot be created or git initialization fails.
#[must_use]
pub fn dir_with_repo() -> TempDir {
    let tempdir = tempdir().unwrap();
    init_repo(tempdir.path());
    tempdir
}

/// Initializes a git repository in the current directory.
/// This is a simplified version for use in benchmarks that don't need a TempDir.
///
/// # Panics
/// Panics if git initialization fails.
pub fn init_repo_simple() {
    assert!(Command::new("git")
        .arg("init")
        .output()
        .expect("Failed to init git repo")
        .status
        .success());
}

/// Creates an empty commit in the current directory.
/// This is a simplified version for use in benchmarks.
///
/// # Panics
/// Panics if the commit fails.
pub fn empty_commit() {
    assert!(Command::new("git")
        .args(["commit", "--allow-empty", "-m", "test commit"])
        .output()
        .expect("Failed to create empty commit")
        .status
        .success());
}

/// Initializes a git repository in the specified directory with a real file commit.
///
/// Creates a test.txt file with "test content" and commits it.
///
/// # Arguments
/// * `dir` - Directory to initialize the repository in
///
/// # Panics
/// Panics if git initialization, file creation, or commit fails.
pub fn init_repo_with_file(dir: &Path) {
    run_git_command(&["init", "--initial-branch", "master"], dir);

    // Create a test file and commit it
    std::fs::write(dir.join("test.txt"), "test content").expect("Failed to create test file");
    run_git_command(&["add", "test.txt"], dir);
    run_git_command(&["commit", "-m", "Initial commit"], dir);
}

/// Creates a temporary directory with an initialized git repository and a file commit.
///
/// The repository will have:
/// - A master branch as the initial branch
/// - A test.txt file committed
///
/// # Returns
/// A `TempDir` that will be automatically cleaned up when dropped.
///
/// # Panics
/// Panics if the temporary directory cannot be created or git initialization fails.
#[must_use]
pub fn dir_with_repo_and_file() -> TempDir {
    let tempdir = tempdir().unwrap();
    init_repo_with_file(tempdir.path());
    tempdir
}

/// Sets up an isolated HOME directory for config isolation tests.
///
/// This helper creates a temporary HOME directory and removes XDG_CONFIG_HOME
/// to ensure tests run in complete isolation. The original HOME is restored
/// after the test closure completes.
///
/// # Arguments
/// * `f` - Closure that takes the temporary home path and returns a result
///
/// # Returns
/// The result from the closure
pub fn with_isolated_home<F, R>(f: F) -> R
where
    F: FnOnce(&Path) -> R,
{
    let temp_dir = TempDir::new().unwrap();

    // Save original HOME
    let original_home = env::var("HOME").ok();
    let original_xdg = env::var("XDG_CONFIG_HOME").ok();

    // Set up isolated HOME directory
    env::set_var("HOME", temp_dir.path());
    env::remove_var("XDG_CONFIG_HOME");

    let result = f(temp_dir.path());

    // Restore original environment
    if let Some(home) = original_home {
        env::set_var("HOME", home);
    } else {
        env::remove_var("HOME");
    }
    if let Some(xdg) = original_xdg {
        env::set_var("XDG_CONFIG_HOME", xdg);
    }

    result
}

/// Sets up an isolated git repository environment in a temporary directory.
///
/// This helper:
/// 1. Sets up hermetic git environment variables
/// 2. Creates a temporary directory with an initialized git repository
/// 3. Changes the current directory to the git repository (with automatic restoration)
///
/// The closure runs with the current directory set to the git repository.
///
/// # Arguments
/// * `f` - Closure that takes the git directory path and returns a result
///
/// # Returns
/// The result from the closure
///
/// # Example
/// ```
/// with_isolated_cwd_git(|git_dir| {
///     // Your test code here - already in git repo directory
///     // with hermetic git environment
/// });
/// ```
pub fn with_isolated_cwd_git<F, R>(f: F) -> R
where
    F: FnOnce(&Path) -> R,
{
    hermetic_git_env();
    let temp_dir = dir_with_repo();
    let _guard = DirGuard::new(temp_dir.path());

    f(temp_dir.path())
}

/// Sets up a complete isolated test environment combining HOME isolation and git repository setup.
///
/// This is a composition of `with_isolated_home` and `with_isolated_cwd_git` that provides
/// maximum isolation for tests. Use this when you need both HOME isolation and a git repository.
///
/// This helper:
/// 1. Creates an isolated HOME directory
/// 2. Sets up hermetic git environment variables
/// 3. Creates a temporary directory with an initialized git repository
/// 4. Changes the current directory to the git repository (with automatic restoration)
/// 5. Ensures HOME points to the isolated directory
///
/// For more flexibility, you can compose `with_isolated_home` and `with_isolated_cwd_git`
/// directly in different orders or use them individually.
///
/// # Arguments
/// * `f` - Closure that takes `(git_dir, home_path)` and returns a result
///
/// # Returns
/// The result from the closure
///
/// # Example
/// ```
/// with_isolated_test_setup(|git_dir, home_path| {
///     // Your test code here - in git repo with isolated HOME
/// });
/// ```
pub fn with_isolated_test_setup<F, R>(f: F) -> R
where
    F: FnOnce(&Path, &Path) -> R,
{
    with_isolated_home(|home_path| with_isolated_cwd_git(|git_dir| f(git_dir, home_path)))
}

/// Writes a .gitperfconfig file in the specified directory.
///
/// # Arguments
/// * `dir` - Directory where .gitperfconfig should be written
/// * `content` - TOML content to write to the config file
///
/// # Panics
/// Panics if the file cannot be written.
pub fn write_gitperfconfig(dir: &Path, content: &str) {
    let config_path = dir.join(".gitperfconfig");
    std::fs::write(&config_path, content).expect("Failed to write .gitperfconfig");
}

/// RAII guard that restores the current directory when dropped.
///
/// This ensures tests that change the current directory don't affect other tests.
pub struct DirGuard {
    original_dir: std::path::PathBuf,
}

impl DirGuard {
    /// Creates a new DirGuard and changes to the specified directory.
    #[must_use]
    pub fn new(new_dir: &Path) -> Self {
        let original_dir = env::current_dir().expect("Failed to get current directory");
        env::set_current_dir(new_dir).expect("Failed to change directory");
        DirGuard { original_dir }
    }
}

impl Drop for DirGuard {
    fn drop(&mut self) {
        let _ = env::set_current_dir(&self.original_dir);
    }
}

/// Sets up a complete test environment with git repo and config, and changes to that directory.
///
/// This is a convenience function that:
/// 1. Sets up hermetic git environment variables
/// 2. Creates a temporary directory with an initialized git repository
/// 3. Writes the provided config content to .gitperfconfig
/// 4. Changes the current directory to the temp directory (with automatic restoration)
///
/// # Arguments
/// * `config_content` - TOML content for .gitperfconfig
///
/// # Returns
/// A tuple of (`TempDir`, `DirGuard`). Both will be automatically cleaned up when dropped.
/// The `DirGuard` ensures the original directory is restored.
///
/// # Panics
/// Panics if any step fails.
#[must_use]
pub fn setup_test_env_with_config(config_content: &str) -> (TempDir, DirGuard) {
    hermetic_git_env();
    let temp_dir = dir_with_repo();
    write_gitperfconfig(temp_dir.path(), config_content);
    let guard = DirGuard::new(temp_dir.path());
    (temp_dir, guard)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env::set_current_dir;

    #[test]
    fn test_hermetic_git_env() {
        hermetic_git_env();
        assert_eq!(env::var("GIT_CONFIG_NOSYSTEM").unwrap(), "true");
        assert_eq!(env::var("GIT_CONFIG_GLOBAL").unwrap(), "/dev/null");
        assert_eq!(env::var("GIT_AUTHOR_NAME").unwrap(), "testuser");
        assert_eq!(
            env::var("GIT_AUTHOR_EMAIL").unwrap(),
            "testuser@example.com"
        );
    }

    #[test]
    fn test_dir_with_repo() {
        let repo_dir = dir_with_repo();
        set_current_dir(repo_dir.path()).expect("Failed to change dir");

        // Verify the repository was initialized
        let output = Command::new("git")
            .args(["rev-parse", "--is-inside-work-tree"])
            .output()
            .expect("Failed to run git command");

        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "true");
    }

    #[test]
    fn test_init_repo() {
        let tempdir = tempdir().unwrap();
        init_repo(tempdir.path());

        set_current_dir(tempdir.path()).expect("Failed to change dir");

        // Verify the repository has at least one commit
        let output = Command::new("git")
            .args(["rev-list", "--count", "HEAD"])
            .output()
            .expect("Failed to run git command");

        assert!(output.status.success());
        let count = String::from_utf8_lossy(&output.stdout)
            .trim()
            .parse::<i32>()
            .unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_hermetic_git_env_vars() {
        let env_vars = hermetic_git_env_vars();

        // Verify all required variables are present and have correct values
        assert_eq!(env_vars.len(), 6);

        // Check each variable
        assert_eq!(env_vars[0], ("GIT_CONFIG_NOSYSTEM", "true"));
        assert_eq!(env_vars[1], ("GIT_CONFIG_GLOBAL", "/dev/null"));
        assert_eq!(env_vars[2], ("GIT_AUTHOR_NAME", "testuser"));
        assert_eq!(env_vars[3], ("GIT_AUTHOR_EMAIL", "testuser@example.com"));
        assert_eq!(env_vars[4], ("GIT_COMMITTER_NAME", "testuser"));
        assert_eq!(env_vars[5], ("GIT_COMMITTER_EMAIL", "testuser@example.com"));

        // Verify values are not empty
        for (key, value) in &env_vars {
            assert!(
                !key.is_empty(),
                "Environment variable key should not be empty"
            );
            assert!(
                !value.is_empty(),
                "Environment variable value for {} should not be empty",
                key
            );
        }
    }

    #[test]
    fn test_init_repo_simple() {
        let tempdir = tempdir().unwrap();
        let original_dir = env::current_dir().unwrap();

        set_current_dir(tempdir.path()).expect("Failed to change to temp dir");

        hermetic_git_env();
        init_repo_simple();

        // Verify the repository was initialized
        let output = Command::new("git")
            .args(["rev-parse", "--is-inside-work-tree"])
            .envs(hermetic_git_env_vars())
            .output()
            .expect("Failed to run git command");

        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "true");

        // Restore original directory
        set_current_dir(original_dir).expect("Failed to restore directory");
    }

    #[test]
    fn test_empty_commit() {
        let tempdir = tempdir().unwrap();
        let original_dir = env::current_dir().unwrap();

        hermetic_git_env();
        init_repo(tempdir.path());
        set_current_dir(tempdir.path()).expect("Failed to change to temp dir");

        // Get initial commit count
        let before = Command::new("git")
            .args(["rev-list", "--count", "HEAD"])
            .envs(hermetic_git_env_vars())
            .output()
            .expect("Failed to run git command");
        assert!(
            before.status.success(),
            "Failed to get initial commit count"
        );
        let count_before = String::from_utf8_lossy(&before.stdout)
            .trim()
            .parse::<i32>()
            .expect("Failed to parse initial commit count");

        hermetic_git_env();
        empty_commit();

        // Verify a new commit was created
        let after = Command::new("git")
            .args(["rev-list", "--count", "HEAD"])
            .envs(hermetic_git_env_vars())
            .output()
            .expect("Failed to run git command");
        assert!(after.status.success(), "Failed to get final commit count");
        let count_after = String::from_utf8_lossy(&after.stdout)
            .trim()
            .parse::<i32>()
            .expect("Failed to parse final commit count");

        assert_eq!(
            count_after,
            count_before + 1,
            "Should have created exactly one new commit"
        );

        // Restore original directory
        set_current_dir(original_dir).expect("Failed to restore directory");
    }

    #[test]
    fn test_dir_guard_restores_directory() {
        let original_dir = env::current_dir().unwrap();
        let tempdir = tempdir().unwrap();

        {
            let _guard = DirGuard::new(tempdir.path());
            // Verify we're in the new directory
            assert_eq!(
                env::current_dir().unwrap(),
                tempdir.path().canonicalize().unwrap()
            );
        }

        // Verify the guard restored the original directory
        assert_eq!(env::current_dir().unwrap(), original_dir);
    }

    #[test]
    fn test_hermetic_git_env_sets_all_vars() {
        // Clear the environment variables first to ensure they're actually being set
        env::remove_var("GIT_CONFIG_NOSYSTEM");
        env::remove_var("GIT_CONFIG_GLOBAL");
        env::remove_var("GIT_AUTHOR_NAME");
        env::remove_var("GIT_AUTHOR_EMAIL");
        env::remove_var("GIT_COMMITTER_NAME");
        env::remove_var("GIT_COMMITTER_EMAIL");

        hermetic_git_env();

        // Verify all variables are set
        assert_eq!(env::var("GIT_CONFIG_NOSYSTEM").unwrap(), "true");
        assert_eq!(env::var("GIT_CONFIG_GLOBAL").unwrap(), "/dev/null");
        assert_eq!(env::var("GIT_AUTHOR_NAME").unwrap(), "testuser");
        assert_eq!(
            env::var("GIT_AUTHOR_EMAIL").unwrap(),
            "testuser@example.com"
        );
        assert_eq!(env::var("GIT_COMMITTER_NAME").unwrap(), "testuser");
        assert_eq!(
            env::var("GIT_COMMITTER_EMAIL").unwrap(),
            "testuser@example.com"
        );
    }
}