Merge guarded Git helpers into status reporting

This commit is contained in:
Chris Bookholt
2026-07-02 04:26:36 -07:00
47 changed files with 10413 additions and 989 deletions
+411 -46
View File
@@ -7,8 +7,8 @@ use crate::git_config::GitConfigScope;
#[cfg(unix)]
use crate::patch_paths::stage_paths;
use crate::status_guard::git_root_from_stdout;
use crate::status_guard::prepare_status_filter_guard;
use crate::status_guard::resolve_git_root_async;
use crate::status_guard::selected_executable_filter_from;
use crate::try_get_has_changes;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
@@ -18,8 +18,71 @@ use std::ffi::OsStr;
use std::path::Path;
#[cfg(unix)]
use std::path::PathBuf;
use std::process::Output;
use tokio::process::Command as TokioCommand;
const FILTER_MARKER_KEY: &str = "codex.sentinelprobe-ran";
const FILTER_MARKER_COMMAND: &str =
"git config codex.sentinelprobe-ran true && git hash-object --stdin";
#[test]
fn status_filter_driver_limit_is_exact() {
let at_limit = (0..MAX_EXECUTABLE_FILTER_DRIVERS)
.map(|index| format!("driver-{index}"))
.collect::<BTreeSet<_>>();
assert!(validate_executable_driver_count(&at_limit).is_ok());
let mut over_limit = at_limit;
over_limit.insert("one-too-many".to_string());
let error = validate_executable_driver_count(&over_limit)
.expect_err("driver after exact limit must be refused");
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
}
fn run_git(cwd: &Path, args: &[&str]) -> Output {
let mut command = std::process::Command::new("git");
isolate_git_command_environment(&mut command);
command
.current_dir(cwd)
.args(args)
.output()
.expect("run Git")
}
fn run_git_success(cwd: &Path, args: &[&str]) -> Output {
let output = run_git(cwd, args);
assert!(
output.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
output
}
fn init_filter_repo() -> tempfile::TempDir {
let repo = tempfile::tempdir().expect("tempdir");
run_git_success(repo.path(), &["init"]);
std::fs::write(repo.path().join("file.txt"), "content\n").expect("write file");
repo
}
fn configure_marker_filter(cwd: &Path, driver: &str) {
run_git_success(
cwd,
&[
"config",
&format!("filter.{driver}.clean"),
FILTER_MARKER_COMMAND,
],
);
}
fn marker_filter_ran(cwd: &Path) -> bool {
run_git(cwd, &["config", "--get", FILTER_MARKER_KEY])
.status
.success()
}
#[test]
fn selected_filter_policy_allows_unused_and_rejects_selected_at_every_scope() {
let config_dir = tempfile::tempdir().expect("config");
@@ -27,6 +90,7 @@ fn selected_filter_policy_allows_unused_and_rejects_selected_at_every_scope() {
std::fs::write(&config, "").expect("config file");
for scope in [
GitConfigScope::Unknown,
GitConfigScope::System,
GitConfigScope::Global,
GitConfigScope::Local,
@@ -98,16 +162,105 @@ fn git_add_filter_policy_rejects_clean_and_process_but_allows_smudge_only() {
}
#[test]
fn required_config_is_not_treated_as_an_executable_command() {
fn selected_filter_checkin_policy_table_is_canonical() {
for (command, required, expected) in [
("clean", None, SelectedFilterPolicy::Refused),
("process", None, SelectedFilterPolicy::Refused),
("smudge", None, SelectedFilterPolicy::NeedsRequiredValue),
("smudge", Some(false), SelectedFilterPolicy::Allowed),
("smudge", Some(true), SelectedFilterPolicy::Refused),
] {
let entries = filter_entries(
GitConfigScope::Local,
Path::new(".git/config"),
&format!("filter.demo.{command}"),
"helper-command",
);
assert_eq!(
classify_selected_filter(&entries, "demo", required),
expected,
"{command} required={required:?}"
);
}
}
#[tokio::test]
async fn sync_and_async_filter_guards_share_the_neutralization_plan() {
let repo = init_filter_repo();
let root = repo.path();
let git = GitRunner::for_cwd_io(root).expect("Git runner");
let entries = filter_entries(
GitConfigScope::Local,
Path::new(".git/config"),
"filter.demo.smudge",
"helper-command",
);
let drivers = BTreeSet::from(["demo".to_string()]);
let sync_guard = executable_filter_guard(&git, root, entries.clone(), &drivers)
.expect("sync neutralization");
let async_guard = executable_filter_guard_async(&git, root, entries, &drivers)
.await
.expect("async neutralization");
let read_plan = |guard: &GitFilterNeutralization| {
read_filter_config(&git, root, guard.git_config_args())
.expect("read effective neutralization")
.into_iter()
.filter(|(key, _entry)| key.starts_with("filter.demo."))
.map(|(key, entry)| (key, entry.value))
.collect::<BTreeMap<_, _>>()
};
let expected = filter_neutralization_entries("demo")
.map(|(key, value)| (key, value.to_string()))
.collect::<BTreeMap<_, _>>();
assert_eq!(read_plan(&sync_guard), expected);
assert_eq!(read_plan(&async_guard), expected);
}
#[test]
fn filter_snapshot_retains_required_without_treating_it_as_executable() {
let mut entries = filter_entries(
GitConfigScope::Local,
Path::new("config"),
"filter.demo.smudge",
"smudge-command",
);
entries.extend(filter_entries(
GitConfigScope::Command,
Path::new("command line:"),
"filter.demo.required",
"true",
);
));
assert_eq!(
executable_filter_drivers(&entries).expect("executable drivers"),
BTreeSet::new()
BTreeSet::from(["demo".to_string()])
);
let selected = BTreeMap::from([(b"file.txt".to_vec(), "demo".to_string())]);
assert_eq!(
selected_executable_filter_for(&entries, &selected, FilterExecution::GitAdd)
.expect("Git add filter policy"),
None
);
let neutralization = GitFilterNeutralization {
config_override: None,
filter_config: entries,
};
assert_eq!(
neutralization.filter_value("demo", "required"),
Some("true")
);
let required_only = filter_entries(
GitConfigScope::Local,
Path::new("config"),
"filter.demo.required",
"true",
);
assert!(
executable_filter_drivers(&required_only)
.expect("required-only config")
.is_empty()
);
}
@@ -149,6 +302,211 @@ fn filter_attribute_parser_rejects_malformed_or_unexpected_records() {
}
}
#[test]
fn sentinel_probe_primitives_preserve_order_budget_and_truth_table() {
assert_eq!(
classify_sentinel_filter_probes(
/*required_succeeded*/ true, /*optional_succeeded*/ None,
),
SentinelFilterProbeResolution::SpecialAttributeState
);
assert_eq!(
classify_sentinel_filter_probes(
/*required_succeeded*/ false, /*optional_succeeded*/ None,
),
SentinelFilterProbeResolution::NeedsOptionalProbe
);
assert_eq!(
classify_sentinel_filter_probes(
/*required_succeeded*/ false,
/*optional_succeeded*/ Some(true),
),
SentinelFilterProbeResolution::LiteralDriver
);
assert_eq!(
classify_sentinel_filter_probes(
/*required_succeeded*/ false,
/*optional_succeeded*/ Some(false),
),
SentinelFilterProbeResolution::ProbeFailure
);
let neutralization = vec![
"-c".to_string(),
"include.path=/private/filter-neutralization.gitconfig".to_string(),
];
assert_eq!(
sentinel_filter_probe_config_args(&neutralization, "set", /*required*/ true)
.expect("sentinel config args"),
vec![
"-c",
"include.path=/private/filter-neutralization.gitconfig",
"-c",
"filter.set.required=true",
]
);
assert_eq!(
sentinel_filter_probe_config_args(&neutralization, "ordinary", /*required*/ true)
.expect_err("reject non-sentinel config argument")
.kind(),
io::ErrorKind::InvalidInput
);
let mut budget = SentinelFilterProbeBudget::default();
assert_eq!(SentinelFilterProbeBudget::max_probes(), 16);
for _ in 0..SentinelFilterProbeBudget::max_probes() {
budget.ensure_probe_available().expect("probe in budget");
budget.record_completed_probe();
}
assert_eq!(
budget
.ensure_probe_available()
.expect_err("hard probe budget")
.to_string(),
"refusing to continue Git filter sentinel disambiguation after 16 child probes (hard limit: 16)"
);
}
#[test]
fn sentinel_special_states_and_literal_driver_names_remain_distinct() {
for (driver, special_rule) in [
("set", "file.txt filter\n"),
("unset", "file.txt -filter\n"),
("unspecified", ""),
] {
let repo = init_filter_repo();
let root = repo.path();
configure_marker_filter(root, driver);
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
std::fs::write(root.join(".gitattributes"), special_rule).expect("write special attribute");
ensure_no_selected_executable_git_filters(&git, root, &["file.txt".to_string()], &[])
.expect("allow special attribute state");
assert!(!marker_filter_ran(root), "special {driver}");
std::fs::write(
root.join(".gitattributes"),
format!("file.txt filter={driver}\n"),
)
.expect("write literal attribute");
let result =
ensure_no_selected_executable_git_filters(&git, root, &["file.txt".to_string()], &[]);
let error = match result {
Ok(_) => panic!("accepted literal sentinel-named driver {driver}"),
Err(error) => error,
};
assert_eq!(error.kind(), io::ErrorKind::Unsupported, "{driver}");
assert!(!marker_filter_ran(root), "literal {driver}");
}
}
#[test]
fn sentinel_probe_neutralizes_every_known_driver_after_attribute_swap() {
for alternate_driver in ["race", "x=y"] {
let repo = init_filter_repo();
let root = repo.path();
configure_marker_filter(root, "set");
configure_marker_filter(root, alternate_driver);
std::fs::write(root.join(".gitattributes"), "file.txt filter\n")
.expect("write initial attribute");
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
let entries = read_filter_config(&git, root, &[]).expect("filter config");
let executable_drivers = executable_filter_drivers(&entries).expect("executable drivers");
let neutralization = executable_filter_guard(&git, root, entries, &executable_drivers)
.expect("filter neutralization");
let output = run_git_success(root, &["check-attr", "-z", "filter", "--", "file.txt"]);
let attributes = parse_filter_attributes(&output.stdout, &[b"file.txt".to_vec()])
.expect("initial attribute snapshot");
std::fs::write(
root.join(".gitattributes"),
format!("file.txt filter={alternate_driver}\n"),
)
.expect("swap attribute after snapshot");
let resolved = resolve_filter_attribute_sentinels(
&git,
root,
attributes,
&[],
&executable_drivers,
&neutralization,
)
.expect("resolve stale sentinel snapshot safely");
assert!(resolved.is_empty(), "{alternate_driver}");
assert!(!marker_filter_ran(root), "{alternate_driver}");
}
}
#[test]
fn high_cardinality_ordinary_sentinels_stop_at_hard_child_probe_budget() {
let repo = init_filter_repo();
let root = repo.path();
configure_marker_filter(root, "unspecified");
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
let entries = read_filter_config(&git, root, &[]).expect("filter config");
let executable_drivers = executable_filter_drivers(&entries).expect("executable drivers");
let neutralization = executable_filter_guard(&git, root, entries, &executable_drivers)
.expect("filter neutralization");
let attributes = (0..=SentinelFilterProbeBudget::max_probes())
.map(|index| {
(
format!("ordinary-{index}.txt").into_bytes(),
FilterAttributeValue::AmbiguousSentinel("unspecified".to_string()),
)
})
.collect();
let error = resolve_filter_attribute_sentinels(
&git,
root,
attributes,
&[],
&executable_drivers,
&neutralization,
)
.expect_err("refuse sentinel work beyond hard child-probe budget");
assert_eq!(
error.to_string(),
"refusing to continue Git filter sentinel disambiguation after 16 child probes (hard limit: 16)"
);
assert!(!marker_filter_ran(root));
}
#[test]
fn unrelated_sentinel_probe_failures_remain_generic_and_fail_closed() {
let repo = init_filter_repo();
let root = repo.path();
configure_marker_filter(root, "set");
std::fs::write(root.join(".gitattributes"), "file.txt filter\n")
.expect("write special attribute");
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
let entries = read_filter_config(&git, root, &[]).expect("filter config");
let executable_drivers = executable_filter_drivers(&entries).expect("executable drivers");
let neutralization = executable_filter_guard(&git, root, entries, &executable_drivers)
.expect("filter neutralization");
let mut budget = SentinelFilterProbeBudget::default();
let malformed_config = ["-c".to_string(), "=".to_string()];
let error = sentinel_spelling_selects_filter_driver(
&git,
root,
b"file.txt",
"set",
&malformed_config,
&neutralization,
&mut budget,
)
.expect_err("malformed config must fail both probes");
assert_eq!(error.kind(), io::ErrorKind::Other);
assert!(
error
.to_string()
.starts_with("git filter attribute selection probe failed with required status")
);
assert!(!marker_filter_ran(root));
}
fn filter_entries(
scope: GitConfigScope,
origin: &Path,
@@ -156,9 +514,9 @@ fn filter_entries(
value: &str,
) -> BTreeMap<String, GitConfigEntry> {
let origin = if origin == Path::new("command line:") {
"command line:".to_string()
crate::git_config::GitConfigOrigin::CommandLine
} else {
format!("file:{}", origin.display())
crate::git_config::GitConfigOrigin::File(origin.to_path_buf())
};
BTreeMap::from([(
key.to_string(),
@@ -193,7 +551,7 @@ fn run_isolated_test(test_name: &str, env: &[(&str, &OsStr)]) {
);
}
async fn run_git(repo_path: &Path, args: &[&str]) {
async fn run_git_async(repo_path: &Path, args: &[&str]) {
let output = TokioCommand::new("git")
.args(args)
.current_dir(repo_path)
@@ -211,12 +569,12 @@ async fn run_git(repo_path: &Path, args: &[&str]) {
async fn create_test_git_repo(temp_dir: &tempfile::TempDir) -> std::path::PathBuf {
let repo_path = temp_dir.path().join("repo");
std::fs::create_dir(&repo_path).expect("create repo dir");
run_git(&repo_path, &["init"]).await;
run_git(&repo_path, &["config", "user.name", "Test User"]).await;
run_git(&repo_path, &["config", "user.email", "test@example.com"]).await;
run_git_async(&repo_path, &["init"]).await;
run_git_async(&repo_path, &["config", "user.name", "Test User"]).await;
run_git_async(&repo_path, &["config", "user.email", "test@example.com"]).await;
std::fs::write(repo_path.join("test.txt"), "test content").expect("write test file");
run_git(&repo_path, &["add", "."]).await;
run_git(&repo_path, &["commit", "-m", "initial"]).await;
run_git_async(&repo_path, &["add", "."]).await;
run_git_async(&repo_path, &["commit", "-m", "initial"]).await;
repo_path
}
@@ -225,9 +583,9 @@ async fn ordinary_apply_allows_an_unselected_executable_filter() {
let temp_dir = tempfile::tempdir().expect("create temp dir");
let repo_path = create_test_git_repo(&temp_dir).await;
std::fs::write(repo_path.join("test.txt"), "old\n").expect("write fixture");
run_git(&repo_path, &["add", "test.txt"]).await;
run_git(&repo_path, &["commit", "-m", "normalize fixture"]).await;
run_git(
run_git_async(&repo_path, &["add", "test.txt"]).await;
run_git_async(&repo_path, &["commit", "-m", "normalize fixture"]).await;
run_git_async(
&repo_path,
&[
"config",
@@ -259,9 +617,9 @@ async fn configure_clean_filter(repo_path: &Path, tracked_path: &str) {
format!("{tracked_path} filter=x=y\n"),
)
.expect("write attributes");
run_git(repo_path, &["add", ".gitattributes"]).await;
run_git(repo_path, &["commit", "-m", "attributes"]).await;
run_git(
run_git_async(repo_path, &["add", ".gitattributes"]).await;
run_git_async(repo_path, &["commit", "-m", "attributes"]).await;
run_git_async(
repo_path,
&[
"config",
@@ -290,19 +648,19 @@ async fn configured_filter_ran(repo_path: &Path) -> bool {
async fn add_submodule_with_clean_filter(parent: &Path) {
let source = tempfile::tempdir().expect("submodule source");
let source_path = source.path();
run_git(source_path, &["init"]).await;
run_git(source_path, &["config", "user.name", "Test User"]).await;
run_git(source_path, &["config", "user.email", "test@example.com"]).await;
run_git_async(source_path, &["init"]).await;
run_git_async(source_path, &["config", "user.name", "Test User"]).await;
run_git_async(source_path, &["config", "user.email", "test@example.com"]).await;
std::fs::write(source_path.join("nested.txt"), "original\n").expect("nested file");
std::fs::write(
source_path.join(".gitattributes"),
"nested.txt filter=codex-test\n",
)
.expect("nested attributes");
run_git(source_path, &["add", "."]).await;
run_git(source_path, &["commit", "-m", "seed"]).await;
run_git_async(source_path, &["add", "."]).await;
run_git_async(source_path, &["commit", "-m", "seed"]).await;
run_git(
run_git_async(
parent,
&[
"-c",
@@ -314,9 +672,9 @@ async fn add_submodule_with_clean_filter(parent: &Path) {
],
)
.await;
run_git(parent, &["commit", "-m", "add submodule"]).await;
run_git_async(parent, &["commit", "-m", "add submodule"]).await;
let nested = parent.join("nested");
run_git(
run_git_async(
&nested,
&[
"config",
@@ -353,7 +711,7 @@ async fn get_has_changes_distinguishes_filter_sentinels_from_literal_driver_name
let temp_dir = tempfile::tempdir().expect("create temp dir");
let repo_path = create_test_git_repo(&temp_dir).await;
let clean_key = format!("filter.{driver}.clean");
run_git(
run_git_async(
&repo_path,
&[
"config",
@@ -370,8 +728,8 @@ async fn get_has_changes_distinguishes_filter_sentinels_from_literal_driver_name
};
std::fs::write(repo_path.join(".gitattributes"), sentinel)
.expect("write sentinel attribute");
run_git(&repo_path, &["add", ".gitattributes"]).await;
run_git(&repo_path, &["commit", "-m", "sentinel attribute"]).await;
run_git_async(&repo_path, &["add", ".gitattributes"]).await;
run_git_async(&repo_path, &["commit", "-m", "sentinel attribute"]).await;
assert_eq!(try_get_has_changes(&repo_path).await, Ok(false), "{driver}");
assert!(!configured_filter_ran(&repo_path).await, "{driver}");
@@ -415,7 +773,7 @@ async fn checked_has_changes_accepts_non_utf8_repository_root() {
.path()
.join(OsString::from_vec(b"repo-\xff".to_vec()));
std::fs::create_dir(&repo_path).expect("create non-UTF-8 repository directory");
run_git(&repo_path, &["init"]).await;
run_git_async(&repo_path, &["init"]).await;
assert_eq!(try_get_has_changes(&repo_path).await, Ok(false));
}
@@ -444,7 +802,8 @@ async fn root_probe_distinguishes_repository_command_failure() {
permissions.set_mode(0o755);
std::fs::set_permissions(&failing_git, permissions).expect("mark failing Git executable");
let git = GitRunner::from_executable_for_test(failing_git);
let git = GitRunner::from_executable_for_test(&repo_path, failing_git)
.expect("authority-bound failing Git");
assert_eq!(
resolve_git_root_async(&git, &repo_path).await,
Err(GitReadError::CommandFailed {
@@ -463,9 +822,9 @@ async fn legacy_git_without_show_scope_uses_origin_fallback() {
let repo_path = create_test_git_repo(&temp_dir).await;
std::fs::write(repo_path.join(".gitattributes"), "test.txt filter=legacy\n")
.expect("attributes");
run_git(&repo_path, &["add", ".gitattributes"]).await;
run_git(&repo_path, &["commit", "-m", "attributes"]).await;
run_git(
run_git_async(&repo_path, &["add", ".gitattributes"]).await;
run_git_async(&repo_path, &["commit", "-m", "attributes"]).await;
run_git_async(
&repo_path,
&["config", "filter.legacy.clean", "git hash-object --stdin"],
)
@@ -495,10 +854,16 @@ async fn legacy_git_without_show_scope_uses_origin_fallback() {
permissions.set_mode(0o755);
std::fs::set_permissions(&wrapper, permissions).expect("legacy Git executable");
let git = GitRunner::from_executable_for_test(wrapper);
let git = GitRunner::from_executable_for_test(&repo_path, wrapper)
.expect("authority-bound legacy Git");
assert_eq!(
selected_executable_filter_from(&git, &repo_path).await,
Ok(Some(("legacy".to_string(), b"test.txt".to_vec())))
prepare_status_filter_guard(&git, &repo_path)
.await
.map(|_| ()),
Err(GitReadError::SelectedExecutableFilter {
driver: "legacy".to_string(),
path: "test.txt".to_string(),
})
);
}
@@ -510,7 +875,7 @@ async fn get_has_changes_rejects_core_worktree_redirection_before_running_filter
std::fs::create_dir(&redirected).expect("redirected worktree");
std::fs::write(redirected.join(".gitattributes"), "test.txt filter=x=y\n").expect("attributes");
std::fs::write(redirected.join("test.txt"), "redirected content\n").expect("redirected file");
run_git(
run_git_async(
&repo_path,
&[
"config",
@@ -519,7 +884,7 @@ async fn get_has_changes_rejects_core_worktree_redirection_before_running_filter
],
)
.await;
run_git(
run_git_async(
&repo_path,
&[
"config",
@@ -543,8 +908,8 @@ async fn legacy_git_config_cannot_hide_a_selected_local_filter_from_probe() {
let repo_path = create_test_git_repo(&temp_dir).await;
std::fs::write(repo_path.join(".gitattributes"), "test.txt filter=evil\n")
.expect("attributes");
run_git(&repo_path, &["add", ".gitattributes"]).await;
run_git(&repo_path, &["commit", "-m", "attributes"]).await;
run_git_async(&repo_path, &["add", ".gitattributes"]).await;
run_git_async(&repo_path, &["commit", "-m", "attributes"]).await;
let marker = temp_dir.path().join("filter-ran");
let filter = repo_path.join("clean.sh");
@@ -558,7 +923,7 @@ async fn legacy_git_config_cannot_hide_a_selected_local_filter_from_probe() {
.permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(&filter, permissions).expect("filter executable");
run_git(
run_git_async(
&repo_path,
&[
"config",
@@ -635,7 +1000,7 @@ async fn apply_and_stage_reject_global_relative_filter_without_running_it() {
.permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(repo_path.join("clean.sh"), permissions).expect("filter executable");
run_git(
run_git_async(
&repo_path,
&[
"-c",
@@ -646,7 +1011,7 @@ async fn apply_and_stage_reject_global_relative_filter_without_running_it() {
],
)
.await;
run_git(
run_git_async(
&repo_path,
&["-c", "filter.evil.clean=", "commit", "-m", "fixture"],
)
@@ -687,8 +1052,8 @@ async fn nested_cwd_rejects_global_lfs_filter_without_running_it() {
std::fs::create_dir(&repo_bin).expect("repository bin");
std::fs::write(repo_path.join(".gitattributes"), "test.txt filter=lfs\n")
.expect("attributes");
run_git(&repo_path, &["add", ".gitattributes"]).await;
run_git(&repo_path, &["commit", "-m", "attributes"]).await;
run_git_async(&repo_path, &["add", ".gitattributes"]).await;
run_git_async(&repo_path, &["commit", "-m", "attributes"]).await;
std::fs::write(repo_path.join("test.txt"), "changed\n").expect("modify tracked file");
let config_dir = tempfile::tempdir().expect("config tempdir");