Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions benches/ferrflow_benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ fn bench_config_loading(c: &mut Criterion) {
let dir = TempDir::new().unwrap();
let config_path = dir.path().join(".ferrflow");
std::fs::write(&config_path, generate_config_json(num_pkgs)).unwrap();
std::process::Command::new("git")
ferrflow::git_cmd::command()
.args(["init", "-q"])
.current_dir(dir.path())
.output()
Expand All @@ -200,7 +200,7 @@ fn run_git(dir: &std::path::Path, args: &[&str]) -> String {

fn run_git_with_stdin(dir: &std::path::Path, args: &[&str], stdin: Option<&[u8]>) -> String {
use std::io::Write;
let mut cmd = std::process::Command::new("git");
let mut cmd = ferrflow::git_cmd::command();
cmd.current_dir(dir).args(args);
cmd.env("GIT_AUTHOR_NAME", "bench");
cmd.env("GIT_AUTHOR_EMAIL", "bench@test.com");
Expand Down Expand Up @@ -384,7 +384,7 @@ fn bench_validate(c: &mut Criterion) {
.unwrap();
}

std::process::Command::new("git")
ferrflow::git_cmd::command()
.args(["init", "-q"])
.current_dir(dir.path())
.output()
Expand Down
14 changes: 7 additions & 7 deletions src/bot_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,11 +318,11 @@ fn configure_bot_git_identity_in(repo_dir: &std::path::Path) {
.unwrap_or_else(|| DEFAULT_BOT_USER_ID.to_string());
let email = format!("{user_id}+{login}@users.noreply.github.com");

let _ = std::process::Command::new("git")
let _ = crate::git_cmd::command()
.args(["config", "--local", "user.name", &login])
.current_dir(repo_dir)
.status();
let _ = std::process::Command::new("git")
let _ = crate::git_cmd::command()
.args(["config", "--local", "user.email", &email])
.current_dir(repo_dir)
.status();
Expand Down Expand Up @@ -576,7 +576,7 @@ mod tests {
}

fn read_local_git_config(repo_dir: &std::path::Path, key: &str) -> Option<String> {
let out = std::process::Command::new("git")
let out = crate::test_utils::git_command()
.args(["config", "--local", "--get", key])
.current_dir(repo_dir)
.output()
Expand All @@ -589,7 +589,7 @@ mod tests {
}

fn init_repo(dir: &std::path::Path) {
let ok = std::process::Command::new("git")
let ok = crate::test_utils::git_command()
.args(["init", "-q"])
.current_dir(dir)
.status()
Expand All @@ -600,7 +600,7 @@ mod tests {

#[test]
fn configure_bot_git_identity_uses_hosted_defaults() {
if std::process::Command::new("git")
if crate::test_utils::git_command()
.arg("--version")
.status()
.is_err()
Expand Down Expand Up @@ -629,7 +629,7 @@ mod tests {

#[test]
fn configure_bot_git_identity_honours_env_overrides() {
if std::process::Command::new("git")
if crate::test_utils::git_command()
.arg("--version")
.status()
.is_err()
Expand Down Expand Up @@ -661,7 +661,7 @@ mod tests {

#[test]
fn configure_bot_git_identity_treats_blank_overrides_as_unset() {
if std::process::Command::new("git")
if crate::test_utils::git_command()
.arg("--version")
.status()
.is_err()
Expand Down
3 changes: 1 addition & 2 deletions src/doctor/checks.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::path::Path;
use std::process::Command;

use crate::config::{Config, ForgeKind, GENERIC_TOKEN_ENV_VAR};
use crate::forge::{Probe, resolve_forge};
Expand Down Expand Up @@ -463,7 +462,7 @@ pub(super) fn identity_check(identity: Option<String>, on_actions: bool) -> Chec
}

fn dirty_count(root: &Path) -> Option<usize> {
let output = Command::new("git")
let output = crate::git_cmd::command()
.current_dir(root)
.args(["status", "--porcelain"])
.output()
Expand Down
8 changes: 4 additions & 4 deletions src/formats/gomod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub struct GoModVersionFile;

impl VersionFile for GoModVersionFile {
fn read_version(&self, file_path: &Path) -> Result<String> {
let mut cmd = std::process::Command::new("git");
let mut cmd = crate::git_cmd::command();
cmd.args([
"describe",
"--tags",
Expand Down Expand Up @@ -74,7 +74,6 @@ impl VersionFile for GoModVersionFile {
mod tests {
use super::*;
use std::path::Path;
use std::process::Command;

#[test]
fn write_version_is_noop() {
Expand All @@ -96,9 +95,10 @@ mod tests {
"config email",
),
(vec!["config", "user.name", "Test"], "config name"),
(vec!["config", "tag.gpgsign", "false"], "config tag.gpgsign"),
(vec!["commit", "--allow-empty", "-m", "initial"], "commit"),
] {
let out = Command::new("git")
let out = crate::test_utils::git_command()
.args(args)
.current_dir(repo)
.output()
Expand Down Expand Up @@ -132,7 +132,7 @@ mod tests {
let repo = dir.path();
init_repo(repo);

let tag_out = Command::new("git")
let tag_out = crate::test_utils::git_command()
.args(["tag", "v1.2.3"])
.current_dir(repo)
.output()
Expand Down
2 changes: 1 addition & 1 deletion src/git/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub fn fetch_tags(repo: &Repository, remote: Remote<'_>) -> Result<()> {
let url = get_remote_url(repo, remote_name)
.ok_or_else(|| anyhow!("Remote '{remote_name}' not found"))?;

let mut cmd = std::process::Command::new("git");
let mut cmd = crate::git_cmd::command();
cmd.current_dir(workdir);
configure_git_command(&mut cmd, &url, forge);
cmd.args(["fetch", "--tags", remote_name]);
Expand Down
40 changes: 40 additions & 0 deletions src/git/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,49 @@ fn ensure_commit_identity_with_env(
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::ENV_LOCK;

const INHERITED_IDENTITY_ENV: [&str; 7] = [
"GIT_AUTHOR_NAME",
"GIT_AUTHOR_EMAIL",
"GIT_COMMITTER_NAME",
"GIT_COMMITTER_EMAIL",
"EMAIL",
"GIT_CONFIG_PARAMETERS",
"GIT_CONFIG_COUNT",
];

struct IdentityEnvGuard {
_lock: std::sync::MutexGuard<'static, ()>,
saved: Vec<(&'static str, std::ffi::OsString)>,
}

impl IdentityEnvGuard {
fn clear() -> Self {
let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let saved = INHERITED_IDENTITY_ENV
.into_iter()
.filter_map(|var| std::env::var_os(var).map(|v| (var, v)))
.collect();
for var in INHERITED_IDENTITY_ENV {
unsafe { std::env::remove_var(var) };
}
Self { _lock: lock, saved }
}
}

impl Drop for IdentityEnvGuard {
fn drop(&mut self) {
for (var, value) in &self.saved {
unsafe { std::env::set_var(var, value) };
}
}
}

struct IsolatedRepo {
dir: tempfile::TempDir,
global_config: String,
_env: IdentityEnvGuard,
}

impl IsolatedRepo {
Expand All @@ -75,6 +114,7 @@ mod tests {
let repo = Self {
global_config: global.to_string_lossy().into_owned(),
dir,
_env: IdentityEnvGuard::clear(),
};
repo.git(&["init", "-q"]);
repo.git(&["config", "--local", "user.useConfigOnly", "true"]);
Expand Down
18 changes: 9 additions & 9 deletions src/git/push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub(super) fn remote_tag_target_shas(
if tags.is_empty() {
return Ok(HashMap::new());
}
let mut cmd = std::process::Command::new("git");
let mut cmd = crate::git_cmd::command();
cmd.current_dir(workdir);
configure_git_command(&mut cmd, push_url, forge);
cmd.arg("ls-remote").arg("--tags").arg(push_url);
Expand Down Expand Up @@ -109,7 +109,7 @@ pub fn verify_remote_branch(
let url = get_remote_url(repo, remote_name)
.ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;

let mut cmd = std::process::Command::new("git");
let mut cmd = crate::git_cmd::command();
cmd.current_dir(workdir);
configure_git_command(&mut cmd, &url, forge);
cmd.args([
Expand Down Expand Up @@ -234,7 +234,7 @@ fn push_branch_once(
let source = resolve_push_source(repo, branch);
let refspec = format!("{}{source}:refs/heads/{branch}", mode.refspec_prefix());

let mut cmd = std::process::Command::new("git");
let mut cmd = crate::git_cmd::command();
cmd.current_dir(workdir);
configure_git_command(&mut cmd, &push_url, forge);
cmd.arg("push").arg(&push_url).arg(&refspec);
Expand Down Expand Up @@ -275,7 +275,7 @@ pub fn release_branch_foreign_commit(
let url = get_remote_url(repo, remote_name)
.ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;

let mut ls = std::process::Command::new("git");
let mut ls = crate::git_cmd::command();
ls.current_dir(workdir);
configure_git_command(&mut ls, &url, forge);
ls.args([
Expand All @@ -299,7 +299,7 @@ pub fn release_branch_foreign_commit(
return Ok(None);
}

let mut fetch = std::process::Command::new("git");
let mut fetch = crate::git_cmd::command();
fetch.current_dir(workdir);
configure_git_command(&mut fetch, &url, forge);
fetch.args(["fetch", "--quiet", &url, &format!("refs/heads/{branch}")]);
Expand All @@ -315,7 +315,7 @@ pub fn release_branch_foreign_commit(
.error_code(error_code::GIT_INSPECT_RELEASE_BRANCH);
}

let mut log = std::process::Command::new("git");
let mut log = crate::git_cmd::command();
log.current_dir(workdir);
log.args(["log", "--format=%s", &format!("{base}..FETCH_HEAD")]);
let log_out = log
Expand Down Expand Up @@ -420,7 +420,7 @@ fn shell_push_tags(
}

let prefix = if force { "+" } else { "" };
let mut cmd = std::process::Command::new("git");
let mut cmd = crate::git_cmd::command();
cmd.current_dir(workdir);
configure_git_command(&mut cmd, &push_url, forge);
cmd.arg("push").arg(&push_url);
Expand Down Expand Up @@ -459,7 +459,7 @@ pub fn reset_branch_to_remote(repo: &Repository, remote: Remote<'_>, branch: &st
let push_url = get_remote_url(repo, remote_name)
.ok_or_else(|| anyhow!("Remote '{remote_name}' has no URL"))?;

let mut fetch_cmd = std::process::Command::new("git");
let mut fetch_cmd = crate::git_cmd::command();
fetch_cmd.current_dir(workdir);
configure_git_command(&mut fetch_cmd, &push_url, forge);
fetch_cmd.arg("fetch").arg(remote_name).arg(format!(
Expand Down Expand Up @@ -582,7 +582,7 @@ pub fn delete_tag_if_unchanged(
Some(_) => {}
}

let mut cmd = std::process::Command::new("git");
let mut cmd = crate::git_cmd::command();
cmd.current_dir(workdir);
configure_git_command(&mut cmd, &url, forge);
cmd.args(["push", "--delete", &url, &format!("refs/tags/{tag}")]);
Expand Down
3 changes: 1 addition & 2 deletions src/git/shell.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use anyhow::{Context, Result, anyhow};
use std::path::Path;
use std::process::Command;

use super::auth::scrub_trace_env;

Expand All @@ -13,7 +12,7 @@ pub(super) fn run_git_with_env(
args: &[&str],
extra_env: &[(&str, &str)],
) -> Result<String> {
let mut cmd = Command::new("git");
let mut cmd = crate::git_cmd::command();
cmd.current_dir(workdir);
scrub_trace_env(&mut cmd);
for (k, v) in extra_env {
Expand Down
2 changes: 1 addition & 1 deletion src/git/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ mod tests {
ensure_safe_refname_fragment(bad, "tag").is_err(),
"should reject {bad:?}"
);
let accepted = std::process::Command::new("git")
let accepted = crate::test_utils::git_command()
.arg("check-ref-format")
.arg(format!("refs/tags/{bad}"))
.status()
Expand Down
80 changes: 80 additions & 0 deletions src/git_cmd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use std::process::Command;

const REPO_LOCATION_ENV: [&str; 10] = [
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_IMPLICIT_WORK_TREE",
"GIT_COMMON_DIR",
"GIT_INDEX_FILE",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_SHALLOW_FILE",
"GIT_GRAFT_FILE",
"GIT_PREFIX",
];

pub fn command() -> Command {
Comment thread
ferrfleet-interne[bot] marked this conversation as resolved.
Resolved
let mut cmd = Command::new("git");
for var in REPO_LOCATION_ENV {
cmd.env_remove(var);
}
cmd
}

#[cfg(all(test, feature = "cli"))]
mod tests {
use crate::test_utils::{ENV_LOCK, git, init_repo};
use std::path::Path;

struct GitDirGuard(Option<std::ffi::OsString>);

impl GitDirGuard {
fn set(path: &Path) -> Self {
let previous = std::env::var_os("GIT_DIR");
unsafe { std::env::set_var("GIT_DIR", path) };
Self(previous)
}
}

impl Drop for GitDirGuard {
fn drop(&mut self) {
unsafe {
match &self.0 {
Some(v) => std::env::set_var("GIT_DIR", v),
None => std::env::remove_var("GIT_DIR"),
}
}
}
}

#[test]
fn an_inherited_git_dir_never_redirects_git_away_from_the_temp_repo() {
let _lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let decoy = tempfile::tempdir().unwrap();
git(decoy.path(), &["init", "-q"]);
let decoy_config = decoy.path().join(".git/config");
let config_before = std::fs::read_to_string(&decoy_config).unwrap();

{
let _guard = GitDirGuard::set(&decoy.path().join(".git"));
let initialized = init_repo();
let git_dir = super::command()
.current_dir(initialized.0.path())
.args(["rev-parse", "--absolute-git-dir"])
.output()
.unwrap();
assert!(git_dir.status.success());
assert_eq!(
Path::new(String::from_utf8_lossy(&git_dir.stdout).trim())
.canonicalize()
.unwrap(),
initialized.0.path().join(".git").canonicalize().unwrap()
);
}

assert_eq!(
std::fs::read_to_string(&decoy_config).unwrap(),
config_before
);
}
}
Loading
Loading