Skip to main content

fallow_engine/
git_env.rs

1//! Git process environment helpers owned by the engine boundary.
2
3use std::path::Path;
4use std::process::{Command, Stdio};
5
6/// Environment variables that describe an enclosing git operation's repository
7/// state and should not leak into fallow-owned git subprocesses.
8pub const AMBIENT_GIT_ENV_VARS: &[&str] = &[
9    "GIT_DIR",
10    "GIT_WORK_TREE",
11    "GIT_INDEX_FILE",
12    "GIT_OBJECT_DIRECTORY",
13    "GIT_COMMON_DIR",
14    "GIT_PREFIX",
15];
16
17/// Strip ambient git repository-state environment variables from a `Command`.
18///
19/// Returns the `Command` for fluent chaining alongside `.args()` and
20/// `.current_dir()`.
21pub fn clear_ambient_git_env(cmd: &mut Command) -> &mut Command {
22    for var in AMBIENT_GIT_ENV_VARS {
23        cmd.env_remove(var);
24    }
25    cmd
26}
27
28/// Build a `git` command that runs in `cwd`.
29///
30/// Every Fallow-owned Git process starts here:
31/// - The ambient repository-state environment is cleared.
32/// - Stdin is closed. Long-lived embedders keep protocol stdin open, which Git
33///   for Windows can inherit and hold.
34/// - Inside a deregistered base snapshot, which holds an untrusted commit, the
35///   command gets a `GIT_DIR` that does not exist, so Git finds no repository.
36/// - `safe.bareRepository=explicit` stops Git from using a directory shaped
37///   as a bare repository that it finds on its own. Checkouts, their
38///   subdirectories and linked worktrees are not affected.
39/// - `core.fsmonitor=false` stops Git from running a file system monitor
40///   program that the config of the repository names.
41#[expect(
42    clippy::disallowed_methods,
43    reason = "engine-owned git spawn wrapper clears ambient git env before every git subprocess"
44)]
45pub fn git_command(cwd: &Path) -> Command {
46    let mut command = Command::new("git");
47    clear_ambient_git_env(&mut command);
48    crate::base_worktree_registration::confine_git_to_host(&mut command, cwd);
49    command
50        .stdin(Stdio::null())
51        .args([
52            "-c",
53            "safe.bareRepository=explicit",
54            "-c",
55            "core.fsmonitor=false",
56        ])
57        .current_dir(cwd);
58    command
59}
60
61#[cfg(all(test, unix))]
62mod tests {
63    use super::*;
64    use crate::git_fixture::{fixture_git, fixture_git_command};
65
66    /// A repository whose config names a file system monitor program that
67    /// creates `marker`.
68    #[cfg(unix)]
69    fn repo_with_fsmonitor(dir: &Path, marker: &Path) {
70        std::fs::create_dir_all(dir).expect("repo dir");
71        fixture_git(dir, &["init", "-q", "-b", "main"]);
72        std::fs::write(dir.join("tracked.txt"), "a\n").expect("file");
73        fixture_git(dir, &["add", "."]);
74        let program = format!("touch '{}'; false", marker.display());
75        fixture_git(dir, &["config", "core.fsmonitor", &program]);
76    }
77
78    #[cfg(unix)]
79    #[test]
80    fn git_command_runs_no_fsmonitor_program_of_the_repository() {
81        let temp = tempfile::tempdir().expect("temp dir");
82        let repo = temp.path().join("repo");
83        let marker = temp.path().join("fsmonitor-ran");
84        repo_with_fsmonitor(&repo, &marker);
85
86        // The fixture runs the program, so the config works as written.
87        let _ = fixture_git_command(&repo)
88            .args(["status", "--porcelain"])
89            .output()
90            .expect("git starts");
91        assert!(marker.exists(), "the fixture repository runs its program");
92        std::fs::remove_file(&marker).expect("remove marker");
93
94        for args in [
95            &["status", "--porcelain"][..],
96            &["ls-files", "-s", "-z"][..],
97        ] {
98            let _ = git_command(&repo).args(args).output().expect("git starts");
99            assert!(!marker.exists(), "git {args:?} ran the program");
100        }
101    }
102}