mirror of
https://github.com/openai/codex.git
synced 2026-11-21 22:50:37 +00:00
Merge three-way safeguards and harden frozen Git status reads
This commit is contained in:
Generated
+5
-2
@@ -3134,9 +3134,11 @@ dependencies = [
|
||||
"codex-utils-path-uri",
|
||||
"futures",
|
||||
"gix",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"pretty_assertions",
|
||||
"regex",
|
||||
"rustix 1.1.4",
|
||||
"same-file",
|
||||
"schemars 0.8.22",
|
||||
"serde",
|
||||
@@ -3146,6 +3148,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"ts-rs",
|
||||
"walkdir",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4821,9 +4824,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.18"
|
||||
version = "0.9.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
|
||||
checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
@@ -172,10 +172,7 @@ console.log(fib(10));
|
||||
|
||||
let apply_result = apply_diff_from_task(task_response, Some(repo_path.to_path_buf())).await;
|
||||
|
||||
assert!(
|
||||
apply_result.is_err(),
|
||||
"Expected apply to fail due to merge conflicts"
|
||||
);
|
||||
let apply_error = apply_result.expect_err("Expected apply to fail due to merge conflicts");
|
||||
|
||||
let contents = std::fs::read_to_string(&fibonacci_path).expect("Failed to read fibonacci.js");
|
||||
|
||||
@@ -183,6 +180,6 @@ console.log(fib(10));
|
||||
contents.contains("<<<<<<< HEAD")
|
||||
|| contents.contains("=======")
|
||||
|| contents.contains(">>>>>>> "),
|
||||
"fibonacci.js should contain merge conflict markers, got: {contents}",
|
||||
"fibonacci.js should contain merge conflict markers, got: {contents}\napply error: {apply_error:#}",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ codex-file-system = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
futures = { workspace = true, features = ["alloc", "executor"] }
|
||||
futures = { workspace = true, features = ["alloc"] }
|
||||
gix = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
regex = "1"
|
||||
@@ -33,7 +33,17 @@ ts-rs = { workspace = true, features = [
|
||||
] }
|
||||
walkdir = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
rustix = { version = "1.1.4", features = ["fs"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.52", features = ["Win32_Storage_FileSystem"] }
|
||||
|
||||
[dev-dependencies]
|
||||
futures = { workspace = true, features = ["executor"] }
|
||||
pretty_assertions = { workspace = true }
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
|
||||
+574
-218
@@ -10,15 +10,16 @@ use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::FsmonitorOverride;
|
||||
use crate::apply_output::parse_git_apply_output;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::guarded_config::GuardedGitConfig;
|
||||
use crate::patch_paths::extract_patch_path_inventory_guarded;
|
||||
use crate::reverse_staging::stage_effective_paths_for_reverse;
|
||||
#[cfg(test)]
|
||||
use crate::safe_git::DISABLED_HOOKS_PATH;
|
||||
use crate::reverse_staging::ReverseApplyMode;
|
||||
use crate::reverse_staging::execute_reverse_staging_plan;
|
||||
use crate::reverse_staging::execute_reverse_staging_plan_in_scratch;
|
||||
use crate::reverse_staging::prepare_reverse_staging_plan;
|
||||
use crate::reverse_staging::seal_reverse_staging_plan;
|
||||
use crate::reverse_staging::validate_effective_paths_for_reverse;
|
||||
#[cfg(test)]
|
||||
use crate::safe_git::isolate_git_command_environment;
|
||||
|
||||
@@ -43,6 +44,47 @@ pub struct ApplyGitResult {
|
||||
pub cmd_for_log: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum ApplyStrategy {
|
||||
Direct,
|
||||
ThreeWay,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static AFTER_REVERSE_STAGING_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
|
||||
std::cell::RefCell::new(None);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_after_reverse_staging_hook(hook: impl FnOnce() + 'static) {
|
||||
AFTER_REVERSE_STAGING_HOOK.with(|slot| {
|
||||
let previous = slot.borrow_mut().replace(Box::new(hook));
|
||||
assert!(
|
||||
previous.is_none(),
|
||||
"reverse staging test hook already installed"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn run_after_reverse_staging_hook() {
|
||||
AFTER_REVERSE_STAGING_HOOK.with(|slot| {
|
||||
if let Some(hook) = slot.borrow_mut().take() {
|
||||
hook();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
impl ApplyStrategy {
|
||||
fn reverse_mode(self) -> ReverseApplyMode {
|
||||
match self {
|
||||
Self::Direct => ReverseApplyMode::Direct,
|
||||
Self::ThreeWay => ReverseApplyMode::ThreeWay,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a unified diff to the target repository by shelling out to `git apply`.
|
||||
///
|
||||
/// When [`ApplyGitRequest::preflight`] is `true`, this behaves like `git apply --check` and
|
||||
@@ -58,6 +100,7 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
.and_then(std::fs::canonicalize)?;
|
||||
let mut config = GuardedGitConfig::authorize(&git, &expected_root, cfg_parts)?;
|
||||
resolve_git_root(&config, &requested_cwd)?;
|
||||
config.freeze_apply_policy()?;
|
||||
|
||||
// Write unified diff into a temporary file
|
||||
let (tmpdir, patch_path) = write_temp_patch(&req.diff)?;
|
||||
@@ -69,15 +112,38 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
config.authorize_filter_paths(patch_paths)?;
|
||||
let patch_arg = patch_path.to_string_lossy().to_string();
|
||||
|
||||
// Applicability checks conflate content conflicts with fatal whitespace
|
||||
// policy. Parse the requested orientation independently first: numstat
|
||||
// enforces the frozen whitespace policy without consulting or changing
|
||||
// the index/worktree. This ordering makes a mixed conflict + policy error
|
||||
// fail before merge-policy reads or reverse staging.
|
||||
let (policy_rendered, policy_output) = config.run_apply_policy_gate(req.revert, &patch_arg)?;
|
||||
let policy_code = policy_output.status.code().unwrap_or(-1);
|
||||
let policy_stdout = String::from_utf8_lossy(&policy_output.stdout).into_owned();
|
||||
let policy_stderr = String::from_utf8_lossy(&policy_output.stderr).into_owned();
|
||||
if policy_code != 0 {
|
||||
return Ok(structured_apply_result(
|
||||
policy_code,
|
||||
policy_stdout,
|
||||
policy_stderr,
|
||||
policy_rendered,
|
||||
));
|
||||
}
|
||||
|
||||
// Optional preflight: dry-run only; do not modify working tree
|
||||
if req.preflight {
|
||||
let mut check_args = vec!["apply".to_string(), "--check".to_string()];
|
||||
let (rendered, output) = config.run_apply_preflight_check(req.revert, &patch_arg)?;
|
||||
let c_code = output.status.code().unwrap_or(-1);
|
||||
let c_out = String::from_utf8_lossy(&output.stdout).into_owned();
|
||||
let c_err = String::from_utf8_lossy(&output.stderr).into_owned();
|
||||
if req.revert {
|
||||
check_args.push("-R".to_string());
|
||||
let mode = if c_code == 0 {
|
||||
ReverseApplyMode::Direct
|
||||
} else {
|
||||
ReverseApplyMode::ThreeWay
|
||||
};
|
||||
validate_effective_paths_for_reverse(&config, patch_paths, mode)?;
|
||||
}
|
||||
check_args.push(patch_arg);
|
||||
let rendered = config.render_command_for_log(&check_args)?;
|
||||
let (c_code, c_out, c_err) = run_guarded_apply(&config, &check_args)?;
|
||||
let (mut applied_paths, mut skipped_paths, mut conflicted_paths) =
|
||||
parse_git_apply_output(&c_out, &c_err);
|
||||
applied_paths.sort();
|
||||
@@ -101,35 +167,71 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
// reverse check must inspect the working tree before staging: requiring
|
||||
// the old index to match would misclassify a clean undo as a three-way
|
||||
// fallback. Forward direct application still requires index agreement.
|
||||
let mut plain_check_args = vec!["apply".to_string(), "--check".to_string()];
|
||||
if !req.revert {
|
||||
plain_check_args.push("--index".to_string());
|
||||
}
|
||||
if req.revert {
|
||||
plain_check_args.push("-R".to_string());
|
||||
}
|
||||
plain_check_args.push(patch_arg.clone());
|
||||
let (plain_check_code, _, _) = run_guarded_apply(&config, &plain_check_args)?;
|
||||
let plain_check = config.run_apply_strategy_check(req.revert, &patch_arg)?;
|
||||
let plain_check_code = plain_check.status.code().unwrap_or(-1);
|
||||
|
||||
let mut args = vec!["apply".to_string()];
|
||||
if plain_check_code != 0 {
|
||||
config.install_three_way_merge_policy()?;
|
||||
args.push("--3way".to_string());
|
||||
let strategy = if plain_check_code != 0 {
|
||||
ApplyStrategy::ThreeWay
|
||||
} else {
|
||||
args.push("--index".to_string());
|
||||
}
|
||||
if req.revert {
|
||||
// Stage only after the worktree-only applicability decision. The
|
||||
// guarded config is shared with the final Git command.
|
||||
stage_effective_paths_for_reverse(&mut config, patch_paths)?;
|
||||
}
|
||||
if req.revert {
|
||||
args.push("-R".to_string());
|
||||
}
|
||||
args.push(patch_arg);
|
||||
ApplyStrategy::Direct
|
||||
};
|
||||
let reverse_plan = req
|
||||
.revert
|
||||
.then(|| prepare_reverse_staging_plan(&config, patch_paths, strategy.reverse_mode()))
|
||||
.transpose()?;
|
||||
|
||||
let cmd_for_log = config.render_command_for_log(&args)?;
|
||||
let (code, stdout, stderr) = run_guarded_apply(&config, &args)?;
|
||||
if strategy == ApplyStrategy::ThreeWay {
|
||||
config.install_three_way_merge_policy(&patch_path_inventory.primary_records)?;
|
||||
}
|
||||
let mut reverse_plan = reverse_plan
|
||||
.map(|plan| seal_reverse_staging_plan(&mut config, plan))
|
||||
.transpose()?;
|
||||
|
||||
if strategy == ApplyStrategy::ThreeWay && config.three_way_requires_merge_policy_proof()? {
|
||||
let scratch = config.create_three_way_scratch_storage()?;
|
||||
if let Some(plan) = &mut reverse_plan {
|
||||
execute_reverse_staging_plan_in_scratch(&config, plan, &scratch)?;
|
||||
}
|
||||
config.prove_three_way_merge_policy_safety(&scratch, req.revert, &patch_arg)?;
|
||||
}
|
||||
|
||||
if let Some(plan) = reverse_plan {
|
||||
// The same sealed plan was modeled in scratch before any merge-policy
|
||||
// refusal could mutate the real index.
|
||||
execute_reverse_staging_plan(&config, plan)?;
|
||||
#[cfg(test)]
|
||||
run_after_reverse_staging_hook();
|
||||
}
|
||||
|
||||
let (cmd_for_log, output) = match strategy {
|
||||
ApplyStrategy::Direct => {
|
||||
// The fixed helper requires proof that the successful frozen-
|
||||
// policy gate covered this exact patch and orientation.
|
||||
let rendered = config.render_direct_apply_for_log(req.revert, &patch_arg)?;
|
||||
let output = config.run_direct_apply(req.revert, &patch_arg)?;
|
||||
(
|
||||
rendered,
|
||||
(
|
||||
output.status.code().unwrap_or(-1),
|
||||
String::from_utf8_lossy(&output.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
),
|
||||
)
|
||||
}
|
||||
ApplyStrategy::ThreeWay => {
|
||||
let rendered = config.render_three_way_apply_for_log(req.revert, &patch_arg)?;
|
||||
let output = config.run_three_way_apply(req.revert, &patch_arg)?;
|
||||
(
|
||||
rendered,
|
||||
(
|
||||
output.status.code().unwrap_or(-1),
|
||||
String::from_utf8_lossy(&output.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
),
|
||||
)
|
||||
}
|
||||
};
|
||||
let (code, stdout, stderr) = output;
|
||||
|
||||
let (mut applied_paths, mut skipped_paths, mut conflicted_paths) = if code == 0 {
|
||||
(patch_path_inventory.primary_paths, Vec::new(), Vec::new())
|
||||
@@ -154,6 +256,31 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
})
|
||||
}
|
||||
|
||||
fn structured_apply_result(
|
||||
exit_code: i32,
|
||||
stdout: String,
|
||||
stderr: String,
|
||||
cmd_for_log: String,
|
||||
) -> ApplyGitResult {
|
||||
let (mut applied_paths, mut skipped_paths, mut conflicted_paths) =
|
||||
parse_git_apply_output(&stdout, &stderr);
|
||||
applied_paths.sort();
|
||||
applied_paths.dedup();
|
||||
skipped_paths.sort();
|
||||
skipped_paths.dedup();
|
||||
conflicted_paths.sort();
|
||||
conflicted_paths.dedup();
|
||||
ApplyGitResult {
|
||||
exit_code,
|
||||
applied_paths,
|
||||
skipped_paths,
|
||||
conflicted_paths,
|
||||
stdout,
|
||||
stderr,
|
||||
cmd_for_log,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_git_root(config: &GuardedGitConfig<'_>, requested_cwd: &Path) -> io::Result<PathBuf> {
|
||||
let mut command = config.rev_parse_command()?;
|
||||
command.arg("--show-toplevel");
|
||||
@@ -205,42 +332,6 @@ pub(crate) fn write_temp_patch(diff: &str) -> io::Result<(tempfile::TempDir, Pat
|
||||
Ok((dir, path))
|
||||
}
|
||||
|
||||
fn run_guarded_apply(
|
||||
config: &GuardedGitConfig<'_>,
|
||||
args: &[String],
|
||||
) -> io::Result<(i32, String, String)> {
|
||||
let Some((subcommand, args)) = args.split_first() else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"missing guarded Git subcommand",
|
||||
));
|
||||
};
|
||||
if subcommand != "apply" {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"unexpected guarded Git subcommand",
|
||||
));
|
||||
}
|
||||
let mut command = config.apply_command()?;
|
||||
command.args(args);
|
||||
let output = command.output()?;
|
||||
Ok((
|
||||
output.status.code().unwrap_or(-1),
|
||||
String::from_utf8_lossy(&output.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn safe_git_config_parts() -> Vec<String> {
|
||||
vec![
|
||||
"-c".to_string(),
|
||||
format!("core.hooksPath={DISABLED_HOOKS_PATH}"),
|
||||
"-c".to_string(),
|
||||
FsmonitorOverride::Disabled.git_config_arg().to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "apply_transport_tests.rs"]
|
||||
mod transport_tests;
|
||||
@@ -259,6 +350,7 @@ mod tests {
|
||||
use crate::guarded_config::config_source_authorization_count;
|
||||
use crate::guarded_config::merge_attribute_read_count;
|
||||
use crate::guarded_config::merge_config_read_count;
|
||||
use crate::guarded_config::merge_overlay_count;
|
||||
use crate::guarded_config::reset_config_source_authorization_count;
|
||||
use crate::guarded_config::reset_merge_policy_counts;
|
||||
use crate::safe_git::filter_policy_overlay_count;
|
||||
@@ -326,57 +418,6 @@ mod tests {
|
||||
.replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
fn commit_filter_attributes(root: &Path, tracked_path: &str) {
|
||||
std::fs::write(
|
||||
root.join(".gitattributes"),
|
||||
format!("{tracked_path} filter=x=y\n"),
|
||||
)
|
||||
.expect("write attributes");
|
||||
let (add_code, _, add_err) = run(root, &["git", "add", ".gitattributes"]);
|
||||
assert_eq!(add_code, 0, "add attributes: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "attributes"]);
|
||||
assert_eq!(commit_code, 0, "commit attributes: {commit_err}");
|
||||
}
|
||||
|
||||
fn configure_clean_filter(root: &Path, tracked_path: &str) {
|
||||
commit_filter_attributes(root, tracked_path);
|
||||
let (config_code, _, config_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"config",
|
||||
"filter.x=y.clean",
|
||||
"git config codex.filterran true && git hash-object --stdin",
|
||||
],
|
||||
);
|
||||
assert_eq!(config_code, 0, "configure filter: {config_err}");
|
||||
}
|
||||
|
||||
fn configure_worktree_clean_filter(root: &Path, tracked_path: &str) {
|
||||
commit_filter_attributes(root, tracked_path);
|
||||
let (extension_code, _, extension_err) = run(
|
||||
root,
|
||||
&["git", "config", "extensions.worktreeConfig", "true"],
|
||||
);
|
||||
assert_eq!(extension_code, 0, "enable worktree config: {extension_err}");
|
||||
let (config_code, _, config_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"config",
|
||||
"--worktree",
|
||||
"filter.x=y.clean",
|
||||
"git config codex.filterran true && git hash-object --stdin",
|
||||
],
|
||||
);
|
||||
assert_eq!(config_code, 0, "configure worktree filter: {config_err}");
|
||||
}
|
||||
|
||||
fn configured_filter_ran(root: &Path) -> bool {
|
||||
let (code, _, _) = run(root, &["git", "config", "--get", "codex.filterran"]);
|
||||
code == 0
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn trusted_git_directory() -> PathBuf {
|
||||
std::env::split_paths(&std::env::var_os("PATH").expect("PATH"))
|
||||
@@ -440,6 +481,416 @@ mod tests {
|
||||
assert!(!root.join("preflight.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_resolves_relative_primary_config_from_repository_root() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
if std::env::var_os("CODEX_GIT_UTILS_APPLY_ENV_CHILD").is_none() {
|
||||
run_isolated_test(
|
||||
"apply::tests::apply_resolves_relative_primary_config_from_repository_root",
|
||||
&[("GIT_CONFIG_GLOBAL", OsStr::new("../external/config"))],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let root = fixture.path().join("repo");
|
||||
let nested_cwd = root.join("nested");
|
||||
let external_config = fixture.path().join("external/config");
|
||||
let mismatched_nested_config = root.join("external/config");
|
||||
std::fs::create_dir_all(&nested_cwd).expect("nested cwd");
|
||||
std::fs::create_dir_all(external_config.parent().expect("config parent"))
|
||||
.expect("external config directory");
|
||||
std::fs::create_dir_all(
|
||||
mismatched_nested_config
|
||||
.parent()
|
||||
.expect("mismatched config parent"),
|
||||
)
|
||||
.expect("mismatched config directory");
|
||||
std::fs::write(&external_config, "[codex]\n\tprobe = loaded\n").expect("external config");
|
||||
std::fs::write(&mismatched_nested_config, "[invalid\n")
|
||||
.expect("mismatched nested-cwd config");
|
||||
let (init_code, _, init_err) = run(&root, &["git", "init"]);
|
||||
assert_eq!(init_code, 0, "init repository: {init_err}");
|
||||
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: nested_cwd,
|
||||
diff: "diff --git a/hello.txt b/hello.txt\nnew file mode 100644\n--- /dev/null\n+++ b/hello.txt\n@@ -0,0 +1 @@\n+hello\n".to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("apply with root-relative primary config");
|
||||
assert_eq!(result.exit_code, 0, "apply result: {result:?}");
|
||||
assert_eq!(read_file_normalized(&root.join("hello.txt")), "hello\n");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn apply_refuses_process_relative_primary_config_before_mutating_the_repository() {
|
||||
const TEST_NAME: &str = "apply::tests::apply_refuses_process_relative_primary_config_before_mutating_the_repository";
|
||||
if std::env::var_os("CODEX_GIT_UTILS_APPLY_ENV_CHILD").is_none() {
|
||||
run_isolated_test(
|
||||
TEST_NAME,
|
||||
&[
|
||||
(
|
||||
"GIT_CONFIG_GLOBAL",
|
||||
OsStr::new("/proc/self/cwd/codex-process-relative.gitconfig"),
|
||||
),
|
||||
("GIT_CONFIG_NOSYSTEM", OsStr::new("1")),
|
||||
],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(
|
||||
root.join("codex-process-relative.gitconfig"),
|
||||
"[filter \"unsafe\"]\nclean = false\n",
|
||||
)
|
||||
.expect("worktree config");
|
||||
let before_index = run(root, &["git", "ls-files", "--stage", "-z"]).1;
|
||||
let request = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: "diff --git a/hello.txt b/hello.txt\nnew file mode 100644\n--- /dev/null\n+++ b/hello.txt\n@@ -0,0 +1 @@\n+hello\n".to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
};
|
||||
|
||||
let error = apply_git_patch(&request).expect_err("process-relative primary config");
|
||||
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
|
||||
assert!(error.to_string().contains("process-relative"), "{error}");
|
||||
assert!(!root.join("hello.txt").exists());
|
||||
assert_eq!(
|
||||
run(root, &["git", "ls-files", "--stage", "-z"]).1,
|
||||
before_index
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numstat_path_discovery_does_not_preempt_apply_whitespace_result() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
let (config_code, _, config_err) =
|
||||
run(root, &["git", "config", "apply.whitespace", "error"]);
|
||||
assert_eq!(config_code, 0, "configure whitespace policy: {config_err}");
|
||||
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: "diff --git a/trailing.txt b/trailing.txt\nnew file mode 100644\n--- /dev/null\n+++ b/trailing.txt\n@@ -0,0 +1 @@\n+trailing \n".to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("path discovery must leave apply failure in the structured result");
|
||||
assert_ne!(result.exit_code, 0);
|
||||
assert!(
|
||||
result.stderr.contains("trailing whitespace"),
|
||||
"apply result: {result:?}"
|
||||
);
|
||||
assert!(!root.join("trailing.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fatal_whitespace_policy_precedes_selected_merge_driver_without_mutation() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
for policy in ["error", "error-all"] {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join(".gitattributes"), "file.txt merge=selected\n")
|
||||
.expect("write attributes");
|
||||
std::fs::write(root.join("file.txt"), "old\n").expect("write file");
|
||||
assert_eq!(run(root, &["git", "add", "."]).0, 0);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0);
|
||||
assert_eq!(
|
||||
run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"config",
|
||||
"merge.selected.driver",
|
||||
"git config --file .git/config codex.mergeran true && false",
|
||||
],
|
||||
)
|
||||
.0,
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
run(root, &["git", "config", "apply.whitespace", policy]).0,
|
||||
0
|
||||
);
|
||||
let index_before = std::fs::read(root.join(".git/index")).expect("read index");
|
||||
|
||||
reset_merge_policy_counts();
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new \n".to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("return structured whitespace failure");
|
||||
|
||||
assert_ne!(result.exit_code, 0, "{policy}: {result:?}");
|
||||
assert!(
|
||||
result.stderr.contains("trailing whitespace"),
|
||||
"{policy}: {result:?}"
|
||||
);
|
||||
assert!(result.cmd_for_log.contains("--numstat"), "{result:?}");
|
||||
assert_eq!(merge_config_read_count(), 0, "{policy}");
|
||||
assert_eq!(merge_attribute_read_count(), 0, "{policy}");
|
||||
assert_eq!(merge_overlay_count(), 0, "{policy}");
|
||||
assert_eq!(read_file_normalized(&root.join("file.txt")), "old\n");
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".git/index")).expect("reread index"),
|
||||
index_before,
|
||||
"{policy}"
|
||||
);
|
||||
assert_ne!(
|
||||
run(root, &["git", "config", "--get", "codex.mergeran"]).0,
|
||||
0,
|
||||
"{policy}: merge driver must not run"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonfatal_whitespace_policies_reach_the_final_apply() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
for (policy, expected) in [("warn", "new \n"), ("fix", "new\n")] {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("file.txt"), "old\n").expect("write file");
|
||||
assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0);
|
||||
assert_eq!(
|
||||
run(root, &["git", "config", "apply.whitespace", policy]).0,
|
||||
0
|
||||
);
|
||||
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new \n".to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("apply with nonfatal whitespace policy");
|
||||
|
||||
assert_eq!(result.exit_code, 0, "{policy}: {result:?}");
|
||||
assert_eq!(read_file_normalized(&root.join("file.txt")), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fatal_whitespace_gate_remains_authoritative_after_reverse_staging() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
for policy in ["error", "error-all"] {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join(".gitattributes"), "file.txt -whitespace\n")
|
||||
.expect("write permissive attributes");
|
||||
std::fs::write(root.join("file.txt"), "bad \n").expect("write base file");
|
||||
assert_eq!(
|
||||
run(root, &["git", "add", ".gitattributes", "file.txt"]).0,
|
||||
0
|
||||
);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0);
|
||||
std::fs::write(root.join("file.txt"), "good\n").expect("write patched file");
|
||||
let patch = run(root, &["git", "diff", "--full-index", "--", "file.txt"]);
|
||||
assert_eq!(patch.0, 0, "create patch: {}", patch.2);
|
||||
assert_eq!(
|
||||
run(root, &["git", "config", "apply.whitespace", policy]).0,
|
||||
0
|
||||
);
|
||||
|
||||
let attributes = root.join(".gitattributes");
|
||||
install_after_reverse_staging_hook(move || {
|
||||
std::fs::write(attributes, "file.txt whitespace\n")
|
||||
.expect("tighten whitespace attributes after staging");
|
||||
});
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: patch.1,
|
||||
revert: true,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("reverse apply after attribute mutation");
|
||||
|
||||
assert_eq!(result.exit_code, 0, "{policy}: {result:?}");
|
||||
assert!(
|
||||
result.cmd_for_log.contains("--whitespace=nowarn"),
|
||||
"{policy}: {}",
|
||||
result.cmd_for_log
|
||||
);
|
||||
assert_eq!(
|
||||
read_file_normalized(&root.join(".gitattributes")),
|
||||
"file.txt whitespace\n",
|
||||
"{policy}: race hook did not tighten the attribute"
|
||||
);
|
||||
assert_eq!(read_file_normalized(&root.join("file.txt")), "bad \n");
|
||||
let cached = run(
|
||||
root,
|
||||
&["git", "diff", "--cached", "--quiet", "--", "file.txt"],
|
||||
);
|
||||
assert_eq!(cached.0, 0, "{policy}: index retained staged data");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fatal_whitespace_gate_and_projection_cover_reverse_three_way_staging() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join(".gitattributes"), "file.txt -whitespace\n")
|
||||
.expect("write permissive attributes");
|
||||
let base_contents = "01\n02\n03\n04\n05\n06\n07\n08\n09\nbad \n11\n12\n13\n14\n15\n";
|
||||
let patched_contents = "01\n02\n03\n04\n05\n06\n07\n08\n09\ngood\n11\n12\n13\n14\n15\n";
|
||||
let independent_contents =
|
||||
"01\n02\n03\n04\n05\n06\nSEVEN\n08\n09\ngood\n11\n12\n13\n14\n15\n";
|
||||
let expected_contents = "01\n02\n03\n04\n05\n06\nSEVEN\n08\n09\nbad \n11\n12\n13\n14\n15\n";
|
||||
std::fs::write(root.join("file.txt"), base_contents).expect("write base");
|
||||
assert_eq!(
|
||||
run(root, &["git", "add", ".gitattributes", "file.txt"]).0,
|
||||
0
|
||||
);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0);
|
||||
let base = run(root, &["git", "rev-parse", "HEAD"]).1;
|
||||
std::fs::write(root.join("file.txt"), patched_contents).expect("write patch side");
|
||||
assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "patched"]).0, 0);
|
||||
let patch = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"diff",
|
||||
"--full-index",
|
||||
base.trim(),
|
||||
"HEAD",
|
||||
"--",
|
||||
"file.txt",
|
||||
],
|
||||
);
|
||||
assert_eq!(patch.0, 0, "create patch: {}", patch.2);
|
||||
std::fs::write(root.join("file.txt"), independent_contents)
|
||||
.expect("write independent worktree edit");
|
||||
assert_eq!(
|
||||
run(root, &["git", "config", "apply.whitespace", "error"]).0,
|
||||
0
|
||||
);
|
||||
|
||||
let attributes = root.join(".gitattributes");
|
||||
install_after_reverse_staging_hook(move || {
|
||||
std::fs::write(attributes, "file.txt whitespace\n")
|
||||
.expect("tighten whitespace attributes after staging");
|
||||
});
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: patch.1,
|
||||
revert: true,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("reverse three-way after attribute mutation");
|
||||
|
||||
assert_eq!(result.exit_code, 0, "{result:?}");
|
||||
assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=<isolated>"));
|
||||
assert!(result.cmd_for_log.contains("--3way"));
|
||||
assert!(result.cmd_for_log.contains("--whitespace=nowarn"));
|
||||
assert_eq!(
|
||||
read_file_normalized(&root.join(".gitattributes")),
|
||||
"file.txt whitespace\n",
|
||||
"race hook did not tighten the attribute"
|
||||
);
|
||||
assert_eq!(
|
||||
read_file_normalized(&root.join("file.txt")),
|
||||
expected_contents
|
||||
);
|
||||
assert_eq!(
|
||||
run(root, &["git", "diff", "--quiet", "--", "file.txt"]).0,
|
||||
0,
|
||||
"final index and worktree differ"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_reverse_conflict_and_whitespace_error_does_not_mutate() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
let base = "01\n02\n03\n04\n05\n06\n07\n08\n09\n10\nbase \n12\n13\n14\n15\n";
|
||||
let theirs = "01\n02\n03\n04\n05\n06\n07\n08\n09\n10\ntheirs\n12\n13\n14\n15\n";
|
||||
let independently_edited =
|
||||
"01\n02\n03\n04\n05\n06\n07\nEIGHT\n09\n10\ntheirs\n12\n13\n14\n15\n";
|
||||
std::fs::write(root.join("file.txt"), base).expect("write base");
|
||||
assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0);
|
||||
let base_oid = run(root, &["git", "rev-parse", "HEAD"]).1;
|
||||
std::fs::write(root.join("file.txt"), theirs).expect("write theirs");
|
||||
assert_eq!(run(root, &["git", "add", "file.txt"]).0, 0);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "theirs"]).0, 0);
|
||||
let patch = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"diff",
|
||||
"--full-index",
|
||||
base_oid.trim(),
|
||||
"HEAD",
|
||||
"--",
|
||||
"file.txt",
|
||||
],
|
||||
);
|
||||
assert_eq!(patch.0, 0, "create patch: {}", patch.2);
|
||||
std::fs::write(root.join("file.txt"), independently_edited)
|
||||
.expect("write independent edit");
|
||||
let patch_dir = tempfile::tempdir().expect("patch directory");
|
||||
let patch_path = patch_dir.path().join("mixed.diff");
|
||||
std::fs::write(&patch_path, &patch.1).expect("write patch");
|
||||
let patch_path = patch_path.to_str().expect("UTF-8 patch path");
|
||||
let structural = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"apply",
|
||||
"--check",
|
||||
"--whitespace=nowarn",
|
||||
"-R",
|
||||
patch_path,
|
||||
],
|
||||
);
|
||||
assert_ne!(
|
||||
structural.0, 0,
|
||||
"fixture must retain a structural reverse conflict"
|
||||
);
|
||||
assert_eq!(
|
||||
run(root, &["git", "config", "apply.whitespace", "error"]).0,
|
||||
0
|
||||
);
|
||||
let index_before = std::fs::read(root.join(".git/index")).expect("read index");
|
||||
let worktree_before = std::fs::read(root.join("file.txt")).expect("read worktree");
|
||||
|
||||
reset_merge_policy_counts();
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: patch.1,
|
||||
revert: true,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("return mixed policy failure");
|
||||
|
||||
assert_ne!(result.exit_code, 0, "{result:?}");
|
||||
assert!(result.stderr.contains("trailing whitespace"), "{result:?}");
|
||||
assert_eq!(merge_config_read_count(), 0);
|
||||
assert_eq!(merge_attribute_read_count(), 0);
|
||||
assert_eq!(merge_overlay_count(), 0);
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".git/index")).expect("reread index"),
|
||||
index_before
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(root.join("file.txt")).expect("reread worktree"),
|
||||
worktree_before
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_uses_cwd_repo_despite_inherited_repository_selectors() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
@@ -794,101 +1245,6 @@ diff --git a/ghost.txt b/ghost.txt\n--- a/ghost.txt\n+++ b/ghost.txt\n@@ -1,1 +1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_rejects_configured_clean_filter_without_running_it() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("file.txt"), "orig\n").expect("write file");
|
||||
let (add_code, _, add_err) = run(root, &["git", "add", "file.txt"]);
|
||||
assert_eq!(add_code, 0, "add file: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "seed"]);
|
||||
assert_eq!(commit_code, 0, "commit file: {commit_err}");
|
||||
configure_clean_filter(root, "file.txt");
|
||||
|
||||
let diff = "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1,1 +1,1 @@\n-orig\n+next\n";
|
||||
for (revert, preflight) in [(false, false), (false, true), (true, false), (true, true)] {
|
||||
let request = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert,
|
||||
preflight,
|
||||
};
|
||||
reset_config_source_authorization_count();
|
||||
let error = apply_git_patch(&request).expect_err("reject configured filter");
|
||||
assert_eq!(
|
||||
config_source_authorization_count(),
|
||||
1,
|
||||
"{revert} {preflight}"
|
||||
);
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
assert!(!configured_filter_ran(root));
|
||||
assert_eq!(read_file_normalized(&root.join("file.txt")), "orig\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_rejects_worktree_scoped_clean_filter_without_running_it() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("file.txt"), "orig\n").expect("write file");
|
||||
let (add_code, _, add_err) = run(root, &["git", "add", "file.txt"]);
|
||||
assert_eq!(add_code, 0, "add file: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "seed"]);
|
||||
assert_eq!(commit_code, 0, "commit file: {commit_err}");
|
||||
configure_worktree_clean_filter(root, "file.txt");
|
||||
|
||||
let request = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1,1 +1,1 @@\n-orig\n+next\n".to_string(),
|
||||
revert: false,
|
||||
preflight: true,
|
||||
};
|
||||
let error = apply_git_patch(&request).expect_err("reject worktree filter");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
assert!(!configured_filter_ran(root));
|
||||
assert_eq!(read_file_normalized(&root.join("file.txt")), "orig\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_probe_rejects_command_scoped_clean_filter() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
if std::env::var_os("CODEX_GIT_UTILS_APPLY_ENV_CHILD").is_none() {
|
||||
run_isolated_test(
|
||||
"apply::tests::apply_probe_rejects_command_scoped_clean_filter",
|
||||
&[(
|
||||
"CODEX_APPLY_GIT_CFG",
|
||||
OsStr::new(
|
||||
"filter.codex-test.clean=git config codex.filterran true && git hash-object --stdin",
|
||||
),
|
||||
)],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("test.txt"), "orig\n").expect("write file");
|
||||
let (add_code, _, add_err) = run(root, &["git", "add", "test.txt"]);
|
||||
assert_eq!(add_code, 0, "add file: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "seed"]);
|
||||
assert_eq!(commit_code, 0, "commit file: {commit_err}");
|
||||
std::fs::write(root.join(".gitattributes"), "test.txt filter=codex-test\n")
|
||||
.expect("attributes");
|
||||
|
||||
let request = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: "diff --git a/test.txt b/test.txt\n--- a/test.txt\n+++ b/test.txt\n@@ -1 +1 @@\n-orig\n+next\n".to_string(),
|
||||
revert: false,
|
||||
preflight: true,
|
||||
};
|
||||
let error = apply_git_patch(&request).expect_err("reject command-scoped filter");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
assert!(!configured_filter_ran(root));
|
||||
assert_eq!(read_file_normalized(&root.join("test.txt")), "orig\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_git_root_rejects_core_worktree_redirection() {
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
|
||||
@@ -14,6 +14,12 @@ pub(crate) enum ExactIndexPolicy {
|
||||
paths: Vec<String>,
|
||||
content_filter_paths: Vec<String>,
|
||||
},
|
||||
Flagged {
|
||||
paths: Vec<String>,
|
||||
content_filter_paths: Vec<String>,
|
||||
skip_worktree: BTreeSet<String>,
|
||||
assume_unchanged: BTreeSet<String>,
|
||||
},
|
||||
Refuse {
|
||||
stderr: String,
|
||||
},
|
||||
@@ -154,18 +160,11 @@ pub(crate) fn resolve_exact_index_policy(
|
||||
});
|
||||
}
|
||||
|
||||
let mut reasons = Vec::new();
|
||||
if !skipped.is_empty() {
|
||||
reasons.push(format!("skip-worktree path(s): {}", quote_paths(&skipped)));
|
||||
}
|
||||
if !assumed_unchanged.is_empty() {
|
||||
reasons.push(format!(
|
||||
"assume-unchanged path(s): {}",
|
||||
quote_paths(&assumed_unchanged)
|
||||
));
|
||||
}
|
||||
Ok(ExactIndexPolicy::Refuse {
|
||||
stderr: format!("refusing to stage {}", reasons.join("; ")),
|
||||
Ok(ExactIndexPolicy::Flagged {
|
||||
paths,
|
||||
content_filter_paths,
|
||||
skip_worktree: skipped,
|
||||
assume_unchanged: assumed_unchanged,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::process::Stdio;
|
||||
|
||||
use crate::exact_index_policy::ExactIndexPolicy;
|
||||
use crate::exact_index_policy::resolve_exact_index_policy;
|
||||
use crate::git_command::IsolatedGitStorage;
|
||||
use crate::guarded_config::GuardedGitConfig;
|
||||
use crate::patch_paths::validate_patch_path;
|
||||
|
||||
@@ -17,35 +18,124 @@ pub(crate) struct StagePathsResult {
|
||||
pub(crate) stderr: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum StagingProvenance {
|
||||
FromApply,
|
||||
Standalone,
|
||||
enum SparseCheckoutPolicy {
|
||||
Verified { excluded: BTreeSet<String> },
|
||||
Refuse { result: StagePathsResult },
|
||||
}
|
||||
|
||||
/// Stage only the literal paths supplied by a caller that has already applied
|
||||
/// the operation-specific containment and filesystem policy.
|
||||
///
|
||||
/// Unlike `git add`, `update-index` never treats a path that races from a leaf
|
||||
/// to a directory as a recursive request. Callers that require staging to
|
||||
/// succeed can inspect the returned status; the public forward helper retains
|
||||
/// its historical best-effort handling of a non-zero Git command.
|
||||
///
|
||||
/// This is not a transactional filesystem-confinement primitive. A concurrent
|
||||
/// strict-ancestor swap to a symlink or Windows junction can still redirect the
|
||||
/// bytes read for an already-confined index pathname. It cannot make this
|
||||
/// exact command recurse into, or create index entries for, descendant paths;
|
||||
/// the filter neutralizer also remains in force for the entire command.
|
||||
pub(crate) fn update_index_exact_paths_from_apply(
|
||||
pub(crate) struct PreparedReverseIndexUpdate {
|
||||
paths: Vec<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_index_exact_paths_for_reverse_apply(
|
||||
config: &mut GuardedGitConfig<'_>,
|
||||
paths: &[String],
|
||||
content_filter_paths: &[String],
|
||||
) -> io::Result<PreparedReverseIndexUpdate> {
|
||||
validate_exact_staging_inputs(paths, content_filter_paths)?;
|
||||
config.ensure_apply_filter_path_subset(content_filter_paths)?;
|
||||
if paths.is_empty() {
|
||||
return Ok(PreparedReverseIndexUpdate { paths: Vec::new() });
|
||||
}
|
||||
|
||||
let (paths, content_filter_paths, skip_worktree, assume_unchanged) =
|
||||
match resolve_exact_index_policy(config, paths, content_filter_paths)? {
|
||||
ExactIndexPolicy::Proceed {
|
||||
paths,
|
||||
content_filter_paths,
|
||||
} => (
|
||||
paths,
|
||||
content_filter_paths,
|
||||
BTreeSet::new(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
ExactIndexPolicy::Flagged {
|
||||
paths,
|
||||
content_filter_paths,
|
||||
skip_worktree,
|
||||
assume_unchanged,
|
||||
} => (paths, content_filter_paths, skip_worktree, assume_unchanged),
|
||||
ExactIndexPolicy::Refuse { stderr } => return Err(reverse_prepare_error(stderr)),
|
||||
};
|
||||
config.ensure_apply_filter_path_subset(&content_filter_paths)?;
|
||||
if !assume_unchanged.is_empty() {
|
||||
return Err(reverse_prepare_error(format!(
|
||||
"refusing to stage assume-unchanged path(s): {}",
|
||||
quote_paths(&assume_unchanged)
|
||||
)));
|
||||
}
|
||||
|
||||
let ignored = ignored_untracked_paths(config, &paths)?;
|
||||
let sparse_excluded = match sparse_checkout_policy(config, &paths)? {
|
||||
SparseCheckoutPolicy::Verified { excluded } => excluded,
|
||||
SparseCheckoutPolicy::Refuse { result } => {
|
||||
return Err(reverse_prepare_error(result.stderr));
|
||||
}
|
||||
};
|
||||
let non_sparse_skip_worktree = skip_worktree
|
||||
.difference(&sparse_excluded)
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
if !non_sparse_skip_worktree.is_empty() {
|
||||
return Err(reverse_prepare_error(format!(
|
||||
"refusing to stage skip-worktree path(s): {}",
|
||||
quote_paths(&non_sparse_skip_worktree)
|
||||
)));
|
||||
}
|
||||
let mut reasons = Vec::new();
|
||||
if !ignored.is_empty() {
|
||||
reasons.push(format!(
|
||||
"refusing to stage ignored untracked path(s): {}",
|
||||
quote_paths(&ignored)
|
||||
));
|
||||
}
|
||||
if !sparse_excluded.is_empty() {
|
||||
reasons.push(format!(
|
||||
"refusing to stage path(s) outside the sparse-checkout definition: {}",
|
||||
quote_paths(&sparse_excluded)
|
||||
));
|
||||
}
|
||||
if !reasons.is_empty() {
|
||||
return Err(reverse_prepare_error(reasons.join("; ")));
|
||||
}
|
||||
|
||||
// Attach the one Git-add filter snapshot while the plan is prepared.
|
||||
// Scratch and real executors below perform no policy/config reads.
|
||||
config.authorize_git_add_filter_paths(&content_filter_paths)?;
|
||||
Ok(PreparedReverseIndexUpdate { paths })
|
||||
}
|
||||
|
||||
pub(crate) fn execute_prepared_reverse_index_update(
|
||||
config: &GuardedGitConfig<'_>,
|
||||
prepared: &PreparedReverseIndexUpdate,
|
||||
scratch: Option<&IsolatedGitStorage>,
|
||||
) -> io::Result<StagePathsResult> {
|
||||
update_index_exact_paths_common(
|
||||
config,
|
||||
paths,
|
||||
content_filter_paths,
|
||||
StagingProvenance::FromApply,
|
||||
if prepared.paths.is_empty() {
|
||||
return Ok(StagePathsResult {
|
||||
exit_code: 0,
|
||||
stderr: String::new(),
|
||||
});
|
||||
}
|
||||
let mut command = config.update_index_literal_pathspecs_command()?;
|
||||
command
|
||||
.disable_optional_locks()
|
||||
.args(["--add", "--remove", "--"])
|
||||
.args(&prepared.paths);
|
||||
let output = if let Some(storage) = scratch {
|
||||
command.output_in_merge_scratch(storage)?
|
||||
} else {
|
||||
command.output()?
|
||||
};
|
||||
Ok(StagePathsResult {
|
||||
exit_code: output.status.code().unwrap_or(-1),
|
||||
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
fn reverse_prepare_error(message: String) -> io::Error {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
format!("failed to prepare reverse patch staging: {message}"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -54,20 +144,13 @@ pub(crate) fn update_index_exact_paths_standalone(
|
||||
paths: &[String],
|
||||
content_filter_paths: &[String],
|
||||
) -> io::Result<StagePathsResult> {
|
||||
update_index_exact_paths_common(
|
||||
config,
|
||||
paths,
|
||||
content_filter_paths,
|
||||
StagingProvenance::Standalone,
|
||||
)
|
||||
update_index_exact_paths(config, paths, content_filter_paths)
|
||||
}
|
||||
|
||||
fn update_index_exact_paths_common(
|
||||
config: &mut GuardedGitConfig<'_>,
|
||||
fn validate_exact_staging_inputs(
|
||||
paths: &[String],
|
||||
content_filter_paths: &[String],
|
||||
provenance: StagingProvenance,
|
||||
) -> io::Result<StagePathsResult> {
|
||||
) -> io::Result<()> {
|
||||
for path in paths {
|
||||
if path.as_bytes().contains(&0) {
|
||||
return Err(io::Error::new(
|
||||
@@ -87,9 +170,25 @@ fn update_index_exact_paths_common(
|
||||
"content-filter staging path is not in the exact staging set",
|
||||
));
|
||||
}
|
||||
if matches!(provenance, StagingProvenance::FromApply) {
|
||||
config.ensure_apply_filter_path_subset(content_filter_paths)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage only the literal paths supplied by a standalone caller that has
|
||||
/// already applied the operation-specific containment and filesystem policy.
|
||||
///
|
||||
/// Unlike `git add`, `update-index` never treats a path that races from a leaf
|
||||
/// to a directory as a recursive request. This is not a transactional
|
||||
/// filesystem-confinement primitive: a concurrent strict-ancestor swap to a
|
||||
/// symlink or Windows junction can still redirect the bytes read for an
|
||||
/// already-confined index pathname. It cannot make this exact command recurse
|
||||
/// into, or create index entries for, descendant paths; the filter neutralizer
|
||||
/// also remains in force for the entire command.
|
||||
fn update_index_exact_paths(
|
||||
config: &mut GuardedGitConfig<'_>,
|
||||
paths: &[String],
|
||||
content_filter_paths: &[String],
|
||||
) -> io::Result<StagePathsResult> {
|
||||
validate_exact_staging_inputs(paths, content_filter_paths)?;
|
||||
if paths.is_empty() {
|
||||
return Ok(StagePathsResult {
|
||||
exit_code: 0,
|
||||
@@ -97,12 +196,23 @@ fn update_index_exact_paths_common(
|
||||
});
|
||||
}
|
||||
|
||||
let (paths, content_filter_paths) =
|
||||
let (paths, content_filter_paths, skip_worktree, assume_unchanged) =
|
||||
match resolve_exact_index_policy(config, paths, content_filter_paths)? {
|
||||
ExactIndexPolicy::Proceed {
|
||||
paths,
|
||||
content_filter_paths,
|
||||
} => (paths, content_filter_paths),
|
||||
} => (
|
||||
paths,
|
||||
content_filter_paths,
|
||||
BTreeSet::new(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
ExactIndexPolicy::Flagged {
|
||||
paths,
|
||||
content_filter_paths,
|
||||
skip_worktree,
|
||||
assume_unchanged,
|
||||
} => (paths, content_filter_paths, skip_worktree, assume_unchanged),
|
||||
ExactIndexPolicy::Refuse { stderr } => {
|
||||
return Ok(StagePathsResult {
|
||||
exit_code: 1,
|
||||
@@ -110,23 +220,50 @@ fn update_index_exact_paths_common(
|
||||
});
|
||||
}
|
||||
};
|
||||
if matches!(provenance, StagingProvenance::FromApply) {
|
||||
config.ensure_apply_filter_path_subset(&content_filter_paths)?;
|
||||
if !skip_worktree.is_empty() || !assume_unchanged.is_empty() {
|
||||
let mut reasons = Vec::new();
|
||||
if !skip_worktree.is_empty() {
|
||||
reasons.push(format!(
|
||||
"skip-worktree path(s): {}",
|
||||
quote_paths(&skip_worktree)
|
||||
));
|
||||
}
|
||||
if !assume_unchanged.is_empty() {
|
||||
reasons.push(format!(
|
||||
"assume-unchanged path(s): {}",
|
||||
quote_paths(&assume_unchanged)
|
||||
));
|
||||
}
|
||||
return Ok(StagePathsResult {
|
||||
exit_code: 1,
|
||||
stderr: format!("refusing to stage {}", reasons.join("; ")),
|
||||
});
|
||||
}
|
||||
|
||||
let ignored = ignored_untracked_paths(config, &paths)?;
|
||||
let sparse_excluded = match sparse_checkout_policy(config, &paths)? {
|
||||
SparseCheckoutPolicy::Verified { excluded } => excluded,
|
||||
SparseCheckoutPolicy::Refuse { result } => return Ok(result),
|
||||
};
|
||||
let mut exclusion_reasons = Vec::new();
|
||||
if !ignored.is_empty() {
|
||||
exclusion_reasons.push(format!(
|
||||
"refusing to stage ignored untracked path(s): {}",
|
||||
quote_paths(&ignored)
|
||||
));
|
||||
}
|
||||
if !sparse_excluded.is_empty() {
|
||||
exclusion_reasons.push(format!(
|
||||
"refusing to stage path(s) outside the sparse-checkout definition: {}",
|
||||
quote_paths(&sparse_excluded)
|
||||
));
|
||||
}
|
||||
if !exclusion_reasons.is_empty() {
|
||||
return Ok(StagePathsResult {
|
||||
exit_code: 1,
|
||||
stderr: format!(
|
||||
"refusing to stage ignored untracked path(s): {}",
|
||||
quote_paths(&ignored)
|
||||
),
|
||||
stderr: exclusion_reasons.join("; "),
|
||||
});
|
||||
}
|
||||
if let Some(result) = sparse_checkout_policy(config, &paths)? {
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
config.authorize_git_add_filter_paths(&content_filter_paths)?;
|
||||
let mut command = config.update_index_literal_pathspecs_command()?;
|
||||
@@ -135,10 +272,9 @@ fn update_index_exact_paths_common(
|
||||
.args(["--add", "--remove", "--"])
|
||||
.args(&paths);
|
||||
let output = command.output()?;
|
||||
Ok(StagePathsResult {
|
||||
exit_code: output.status.code().unwrap_or(-1),
|
||||
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
})
|
||||
let exit_code = output.status.code().unwrap_or(-1);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
|
||||
Ok(StagePathsResult { exit_code, stderr })
|
||||
}
|
||||
|
||||
fn ignored_untracked_paths(
|
||||
@@ -191,9 +327,11 @@ fn ignored_untracked_paths(
|
||||
fn sparse_checkout_policy(
|
||||
config: &GuardedGitConfig<'_>,
|
||||
paths: &[String],
|
||||
) -> io::Result<Option<StagePathsResult>> {
|
||||
) -> io::Result<SparseCheckoutPolicy> {
|
||||
if !config.read_bool("core.sparseCheckout")?.unwrap_or(false) {
|
||||
return Ok(None);
|
||||
return Ok(SparseCheckoutPolicy::Verified {
|
||||
excluded: BTreeSet::new(),
|
||||
});
|
||||
}
|
||||
|
||||
// Do not let an older Git fall back to a PATH-resolved
|
||||
@@ -205,11 +343,14 @@ fn sparse_checkout_policy(
|
||||
&& std::str::from_utf8(&builtins.stdout)
|
||||
.is_ok_and(|output| output.lines().any(|command| command == "sparse-checkout"));
|
||||
if !sparse_checkout_is_builtin {
|
||||
return Ok(Some(StagePathsResult {
|
||||
exit_code: builtins.status.code().unwrap_or(-1).max(1),
|
||||
stderr: "unable to verify sparse-checkout staging policy with a built-in Git command"
|
||||
.to_string(),
|
||||
}));
|
||||
return Ok(SparseCheckoutPolicy::Refuse {
|
||||
result: StagePathsResult {
|
||||
exit_code: builtins.status.code().unwrap_or(-1).max(1),
|
||||
stderr:
|
||||
"unable to verify sparse-checkout staging policy with a built-in Git command"
|
||||
.to_string(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let input = nul_path_input(paths)?;
|
||||
@@ -220,13 +361,15 @@ fn sparse_checkout_policy(
|
||||
.stdin(Stdio::from(input));
|
||||
let output = command.output()?;
|
||||
if !output.status.success() {
|
||||
return Ok(Some(StagePathsResult {
|
||||
exit_code: output.status.code().unwrap_or(-1),
|
||||
stderr: format!(
|
||||
"unable to verify sparse-checkout staging policy: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
),
|
||||
}));
|
||||
return Ok(SparseCheckoutPolicy::Refuse {
|
||||
result: StagePathsResult {
|
||||
exit_code: output.status.code().unwrap_or(-1),
|
||||
stderr: format!(
|
||||
"unable to verify sparse-checkout staging policy: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
let included = parse_reported_paths(&output.stdout, paths, "sparse-checkout")?;
|
||||
let excluded = paths
|
||||
@@ -234,17 +377,7 @@ fn sparse_checkout_policy(
|
||||
.filter(|path| !included.contains(path.as_str()))
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
if excluded.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(StagePathsResult {
|
||||
exit_code: 1,
|
||||
stderr: format!(
|
||||
"refusing to stage path(s) outside the sparse-checkout definition: {}",
|
||||
quote_paths(&excluded)
|
||||
),
|
||||
}))
|
||||
}
|
||||
Ok(SparseCheckoutPolicy::Verified { excluded })
|
||||
}
|
||||
|
||||
fn nul_path_input(paths: &[String]) -> io::Result<std::fs::File> {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -48,6 +48,36 @@ async fn bounded_async_output_rejects_the_first_byte_over_limit() {
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn common_info_attributes_treat_a_missing_info_directory_as_empty_and_bound_bytes() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
assert_eq!(
|
||||
read_common_info_attributes_bounded_async(fixture.path(), 4)
|
||||
.await
|
||||
.expect("missing info directory is an empty source"),
|
||||
Vec::<u8>::new()
|
||||
);
|
||||
|
||||
std::fs::create_dir(fixture.path().join("info")).expect("create info directory");
|
||||
std::fs::write(fixture.path().join("info/attributes"), b"1234")
|
||||
.expect("write exact-limit attributes");
|
||||
assert_eq!(
|
||||
read_common_info_attributes_bounded_async(fixture.path(), 4)
|
||||
.await
|
||||
.expect("exact-limit attributes"),
|
||||
b"1234"
|
||||
);
|
||||
std::fs::write(fixture.path().join("info/attributes"), b"12345")
|
||||
.expect("write over-limit attributes");
|
||||
assert_eq!(
|
||||
read_common_info_attributes_bounded_async(fixture.path(), 4)
|
||||
.await
|
||||
.expect_err("over-limit attributes must fail")
|
||||
.kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn bounded_async_output_closes_an_unowned_piped_stdin() {
|
||||
@@ -346,6 +376,92 @@ fn git_config_path(path: &Path) -> String {
|
||||
format!("\"{}\"", path.replace('\\', "\\\\").replace('"', "\\\""))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolated_storage_uses_linked_worktree_shared_index_over_common_decoy() {
|
||||
let fixture = tempdir_for_native_git();
|
||||
let main = fixture.path().join("main");
|
||||
let linked = fixture.path().join("linked");
|
||||
std::fs::create_dir_all(&main).expect("create main worktree");
|
||||
run_git(&main, &["init", "-q"]);
|
||||
run_git(&main, &["config", "user.email", "codex@example.com"]);
|
||||
run_git(&main, &["config", "user.name", "Codex"]);
|
||||
std::fs::write(main.join("tracked.txt"), "tracked\n").expect("write tracked file");
|
||||
run_git(&main, &["add", "tracked.txt"]);
|
||||
run_git(&main, &["commit", "-m", "base"]);
|
||||
run_git(
|
||||
&main,
|
||||
&["worktree", "add", "-b", "linked", path_text(&linked)],
|
||||
);
|
||||
run_git(&linked, &["update-index", "--split-index"]);
|
||||
|
||||
let git_dir = PathBuf::from(run_git_stdout(
|
||||
&linked,
|
||||
&["rev-parse", "--absolute-git-dir"],
|
||||
));
|
||||
let common_dir = PathBuf::from(run_git_stdout(&linked, &["rev-parse", "--git-common-dir"]));
|
||||
let common_dir = if common_dir.is_absolute() {
|
||||
common_dir
|
||||
} else {
|
||||
linked.join(common_dir)
|
||||
};
|
||||
let common_dir = std::fs::canonicalize(common_dir).expect("canonical common directory");
|
||||
assert_ne!(
|
||||
git_dir, common_dir,
|
||||
"fixture must use distinct Git directories"
|
||||
);
|
||||
|
||||
let shared_name = std::fs::read_dir(&git_dir)
|
||||
.expect("read per-worktree Git directory")
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.file_name())
|
||||
.find(|name| {
|
||||
let Some(name) = name.to_str() else {
|
||||
return false;
|
||||
};
|
||||
let Some(suffix) = name.strip_prefix("sharedindex.") else {
|
||||
return false;
|
||||
};
|
||||
matches!(suffix.len(), 40 | 64)
|
||||
&& suffix
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
|
||||
})
|
||||
.expect("linked worktree split-index base");
|
||||
let active_shared = git_dir.join(&shared_name);
|
||||
let active_bytes = std::fs::read(&active_shared).expect("read active shared index");
|
||||
let common_decoy = common_dir.join(&shared_name);
|
||||
std::fs::write(&common_decoy, b"stale common shared-index decoy")
|
||||
.expect("write stale common decoy");
|
||||
|
||||
let runner = GitRunner::for_cwd(&linked).expect("runner");
|
||||
let storage = runner
|
||||
.create_isolated_git_storage()
|
||||
.expect("copy authoritative split index");
|
||||
assert_eq!(
|
||||
std::fs::read(storage.root.path().join(&shared_name)).expect("read scratch shared index"),
|
||||
active_bytes,
|
||||
"distinct common-directory decoy must not replace the active per-worktree base"
|
||||
);
|
||||
|
||||
let isolated = runner
|
||||
.create_isolated_common_dir()
|
||||
.expect("isolated common directory");
|
||||
let mut command = runner.command_for_cwd(&linked).expect("ls-files command");
|
||||
command.args(["ls-files", "--stage", "--", "tracked.txt"]);
|
||||
let output = runner
|
||||
.output_in_isolated_scratch(command, &isolated, &storage)
|
||||
.expect("read copied split index");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"copied split index must resolve its active base: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stdout).contains("\ttracked.txt"),
|
||||
"copied index did not retain tracked entry"
|
||||
);
|
||||
}
|
||||
|
||||
struct OverlappingRegisteredRoute {
|
||||
main: PathBuf,
|
||||
nested: PathBuf,
|
||||
@@ -493,6 +609,39 @@ fn config_source_authority_preserves_and_rejects_a_worktree_crossing_spelling()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn config_source_authority_rejects_direct_and_aliased_procfs_symlinks() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let fixture = tempdir_for_native_git();
|
||||
let root = fixture.path().join("repo");
|
||||
let alias = fixture.path().join("config-alias");
|
||||
std::fs::create_dir_all(&root).expect("create repository");
|
||||
run_git(&root, &["init", "-q"]);
|
||||
symlink("/proc/self/cwd", &alias).expect("create procfs alias");
|
||||
let authority = config_authority_for_root(&root);
|
||||
|
||||
for path in [
|
||||
PathBuf::from("/proc/self/cwd/config"),
|
||||
PathBuf::from("/proc/thread-self/cwd/config"),
|
||||
PathBuf::from("/proc/self/fd/1048575/config"),
|
||||
PathBuf::from("/proc/4294967295/cwd/config"),
|
||||
alias.join("config"),
|
||||
] {
|
||||
let error = authority
|
||||
.ensure_config_source_is_not_worktree_controlled(&path, "test config")
|
||||
.expect_err("process-relative config source");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
|
||||
assert!(error.to_string().contains("process-relative"), "{error}");
|
||||
assert!(error.to_string().contains("test config"), "{error}");
|
||||
assert!(
|
||||
error.to_string().contains(&path.display().to_string()),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_source_authority_allows_protected_metadata_and_unrelated_external_paths() {
|
||||
let fixture = tempdir_for_native_git();
|
||||
@@ -1456,6 +1605,238 @@ fn command_for_cwd_executes_from_a_canonical_windows_path() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_verbatim_git_path_conversion_is_narrow_and_non_lossy() {
|
||||
fn units(value: &str) -> Vec<u16> {
|
||||
value.encode_utf16().collect()
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&units(r"\\?\C:\Users\alice\repo")),
|
||||
WindowsGitPathUnits::Converted(units(r"C:\Users\alice\repo"))
|
||||
);
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&units(r"\\?\UNC\server\share\repo")),
|
||||
WindowsGitPathUnits::Converted(units(r"\\server\share\repo"))
|
||||
);
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&units(r"\\?\unc\server\share")),
|
||||
WindowsGitPathUnits::Converted(units(r"\\server\share"))
|
||||
);
|
||||
|
||||
for unchanged in [r"C:\Users\alice\repo", r"\\server\share\repo"] {
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&units(unchanged)),
|
||||
WindowsGitPathUnits::Unchanged,
|
||||
"unexpected conversion for {unchanged:?}"
|
||||
);
|
||||
}
|
||||
|
||||
for rejected in [
|
||||
r"\\.\C:\device-path",
|
||||
r"\??\C:\nt-path",
|
||||
r"//?/C:/forward-verbatim",
|
||||
r"//./C:/forward-device",
|
||||
r"\\?\C:relative",
|
||||
r"\\?\C:/forward-tail",
|
||||
r"\\?\GLOBALROOT\Device\HarddiskVolume1",
|
||||
r"\\?\Volume{12345678-1234-1234-1234-123456789abc}\repo",
|
||||
r"\\?\UNC\\share",
|
||||
r"\\?\UNC\server\",
|
||||
] {
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&units(rejected)),
|
||||
WindowsGitPathUnits::Rejected,
|
||||
"unexpected acceptance for {rejected:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let mut unpaired_surrogate = units(r"\\?\C:\repo\");
|
||||
unpaired_surrogate.push(0xD800);
|
||||
let mut expected = units(r"C:\repo\");
|
||||
expected.push(0xD800);
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&unpaired_surrogate),
|
||||
WindowsGitPathUnits::Converted(expected)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&units(r"\\?\C:\repo\😀")),
|
||||
WindowsGitPathUnits::Converted(units(r"C:\repo\😀"))
|
||||
);
|
||||
let mut unpaired_low_surrogate = units(r"\\?\C:\repo\");
|
||||
unpaired_low_surrogate.push(0xDC00);
|
||||
let mut expected = units(r"C:\repo\");
|
||||
expected.push(0xDC00);
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&unpaired_low_surrogate),
|
||||
WindowsGitPathUnits::Converted(expected)
|
||||
);
|
||||
|
||||
let mut nul = units(r"\\?\C:\repo\");
|
||||
nul.push(0);
|
||||
assert_eq!(
|
||||
classify_windows_git_path_units(&nul),
|
||||
WindowsGitPathUnits::Rejected
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn git_child_directory_simplifies_canonical_path_without_changing_identity() {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
|
||||
let directory = tempfile::tempdir().expect("fixture");
|
||||
let canonical = std::fs::canonicalize(directory.path()).expect("canonical fixture");
|
||||
let child = git_child_directory(&canonical, "test directory").expect("child spelling");
|
||||
assert_eq!(
|
||||
same_file::Handle::from_path(&canonical).expect("canonical identity"),
|
||||
same_file::Handle::from_path(child.as_path()).expect("child identity")
|
||||
);
|
||||
child.revalidate().expect("revalidate child spelling");
|
||||
let child_units = child
|
||||
.as_path()
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.collect::<Vec<_>>();
|
||||
assert!(!child_units.starts_with(&[b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16,]));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn git_child_directory_pins_git_paths_against_rename_and_replacement() {
|
||||
const WINDOWS_ERROR_SHARING_VIOLATION: i32 = 32;
|
||||
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let git_dir_path = fixture.path().join("git-dir");
|
||||
let common_dir_path = fixture.path().join("common-dir");
|
||||
std::fs::create_dir_all(&git_dir_path).expect("create Git directory");
|
||||
std::fs::create_dir_all(&common_dir_path).expect("create common directory");
|
||||
|
||||
let canonical_git_dir = std::fs::canonicalize(&git_dir_path).expect("canonical Git directory");
|
||||
let canonical_common_dir =
|
||||
std::fs::canonicalize(&common_dir_path).expect("canonical common directory");
|
||||
let git_dir =
|
||||
git_child_directory(&canonical_git_dir, "active Git directory").expect("pin Git directory");
|
||||
let common_dir = git_child_directory(&canonical_common_dir, "active Git common directory")
|
||||
.expect("pin common directory");
|
||||
assert_ne!(
|
||||
git_dir.as_path(),
|
||||
canonical_git_dir,
|
||||
"test must exercise the simplified Git-compatible spelling"
|
||||
);
|
||||
|
||||
let moved_git_dir = fixture.path().join("git-dir-moved");
|
||||
let error = std::fs::rename(&canonical_git_dir, &moved_git_dir)
|
||||
.expect_err("canonical Git directory pin must block rename");
|
||||
assert_eq!(
|
||||
error.raw_os_error(),
|
||||
Some(WINDOWS_ERROR_SHARING_VIOLATION),
|
||||
"{error}"
|
||||
);
|
||||
|
||||
let error = std::fs::remove_dir(&canonical_common_dir)
|
||||
.expect_err("common directory pin must block replacement");
|
||||
assert_eq!(
|
||||
error.raw_os_error(),
|
||||
Some(WINDOWS_ERROR_SHARING_VIOLATION),
|
||||
"{error}"
|
||||
);
|
||||
|
||||
let moved_child_spelling = fixture.path().join("git-dir-child-spelling-moved");
|
||||
let error = std::fs::rename(git_dir.as_path(), &moved_child_spelling)
|
||||
.expect_err("simplified Git-compatible spelling pin must block rename");
|
||||
assert_eq!(
|
||||
error.raw_os_error(),
|
||||
Some(WINDOWS_ERROR_SHARING_VIOLATION),
|
||||
"{error}"
|
||||
);
|
||||
|
||||
drop(git_dir);
|
||||
std::fs::rename(&canonical_git_dir, &moved_git_dir)
|
||||
.expect("released Git directory pins must allow rename");
|
||||
drop(common_dir);
|
||||
std::fs::remove_dir(&canonical_common_dir)
|
||||
.expect("released common directory pins must allow removal");
|
||||
std::fs::create_dir(&common_dir_path).expect("replace released common directory");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn isolated_child_final_validation_rejects_retargeted_spelling_before_spawn() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let repo = fixture.path().join("repo");
|
||||
let original = fixture.path().join("original");
|
||||
let attacker = fixture.path().join("attacker");
|
||||
let child_spelling = fixture.path().join("child-spelling");
|
||||
for directory in [&repo, &original, &attacker] {
|
||||
std::fs::create_dir_all(directory).expect("create directory");
|
||||
}
|
||||
run_git(&repo, &["init", "-q"]);
|
||||
create_junction(&child_spelling, &original);
|
||||
|
||||
let canonical = std::fs::canonicalize(&original).expect("canonical original");
|
||||
let child = GitChildDirectory::new(
|
||||
canonical,
|
||||
child_spelling.clone(),
|
||||
"test Git child directory",
|
||||
)
|
||||
.expect("initial child identity");
|
||||
// Keep identity snapshots that permit deletion, then release the guarded
|
||||
// handles so this test can still exercise the defense-in-depth final
|
||||
// revalidation after a child spelling has actually been retargeted.
|
||||
let canonical_identity =
|
||||
same_file::Handle::from_path(&child.canonical_path).expect("canonical identity snapshot");
|
||||
let child_identity =
|
||||
same_file::Handle::from_path(&child.child_path).expect("child identity snapshot");
|
||||
let GitChildDirectory {
|
||||
child_path,
|
||||
canonical_path,
|
||||
canonical_identity: pinned_canonical_identity,
|
||||
child_identity: pinned_child_identity,
|
||||
description,
|
||||
} = child;
|
||||
drop(pinned_canonical_identity);
|
||||
drop(pinned_child_identity);
|
||||
let child = GitChildDirectory {
|
||||
child_path,
|
||||
canonical_path,
|
||||
canonical_identity,
|
||||
child_identity,
|
||||
description,
|
||||
};
|
||||
let runner = GitRunner::for_cwd(&repo).expect("runner");
|
||||
let isolated = runner
|
||||
.create_isolated_common_dir()
|
||||
.expect("isolated common dir");
|
||||
let marker = fixture.path().join("child-ran.gitconfig");
|
||||
let mut command = runner.command_for_cwd(&repo).expect("marker command");
|
||||
command
|
||||
.args(["config", "--file"])
|
||||
.arg(&marker)
|
||||
.args(["codex.child-ran", "true"]);
|
||||
|
||||
std::fs::remove_dir(&child_spelling).expect("remove original junction");
|
||||
create_junction(&child_spelling, &attacker);
|
||||
|
||||
let error = runner
|
||||
.output_after_isolated_child_validation(
|
||||
&mut command.inner,
|
||||
&isolated,
|
||||
None,
|
||||
[&child, &child, &child, &child],
|
||||
)
|
||||
.expect_err("retargeted child spelling must fail closed");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("no longer identifies the original"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(!marker.exists(), "child command ran despite stale identity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gitdir_terminal_worktree_root_is_never_promoted_to_metadata() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
@@ -1673,6 +2054,79 @@ fn active_commondir_route_is_revalidated_before_every_child() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn active_worktree_identity_is_revalidated_before_every_child() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let root = fixture.path().join("repo");
|
||||
let moved_root = fixture.path().join("repo-moved");
|
||||
std::fs::create_dir_all(&root).expect("create repository");
|
||||
run_git(&root, &["init", "-q"]);
|
||||
let runner = GitRunner::for_cwd(&root).expect("runner for original repository");
|
||||
let sentinel = fixture.path().join("git-child-ran");
|
||||
let mut command = runner
|
||||
.command_for_cwd(&root)
|
||||
.expect("command for original repository");
|
||||
command
|
||||
.args(["config", "--file"])
|
||||
.arg(&sentinel)
|
||||
.args(["probe.value", "ran"]);
|
||||
|
||||
std::fs::rename(&root, &moved_root).expect("move original repository");
|
||||
std::fs::create_dir_all(&root).expect("create replacement repository");
|
||||
run_git(&root, &["init", "-q"]);
|
||||
assert!(moved_root.join(".git").is_dir());
|
||||
assert!(root.join(".git").is_dir());
|
||||
|
||||
let error = runner
|
||||
.output(command)
|
||||
.expect_err("same-path repository replacement must block Git child");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("guarded Git repository identity changed before Git launch"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
!sentinel.exists(),
|
||||
"Git child executed after same-path repository replacement"
|
||||
);
|
||||
assert_eq!(
|
||||
crate::status_guard::map_io_error("status", error),
|
||||
GitReadError::AuthorityRefused {
|
||||
operation: "status".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn active_worktree_identity_pins_repository_for_runner_lifetime() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let root = fixture.path().join("repo");
|
||||
let moved_root = fixture.path().join("repo-moved");
|
||||
std::fs::create_dir_all(&root).expect("create repository");
|
||||
run_git(&root, &["init", "-q"]);
|
||||
let runner = GitRunner::for_cwd(&root).expect("runner for original repository");
|
||||
|
||||
let error = std::fs::rename(&root, &moved_root)
|
||||
.expect_err("live repository identity handle must block replacement");
|
||||
const WINDOWS_ERROR_SHARING_VIOLATION: i32 = 32;
|
||||
assert_eq!(
|
||||
error.raw_os_error(),
|
||||
Some(WINDOWS_ERROR_SHARING_VIOLATION),
|
||||
"{error}"
|
||||
);
|
||||
assert!(root.join(".git").is_dir());
|
||||
assert!(!moved_root.exists());
|
||||
|
||||
drop(runner);
|
||||
std::fs::rename(&root, &moved_root).expect("released identity handle must allow move");
|
||||
assert!(!root.exists());
|
||||
assert!(moved_root.join(".git").is_dir());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn direct_external_separate_git_dir_absolute_and_relative_routes_execute_git() {
|
||||
|
||||
@@ -6,6 +6,84 @@ use std::path::Path;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES;
|
||||
|
||||
pub(crate) fn parse_git_boolean(value: &[u8]) -> Option<bool> {
|
||||
parse_git_boolean_with_minimum(value, i128::from(i32::MIN))
|
||||
}
|
||||
|
||||
/// Parse the Git boolean grammar while excluding numeric `INT_MIN`.
|
||||
///
|
||||
/// Older supported Git releases reject that one signed endpoint after unit
|
||||
/// expansion, so environment gates that must succeed across versions use this
|
||||
/// conservative variant. The accepted spellings otherwise share one parser.
|
||||
pub(crate) fn parse_git_boolean_symmetric_i32(value: &[u8]) -> Option<bool> {
|
||||
parse_git_boolean_with_minimum(value, -i128::from(i32::MAX))
|
||||
}
|
||||
|
||||
fn parse_git_boolean_with_minimum(value: &[u8], minimum: i128) -> Option<bool> {
|
||||
if value.eq_ignore_ascii_case(b"true")
|
||||
|| value.eq_ignore_ascii_case(b"yes")
|
||||
|| value.eq_ignore_ascii_case(b"on")
|
||||
{
|
||||
return Some(true);
|
||||
}
|
||||
if value.is_empty()
|
||||
|| value.eq_ignore_ascii_case(b"false")
|
||||
|| value.eq_ignore_ascii_case(b"no")
|
||||
|| value.eq_ignore_ascii_case(b"off")
|
||||
{
|
||||
return Some(false);
|
||||
}
|
||||
|
||||
// Git parses the remaining boolean spellings through `git_parse_int`: C
|
||||
// base-0 syntax, an optional binary-unit suffix, and signed `int` bounds.
|
||||
let value = std::str::from_utf8(value)
|
||||
.ok()?
|
||||
.trim_start_matches(|value: char| value.is_ascii_whitespace());
|
||||
let (negative, unsigned) = match value.as_bytes().first() {
|
||||
Some(b'-') => (true, &value[1..]),
|
||||
Some(b'+') => (false, &value[1..]),
|
||||
Some(_) => (false, value),
|
||||
None => return None,
|
||||
};
|
||||
let (base, unsigned) = if unsigned.starts_with("0x") || unsigned.starts_with("0X") {
|
||||
(16, &unsigned[2..])
|
||||
} else if unsigned.starts_with('0') {
|
||||
(8, unsigned)
|
||||
} else {
|
||||
(10, unsigned)
|
||||
};
|
||||
let digit_count = unsigned
|
||||
.bytes()
|
||||
.take_while(|byte| match base {
|
||||
8 => matches!(byte, b'0'..=b'7'),
|
||||
10 => byte.is_ascii_digit(),
|
||||
16 => byte.is_ascii_hexdigit(),
|
||||
_ => false,
|
||||
})
|
||||
.count();
|
||||
if digit_count == 0 {
|
||||
return None;
|
||||
}
|
||||
let (digits, suffix) = unsigned.split_at(digit_count);
|
||||
let factor = if suffix.is_empty() {
|
||||
1_i128
|
||||
} else if suffix.eq_ignore_ascii_case("k") {
|
||||
1024
|
||||
} else if suffix.eq_ignore_ascii_case("m") {
|
||||
1024 * 1024
|
||||
} else if suffix.eq_ignore_ascii_case("g") {
|
||||
1024 * 1024 * 1024
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let magnitude = i128::from_str_radix(digits, base).ok()?;
|
||||
let signed = if negative { -magnitude } else { magnitude };
|
||||
let value = signed.checked_mul(factor)?;
|
||||
(minimum..=i128::from(i32::MAX))
|
||||
.contains(&value)
|
||||
.then_some(value != 0)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum GitConfigScope {
|
||||
Unknown,
|
||||
@@ -24,6 +102,58 @@ pub(crate) struct GitConfigEntry {
|
||||
pub(crate) value: String,
|
||||
}
|
||||
|
||||
/// A value emitted by `git config --null --show-names`.
|
||||
///
|
||||
/// Git deliberately omits the key/value delimiter for an implicit Boolean
|
||||
/// (`key`) and retains it for an explicit empty value (`key =`). Keep that
|
||||
/// distinction available to bounded fixed policy readers without widening
|
||||
/// acceptance in ordinary config consumers.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum GitConfigValue {
|
||||
Implicit,
|
||||
Explicit(String),
|
||||
}
|
||||
|
||||
/// One ordered record from the fixed merge-policy config query.
|
||||
///
|
||||
/// This deliberately exposes typed implicit-vs-explicit presence only for
|
||||
/// merge policy. Existing executable- and path-valued config readers retain
|
||||
/// their strict rejection of implicit values.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct MergeConfigRecord {
|
||||
pub(crate) key: String,
|
||||
pub(crate) value: GitConfigValue,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
struct GitConfigValueEntry {
|
||||
scope: GitConfigScope,
|
||||
origin: GitConfigOrigin,
|
||||
key: String,
|
||||
value: GitConfigValue,
|
||||
}
|
||||
|
||||
impl TryFrom<GitConfigValueEntry> for GitConfigEntry {
|
||||
type Error = io::Error;
|
||||
|
||||
fn try_from(entry: GitConfigValueEntry) -> Result<Self, Self::Error> {
|
||||
let value = match entry.value {
|
||||
GitConfigValue::Explicit(value) => value,
|
||||
GitConfigValue::Implicit => {
|
||||
return Err(invalid_config_output(
|
||||
"Git config record has no key/value separator",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
scope: entry.scope,
|
||||
origin: entry.origin,
|
||||
key: entry.key,
|
||||
value,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum GitConfigOrigin {
|
||||
CommandLine,
|
||||
@@ -41,6 +171,13 @@ pub(crate) fn parse_effective_config(
|
||||
}
|
||||
|
||||
pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result<Vec<GitConfigEntry>> {
|
||||
parse_config_value_entries(output)?
|
||||
.into_iter()
|
||||
.map(GitConfigEntry::try_from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_config_value_entries(output: &[u8]) -> io::Result<Vec<GitConfigValueEntry>> {
|
||||
if output.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
@@ -57,19 +194,15 @@ pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result<Vec<GitConfigEnt
|
||||
let scope = parse_scope(record[0])?;
|
||||
let origin = parse_config_origin(record[1])?;
|
||||
let entry = parse_utf8_field(record[2], "config key/value")?;
|
||||
let Some((key, value)) = entry.split_once('\n') else {
|
||||
return Err(invalid_config_output(
|
||||
"Git config record has no key/value separator",
|
||||
));
|
||||
};
|
||||
let (key, value) = parse_config_value(entry);
|
||||
if key.is_empty() {
|
||||
return Err(invalid_config_output("empty Git config key"));
|
||||
}
|
||||
let entry = GitConfigEntry {
|
||||
let entry = GitConfigValueEntry {
|
||||
scope,
|
||||
origin,
|
||||
key: key.to_string(),
|
||||
value: value.to_string(),
|
||||
value,
|
||||
};
|
||||
entries.push(entry);
|
||||
}
|
||||
@@ -78,19 +211,17 @@ pub(crate) fn parse_config_entries(output: &[u8]) -> io::Result<Vec<GitConfigEnt
|
||||
|
||||
/// Parse the `--show-origin` form used by Git versions that predate
|
||||
/// `config --show-scope`. The record order still reflects effective config
|
||||
/// precedence, which is what helper selection relies on. Scope is retained as
|
||||
/// best-effort metadata only; command-line entries remain distinguishable.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn parse_effective_config_with_origins(
|
||||
output: &[u8],
|
||||
) -> io::Result<BTreeMap<String, GitConfigEntry>> {
|
||||
Ok(parse_config_entries_with_origins(output)?
|
||||
/// precedence, so duplicate include directives remain ordered. Scope is
|
||||
/// retained as best-effort metadata only; command-line entries remain
|
||||
/// distinguishable.
|
||||
pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result<Vec<GitConfigEntry>> {
|
||||
parse_config_value_entries_with_origins(output)?
|
||||
.into_iter()
|
||||
.map(|entry| (entry.key.clone(), entry))
|
||||
.collect())
|
||||
.map(GitConfigEntry::try_from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result<Vec<GitConfigEntry>> {
|
||||
fn parse_config_value_entries_with_origins(output: &[u8]) -> io::Result<Vec<GitConfigValueEntry>> {
|
||||
if output.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
@@ -106,11 +237,7 @@ pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result<Vec
|
||||
for record in fields.chunks_exact(2) {
|
||||
let origin = parse_config_origin(record[0])?;
|
||||
let entry = parse_utf8_field(record[1], "config key/value")?;
|
||||
let Some((key, value)) = entry.split_once('\n') else {
|
||||
return Err(invalid_config_output(
|
||||
"Git config record has no key/value separator",
|
||||
));
|
||||
};
|
||||
let (key, value) = parse_config_value(entry);
|
||||
if key.is_empty() {
|
||||
return Err(invalid_config_output("empty Git config key"));
|
||||
}
|
||||
@@ -121,16 +248,33 @@ pub(crate) fn parse_config_entries_with_origins(output: &[u8]) -> io::Result<Vec
|
||||
// emitted precedence order, not on this informational label.
|
||||
GitConfigScope::Local
|
||||
};
|
||||
entries.push(GitConfigEntry {
|
||||
entries.push(GitConfigValueEntry {
|
||||
scope,
|
||||
origin,
|
||||
key: key.to_string(),
|
||||
value: value.to_string(),
|
||||
value,
|
||||
});
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn parse_config_value(entry: &str) -> (&str, GitConfigValue) {
|
||||
match entry.split_once('\n') {
|
||||
Some((key, value)) => (key, GitConfigValue::Explicit(value.to_string())),
|
||||
None => (entry, GitConfigValue::Implicit),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn parse_effective_config_with_origins(
|
||||
output: &[u8],
|
||||
) -> io::Result<BTreeMap<String, GitConfigEntry>> {
|
||||
Ok(parse_config_entries_with_origins(output)?
|
||||
.into_iter()
|
||||
.map(|entry| (entry.key.clone(), entry))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(crate) fn read_effective_config_entries_with_fallback(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
@@ -149,6 +293,68 @@ pub(crate) fn read_effective_config_entries_with_fallback(
|
||||
)
|
||||
}
|
||||
|
||||
/// Read the one effective scalar whose implicit form has defined semantics.
|
||||
///
|
||||
/// Existing config readers continue to reject implicit values through
|
||||
/// [`GitConfigEntry::try_from`]. Keeping this query fixed prevents a caller
|
||||
/// from using the permissive parser for executable or path-valued config.
|
||||
pub(crate) fn read_effective_shared_repository_with_fallback(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<Option<GitConfigValue>> {
|
||||
const PATTERN: &str = r"^core\.sharedrepository$";
|
||||
let entries = read_config_value_entries_with_fallback(
|
||||
git,
|
||||
cwd,
|
||||
git_config_args,
|
||||
PATTERN,
|
||||
"shared repository",
|
||||
/*follow_includes*/ true,
|
||||
/*config_file*/ None,
|
||||
)?;
|
||||
let mut effective = None;
|
||||
for entry in entries {
|
||||
if entry.key != "core.sharedrepository" {
|
||||
return Err(invalid_config_output(
|
||||
"unexpected key in shared-repository config output",
|
||||
));
|
||||
}
|
||||
effective = Some(entry.value);
|
||||
}
|
||||
Ok(effective)
|
||||
}
|
||||
|
||||
/// Read the complete ordered merge-driver namespace inventory.
|
||||
///
|
||||
/// Git 2.54 creates a user-driver namespace for any key with a subsection,
|
||||
/// including an empty or dotted subsection. A top-level `merge.*` scalar has
|
||||
/// no subsection and is ignored, except for the separately handled
|
||||
/// `merge.default`. Keep the query fixed so permissive typed values cannot be
|
||||
/// requested for unrelated executable or path config.
|
||||
pub(crate) fn read_merge_config_records_with_fallback(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<Vec<MergeConfigRecord>> {
|
||||
const PATTERN: &str = r"^(merge\.default|merge\..*\..+)$";
|
||||
Ok(read_config_value_entries_with_fallback(
|
||||
git,
|
||||
cwd,
|
||||
git_config_args,
|
||||
PATTERN,
|
||||
"merge",
|
||||
/*follow_includes*/ true,
|
||||
/*config_file*/ None,
|
||||
)?
|
||||
.into_iter()
|
||||
.map(|entry| MergeConfigRecord {
|
||||
key: entry.key,
|
||||
value: entry.value,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(crate) fn read_config_entries_without_includes(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
@@ -197,6 +403,29 @@ fn read_config_entries_with_fallback(
|
||||
follow_includes: bool,
|
||||
config_file: Option<&Path>,
|
||||
) -> io::Result<Vec<GitConfigEntry>> {
|
||||
read_config_value_entries_with_fallback(
|
||||
git,
|
||||
cwd,
|
||||
git_config_args,
|
||||
pattern,
|
||||
probe,
|
||||
follow_includes,
|
||||
config_file,
|
||||
)?
|
||||
.into_iter()
|
||||
.map(GitConfigEntry::try_from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_config_value_entries_with_fallback(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
pattern: &str,
|
||||
probe: &str,
|
||||
follow_includes: bool,
|
||||
config_file: Option<&Path>,
|
||||
) -> io::Result<Vec<GitConfigValueEntry>> {
|
||||
let scoped = run_effective_config_query(
|
||||
git,
|
||||
cwd,
|
||||
@@ -211,7 +440,7 @@ fn read_config_entries_with_fallback(
|
||||
.code()
|
||||
.is_some_and(|code| code == 0 || code == 1)
|
||||
{
|
||||
return parse_config_entries(&scoped.stdout);
|
||||
return parse_config_value_entries(&scoped.stdout);
|
||||
}
|
||||
|
||||
let legacy = run_effective_config_query(
|
||||
@@ -234,7 +463,7 @@ fn read_config_entries_with_fallback(
|
||||
String::from_utf8_lossy(&legacy.stderr).trim()
|
||||
)));
|
||||
}
|
||||
parse_config_entries_with_origins(&legacy.stdout)
|
||||
parse_config_value_entries_with_origins(&legacy.stdout)
|
||||
}
|
||||
|
||||
async fn read_config_entries_with_fallback_async(
|
||||
|
||||
@@ -61,11 +61,16 @@ impl GitConfigEnvironmentSnapshot {
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if let Some(raw_count) = value_for(OsStr::new("GIT_CONFIG_COUNT")) {
|
||||
let count = raw_count
|
||||
let raw_count = raw_count
|
||||
.to_str()
|
||||
.ok_or_else(|| invalid_environment("non-UTF-8 GIT_CONFIG_COUNT"))?
|
||||
.parse::<usize>()
|
||||
.map_err(|_| invalid_environment("invalid GIT_CONFIG_COUNT"))?;
|
||||
.ok_or_else(|| invalid_environment("non-UTF-8 GIT_CONFIG_COUNT"))?;
|
||||
let count = if raw_count.is_empty() {
|
||||
0
|
||||
} else {
|
||||
raw_count
|
||||
.parse::<usize>()
|
||||
.map_err(|_| invalid_environment("invalid GIT_CONFIG_COUNT"))?
|
||||
};
|
||||
if count > MAX_CONFIG_ENVIRONMENT_ENTRIES {
|
||||
return Err(invalid_environment(
|
||||
"GIT_CONFIG_COUNT exceeds the supported safety bound",
|
||||
@@ -98,6 +103,7 @@ impl GitConfigEnvironmentSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub(crate) fn value(&self, name: &str) -> Option<&OsStr> {
|
||||
self.entries
|
||||
.iter()
|
||||
|
||||
@@ -40,10 +40,15 @@ fn snapshot_binds_present_empty_and_absent_fixed_and_indexed_values() {
|
||||
snapshot.value("GIT_CONFIG_PARAMETERS"),
|
||||
Some(OsStr::new("'safe.parameter'='present'"))
|
||||
);
|
||||
assert_eq!(snapshot.value("GIT_CONFIG_COUNT"), Some(OsStr::new("2")));
|
||||
assert_eq!(
|
||||
snapshot.value("GIT_CONFIG_KEY_0"),
|
||||
Some(OsStr::new("safe.one"))
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.value("GIT_CONFIG_VALUE_0"),
|
||||
Some(OsStr::new("present"))
|
||||
);
|
||||
assert_eq!(snapshot.value("GIT_CONFIG_VALUE_1"), None);
|
||||
|
||||
let mut command = Command::new("git");
|
||||
@@ -80,6 +85,39 @@ fn snapshot_rejects_malformed_or_unbounded_command_config_count() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_treats_empty_command_config_count_as_zero() {
|
||||
let values = BTreeMap::from([
|
||||
(OsString::from("GIT_CONFIG_COUNT"), OsString::from("")),
|
||||
(
|
||||
OsString::from("GIT_CONFIG_KEY_0"),
|
||||
OsString::from("untrusted.key"),
|
||||
),
|
||||
(
|
||||
OsString::from("GIT_CONFIG_VALUE_0"),
|
||||
OsString::from("untrusted-value"),
|
||||
),
|
||||
]);
|
||||
let snapshot = GitConfigEnvironmentSnapshot::capture_from(|name| values.get(name).cloned())
|
||||
.expect("capture empty count");
|
||||
|
||||
assert_eq!(snapshot.value("GIT_CONFIG_COUNT"), Some(OsStr::new("")));
|
||||
assert_eq!(snapshot.value("GIT_CONFIG_KEY_0"), None);
|
||||
assert_eq!(snapshot.value("GIT_CONFIG_VALUE_0"), None);
|
||||
|
||||
let mut command = Command::new("git");
|
||||
command.env("GIT_CONFIG_COUNT", "1");
|
||||
snapshot.apply_to(&mut command);
|
||||
let child_environment = command
|
||||
.get_envs()
|
||||
.map(|(name, value)| (name.to_owned(), value.map(OsStr::to_owned)))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
assert_eq!(
|
||||
child_environment.get(OsStr::new("GIT_CONFIG_COUNT")),
|
||||
Some(&Some(OsString::from("")))
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn snapshot_preserves_non_utf8_config_path_bytes() {
|
||||
|
||||
@@ -121,11 +121,7 @@ pub(crate) fn ensure_no_worktree_config_sources(
|
||||
git_root: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<()> {
|
||||
futures::executor::block_on(ensure_no_worktree_config_sources_impl(
|
||||
SourceExecution::Blocking(git),
|
||||
git_root,
|
||||
git_config_args,
|
||||
))
|
||||
ensure_no_worktree_config_sources_blocking_impl(git, git_root, git_config_args)
|
||||
}
|
||||
|
||||
/// Async counterpart to [`ensure_no_worktree_config_sources`] for bounded
|
||||
@@ -137,102 +133,88 @@ pub(crate) async fn ensure_no_worktree_config_sources_async(
|
||||
git_root: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<()> {
|
||||
ensure_no_worktree_config_sources_impl(SourceExecution::Async(git), git_root, git_config_args)
|
||||
.await
|
||||
ensure_no_worktree_config_sources_async_impl(git, git_root, git_config_args).await
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum SourceExecution<'a> {
|
||||
Blocking(&'a GitRunner),
|
||||
Async(&'a GitRunner),
|
||||
}
|
||||
|
||||
impl<'a> SourceExecution<'a> {
|
||||
fn git(self) -> &'a GitRunner {
|
||||
match self {
|
||||
Self::Blocking(git) | Self::Async(git) => git,
|
||||
}
|
||||
}
|
||||
|
||||
async fn selected_home_candidates(self, cwd: &Path) -> io::Result<Vec<std::path::PathBuf>> {
|
||||
match self {
|
||||
Self::Blocking(git) => selected_git_home_config_candidates(git, cwd),
|
||||
Self::Async(git) => selected_git_home_config_candidates_async(git, cwd).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn selected_prefix_candidate(self, cwd: &Path) -> io::Result<Option<std::path::PathBuf>> {
|
||||
match self {
|
||||
Self::Blocking(git) => selected_git_prefix_system_candidate(git, cwd),
|
||||
Self::Async(git) => selected_git_prefix_system_candidate_async(git, cwd).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_include_entries(
|
||||
self,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
config_file: Option<&Path>,
|
||||
) -> io::Result<Vec<crate::git_config::GitConfigEntry>> {
|
||||
match self {
|
||||
Self::Blocking(git) => read_config_entries_without_includes(
|
||||
git,
|
||||
cwd,
|
||||
git_config_args,
|
||||
INCLUDE_CONFIG_PATTERN,
|
||||
"include",
|
||||
config_file,
|
||||
),
|
||||
Self::Async(git) => {
|
||||
read_config_entries_without_includes_async(
|
||||
git,
|
||||
cwd,
|
||||
git_config_args,
|
||||
INCLUDE_CONFIG_PATTERN,
|
||||
"include",
|
||||
config_file,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_entries(
|
||||
self,
|
||||
git_root: &Path,
|
||||
entries: Vec<crate::git_config::GitConfigEntry>,
|
||||
depth: usize,
|
||||
pending: &mut Vec<(std::path::PathBuf, usize)>,
|
||||
budget: &mut IncludeGraphBudget,
|
||||
) -> io::Result<()> {
|
||||
match self {
|
||||
Self::Blocking(git) => {
|
||||
validate_include_entries(git, git_root, entries, depth, pending, budget)
|
||||
}
|
||||
Self::Async(git) => {
|
||||
validate_include_entries_async(git, git_root, entries, depth, pending, budget).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn default_system_candidates(
|
||||
self,
|
||||
cwd: &Path,
|
||||
) -> io::Result<Vec<(&'static str, std::path::PathBuf)>> {
|
||||
match self {
|
||||
Self::Blocking(git) => default_system_config_source_candidates(git, cwd),
|
||||
Self::Async(git) => default_system_config_source_candidates_async(git, cwd).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_no_worktree_config_sources_impl(
|
||||
execution: SourceExecution<'_>,
|
||||
fn ensure_no_worktree_config_sources_blocking_impl(
|
||||
git: &GitRunner,
|
||||
git_root: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<()> {
|
||||
let git_root = normalize_absolute_path(std::fs::canonicalize(git_root)?)?;
|
||||
|
||||
for (description, candidate) in legacy_primary_config_source_candidates(git)? {
|
||||
if !is_disabled_primary_config_path(&candidate) {
|
||||
reject_source(git, &git_root, &candidate, description)?;
|
||||
}
|
||||
}
|
||||
for candidate in selected_git_home_config_candidates(git, &git_root)? {
|
||||
reject_source(git, &git_root, &candidate, "selected Git HOME config")?;
|
||||
}
|
||||
if let Some(candidate) = selected_git_prefix_system_candidate(git, &git_root)? {
|
||||
reject_source(
|
||||
git,
|
||||
&git_root,
|
||||
&candidate,
|
||||
"selected Git prefix system config",
|
||||
)?;
|
||||
}
|
||||
let entries = read_config_entries_without_includes(
|
||||
git,
|
||||
&git_root,
|
||||
git_config_args,
|
||||
INCLUDE_CONFIG_PATTERN,
|
||||
"include",
|
||||
/*config_file*/ None,
|
||||
)?;
|
||||
#[cfg(test)]
|
||||
signal_blocking_no_includes_query_phase();
|
||||
let mut pending = Vec::new();
|
||||
let mut include_budget = IncludeGraphBudget::default();
|
||||
validate_include_entries(
|
||||
git,
|
||||
&git_root,
|
||||
entries,
|
||||
/*depth*/ 1,
|
||||
&mut pending,
|
||||
&mut include_budget,
|
||||
)?;
|
||||
let mut visited = BTreeSet::new();
|
||||
while let Some((config_path, depth)) = pending.pop() {
|
||||
if !pending_include_is_new(&config_path, depth, &mut visited)? {
|
||||
continue;
|
||||
}
|
||||
let entries = read_config_entries_without_includes(
|
||||
git,
|
||||
&git_root,
|
||||
&[],
|
||||
INCLUDE_CONFIG_PATTERN,
|
||||
"include",
|
||||
Some(&config_path),
|
||||
)?;
|
||||
validate_include_entries(
|
||||
git,
|
||||
&git_root,
|
||||
entries,
|
||||
depth + 1,
|
||||
&mut pending,
|
||||
&mut include_budget,
|
||||
)?;
|
||||
}
|
||||
for (description, candidate) in default_system_config_source_candidates(git, &git_root)? {
|
||||
if !is_disabled_primary_config_path(&candidate) {
|
||||
reject_source(git, &git_root, &candidate, description)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ensure_no_worktree_config_sources_async_impl(
|
||||
git: &GitRunner,
|
||||
git_root: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<()> {
|
||||
let git_root = normalize_absolute_path(std::fs::canonicalize(git_root)?)?;
|
||||
let git = execution.git();
|
||||
|
||||
// Environment, HOME, and XDG paths are attacker-controlled byte strings.
|
||||
// Classify their exact OsString spelling before selected Git can open or
|
||||
@@ -242,10 +224,10 @@ async fn ensure_no_worktree_config_sources_impl(
|
||||
reject_source(git, &git_root, &candidate, description)?;
|
||||
}
|
||||
}
|
||||
for candidate in execution.selected_home_candidates(&git_root).await? {
|
||||
for candidate in selected_git_home_config_candidates_async(git, &git_root).await? {
|
||||
reject_source(git, &git_root, &candidate, "selected Git HOME config")?;
|
||||
}
|
||||
if let Some(candidate) = execution.selected_prefix_candidate(&git_root).await? {
|
||||
if let Some(candidate) = selected_git_prefix_system_candidate_async(git, &git_root).await? {
|
||||
reject_source(
|
||||
git,
|
||||
&git_root,
|
||||
@@ -253,71 +235,59 @@ async fn ensure_no_worktree_config_sources_impl(
|
||||
"selected Git prefix system config",
|
||||
)?;
|
||||
}
|
||||
let entries = execution
|
||||
.read_include_entries(&git_root, git_config_args, /*config_file*/ None)
|
||||
.await?;
|
||||
#[cfg(test)]
|
||||
if matches!(execution, SourceExecution::Blocking(_)) {
|
||||
signal_blocking_no_includes_query_phase();
|
||||
}
|
||||
let entries = read_config_entries_without_includes_async(
|
||||
git,
|
||||
&git_root,
|
||||
git_config_args,
|
||||
INCLUDE_CONFIG_PATTERN,
|
||||
"include",
|
||||
/*config_file*/ None,
|
||||
)
|
||||
.await?;
|
||||
let mut pending = Vec::new();
|
||||
let mut include_budget = IncludeGraphBudget::default();
|
||||
execution
|
||||
.validate_entries(
|
||||
&git_root,
|
||||
entries,
|
||||
/*depth*/ 1,
|
||||
&mut pending,
|
||||
&mut include_budget,
|
||||
)
|
||||
.await?;
|
||||
validate_include_entries_async(
|
||||
git,
|
||||
&git_root,
|
||||
entries,
|
||||
/*depth*/ 1,
|
||||
&mut pending,
|
||||
&mut include_budget,
|
||||
)
|
||||
.await?;
|
||||
let mut visited = BTreeSet::new();
|
||||
while let Some((config_path, depth)) = pending.pop() {
|
||||
if depth > MAX_CONFIG_INCLUDE_DEPTH {
|
||||
return Err(path_safety::invalid_config_source(
|
||||
"Git config include depth exceeded",
|
||||
));
|
||||
}
|
||||
match std::fs::canonicalize(&config_path) {
|
||||
Ok(_) => {}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
|
||||
) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
if !visited.insert(config_path.clone()) {
|
||||
if !pending_include_is_new(&config_path, depth, &mut visited)? {
|
||||
continue;
|
||||
}
|
||||
if visited.len() > MAX_CONFIG_INCLUDE_FILES {
|
||||
return Err(path_safety::invalid_config_source(
|
||||
"too many Git config include files",
|
||||
));
|
||||
}
|
||||
// The same file reached through two spellings can resolve a relative
|
||||
// child include differently. Deduplicate only the exact source
|
||||
// spelling, not its canonical target.
|
||||
let entries = execution
|
||||
.read_include_entries(&git_root, &[], Some(&config_path))
|
||||
.await?;
|
||||
execution
|
||||
.validate_entries(
|
||||
&git_root,
|
||||
entries,
|
||||
depth + 1,
|
||||
&mut pending,
|
||||
&mut include_budget,
|
||||
)
|
||||
.await?;
|
||||
let entries = read_config_entries_without_includes_async(
|
||||
git,
|
||||
&git_root,
|
||||
&[],
|
||||
INCLUDE_CONFIG_PATTERN,
|
||||
"include",
|
||||
Some(&config_path),
|
||||
)
|
||||
.await?;
|
||||
validate_include_entries_async(
|
||||
git,
|
||||
&git_root,
|
||||
entries,
|
||||
depth + 1,
|
||||
&mut pending,
|
||||
&mut include_budget,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
// `git var` loads repository config before reporting modern default-system
|
||||
// paths. Delay that supplemental probe until the complete no-includes
|
||||
// source graph above has been classified.
|
||||
for (description, candidate) in execution.default_system_candidates(&git_root).await? {
|
||||
for (description, candidate) in
|
||||
default_system_config_source_candidates_async(git, &git_root).await?
|
||||
{
|
||||
if !is_disabled_primary_config_path(&candidate) {
|
||||
reject_source(git, &git_root, &candidate, description)?;
|
||||
}
|
||||
@@ -325,6 +295,39 @@ async fn ensure_no_worktree_config_sources_impl(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pending_include_is_new(
|
||||
config_path: &Path,
|
||||
depth: usize,
|
||||
visited: &mut BTreeSet<std::path::PathBuf>,
|
||||
) -> io::Result<bool> {
|
||||
if depth > MAX_CONFIG_INCLUDE_DEPTH {
|
||||
return Err(path_safety::invalid_config_source(
|
||||
"Git config include depth exceeded",
|
||||
));
|
||||
}
|
||||
match std::fs::canonicalize(config_path) {
|
||||
Ok(_) => {}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
|
||||
) =>
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
if !visited.insert(config_path.to_path_buf()) {
|
||||
return Ok(false);
|
||||
}
|
||||
if visited.len() > MAX_CONFIG_INCLUDE_FILES {
|
||||
return Err(path_safety::invalid_config_source(
|
||||
"too many Git config include files",
|
||||
));
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn reject_source(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::path_safety::git_var_path_from_bytes;
|
||||
use super::path_safety::invalid_config_source;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES;
|
||||
use crate::git_config::parse_git_boolean_symmetric_i32;
|
||||
|
||||
pub(super) fn default_system_config_source_candidates(
|
||||
git: &GitRunner,
|
||||
@@ -379,19 +380,8 @@ fn git_env_bool(git: &GitRunner, name: &str) -> io::Result<bool> {
|
||||
let value = value
|
||||
.to_str()
|
||||
.ok_or_else(|| invalid_config_source("non-UTF-8 Git boolean environment value"))?;
|
||||
match value.to_ascii_lowercase().as_str() {
|
||||
"1" | "true" | "yes" | "on" => Ok(true),
|
||||
"" | "0" | "false" | "no" | "off" => Ok(false),
|
||||
value => value
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
// Supported Git releases disagree on whether INT_MIN is a valid
|
||||
// numeric boolean. Accept only their shared symmetric range so a
|
||||
// value approved here cannot make the selected Git fail later.
|
||||
.filter(|value| (-i64::from(i32::MAX)..=i64::from(i32::MAX)).contains(value))
|
||||
.map(|value| value != 0)
|
||||
.ok_or_else(|| invalid_config_source("invalid Git boolean environment value")),
|
||||
}
|
||||
parse_git_boolean_symmetric_i32(value.as_bytes())
|
||||
.ok_or_else(|| invalid_config_source("invalid Git boolean environment value"))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -40,6 +40,7 @@ fn init_repo_at(root: &Path) {
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[allow(dead_code)]
|
||||
fn create_junction(path: &Path, target: &Path) {
|
||||
// Bazel's GNU Windows runner can surface temporary paths with `/`
|
||||
// separators. `mklink` treats those separators as option prefixes, so
|
||||
@@ -65,6 +66,17 @@ fn guard(root: &Path) -> io::Result<()> {
|
||||
ensure_no_worktree_config_sources(&git, root, &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_source_authorization_is_safe_inside_futures_local_pool() {
|
||||
let repo = init_repo();
|
||||
let git = GitRunner::for_cwd_io(repo.path()).expect("Git runner");
|
||||
|
||||
futures::executor::block_on(async {
|
||||
ensure_no_worktree_config_sources(&git, repo.path(), &[])
|
||||
.expect("blocking traversal must not enter a nested executor");
|
||||
});
|
||||
}
|
||||
|
||||
fn add_include(root: &Path, key: &str, value: &str) {
|
||||
run_success(root, &["config", "--add", key, value]);
|
||||
}
|
||||
@@ -74,7 +86,28 @@ fn assert_worktree_rejection(error: io::Error) {
|
||||
assert!(error.to_string().contains("worktree-controlled"), "{error}");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn assert_process_relative_include_rejection(error: io::Error) {
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("process-relative Git config include"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
fn run_isolated_source_test(test_name: &str, env: &[(&str, &OsStr)], removed: &[&str]) {
|
||||
let cwd = std::env::current_dir().expect("current directory");
|
||||
run_isolated_source_test_from(test_name, env, removed, &cwd);
|
||||
}
|
||||
|
||||
fn run_isolated_source_test_from(
|
||||
test_name: &str,
|
||||
env: &[(&str, &OsStr)],
|
||||
removed: &[&str],
|
||||
cwd: &Path,
|
||||
) {
|
||||
let mut command = std::process::Command::new(std::env::current_exe().expect("test binary"));
|
||||
crate::safe_git::isolate_git_command_environment(&mut command);
|
||||
command
|
||||
@@ -82,7 +115,8 @@ fn run_isolated_source_test(test_name: &str, env: &[(&str, &OsStr)], removed: &[
|
||||
.arg("--exact")
|
||||
.arg("--nocapture")
|
||||
.env("CODEX_GIT_CONFIG_SOURCE_CHILD", "1")
|
||||
.env("RUST_TEST_THREADS", "1");
|
||||
.env("RUST_TEST_THREADS", "1")
|
||||
.current_dir(cwd);
|
||||
for (name, value) in env {
|
||||
command.env(name, value);
|
||||
}
|
||||
@@ -98,6 +132,90 @@ fn run_isolated_source_test(test_name: &str, env: &[(&str, &OsStr)], removed: &[
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn rejects_process_relative_primary_config_sources_before_git_changes_cwd() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
const TEST_NAME: &str = "git_config_sources::tests::rejects_process_relative_primary_config_sources_before_git_changes_cwd";
|
||||
if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let root = fixture.path().join("repo");
|
||||
let external = fixture.path().join("external");
|
||||
let alias = fixture.path().join("config-alias");
|
||||
let chained_alias = fixture.path().join("chained-alias");
|
||||
init_repo_at(&root);
|
||||
std::fs::create_dir(&external).expect("external directory");
|
||||
std::fs::write(
|
||||
external.join("decoy.gitconfig"),
|
||||
"[safe]\nvalue = external\n",
|
||||
)
|
||||
.expect("external decoy");
|
||||
std::fs::write(
|
||||
external.join(".gitconfig"),
|
||||
"[safe]\nvalue = external-home\n",
|
||||
)
|
||||
.expect("external HOME config");
|
||||
for leaf in ["decoy.gitconfig", "missing-parent.gitconfig"] {
|
||||
std::fs::write(root.join(leaf), "[unsafe]\nhelper = worktree\n")
|
||||
.expect("worktree config");
|
||||
}
|
||||
symlink("/proc/self/cwd", &alias).expect("procfs alias");
|
||||
symlink("config-alias", &chained_alias).expect("chained procfs alias");
|
||||
|
||||
let candidates = [
|
||||
PathBuf::from("/proc/self/cwd/decoy.gitconfig"),
|
||||
PathBuf::from("/proc/thread-self/cwd/decoy.gitconfig"),
|
||||
PathBuf::from("/proc/self/cwd/missing-parent.gitconfig"),
|
||||
alias.join("decoy.gitconfig"),
|
||||
chained_alias.join("decoy.gitconfig"),
|
||||
];
|
||||
for candidate in &candidates {
|
||||
run_isolated_source_test_from(
|
||||
TEST_NAME,
|
||||
&[
|
||||
("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()),
|
||||
("GIT_CONFIG_GLOBAL", candidate.as_os_str()),
|
||||
("GIT_CONFIG_NOSYSTEM", OsStr::new("1")),
|
||||
],
|
||||
&["GIT_CONFIG_SYSTEM"],
|
||||
&external,
|
||||
);
|
||||
}
|
||||
run_isolated_source_test_from(
|
||||
TEST_NAME,
|
||||
&[
|
||||
("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()),
|
||||
("GIT_CONFIG_GLOBAL", OsStr::new("")),
|
||||
(
|
||||
"GIT_CONFIG_SYSTEM",
|
||||
OsStr::new("/proc/self/cwd/decoy.gitconfig"),
|
||||
),
|
||||
],
|
||||
&["GIT_CONFIG_NOSYSTEM"],
|
||||
&external,
|
||||
);
|
||||
run_isolated_source_test_from(
|
||||
TEST_NAME,
|
||||
&[
|
||||
("CODEX_GIT_CONFIG_SOURCE_ROOT", root.as_os_str()),
|
||||
("HOME", OsStr::new("/proc/self/cwd")),
|
||||
("GIT_CONFIG_NOSYSTEM", OsStr::new("1")),
|
||||
],
|
||||
&["GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "XDG_CONFIG_HOME"],
|
||||
&external,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let root = PathBuf::from(
|
||||
std::env::var_os("CODEX_GIT_CONFIG_SOURCE_ROOT").expect("fixture repository root"),
|
||||
);
|
||||
let error = guard(&root).expect_err("process-relative primary config source");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
|
||||
assert!(error.to_string().contains("process-relative"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_protected_metadata_and_external_config_sources() {
|
||||
let repo = init_repo();
|
||||
@@ -402,9 +520,8 @@ fn rejects_worktree_fifo_primary_source_without_opening_it() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_config_nosystem_accepts_cross_version_boolean_values() {
|
||||
const TEST_NAME: &str =
|
||||
"git_config_sources::tests::git_config_nosystem_accepts_cross_version_boolean_values";
|
||||
fn git_config_nosystem_uses_the_shared_parser_with_a_cross_version_numeric_subset() {
|
||||
const TEST_NAME: &str = "git_config_sources::tests::git_config_nosystem_uses_the_shared_parser_with_a_cross_version_numeric_subset";
|
||||
if std::env::var_os("CODEX_GIT_CONFIG_SOURCE_CHILD").is_none() {
|
||||
let repo = init_repo();
|
||||
let unsafe_system = repo.path().join("system.gitconfig");
|
||||
@@ -415,6 +532,11 @@ fn git_config_nosystem_accepts_cross_version_boolean_values() {
|
||||
("-1", "ignored"),
|
||||
("01", "ignored"),
|
||||
("+1", "ignored"),
|
||||
("0x1", "ignored"),
|
||||
("010", "ignored"),
|
||||
("1k", "ignored"),
|
||||
("-1g", "ignored"),
|
||||
(" 1", "ignored"),
|
||||
("2147483647", "ignored"),
|
||||
("-2147483647", "ignored"),
|
||||
("true", "ignored"),
|
||||
@@ -427,9 +549,17 @@ fn git_config_nosystem_accepts_cross_version_boolean_values() {
|
||||
("no", "rejected"),
|
||||
("off", "rejected"),
|
||||
("not-a-bool", "invalid"),
|
||||
("08", "invalid"),
|
||||
("2147483648", "invalid"),
|
||||
("-2147483648", "invalid"),
|
||||
("-0x80000000", "invalid"),
|
||||
("-020000000000", "invalid"),
|
||||
("-2097152k", "invalid"),
|
||||
("-2048m", "invalid"),
|
||||
("-2g", "invalid"),
|
||||
(" -2G", "invalid"),
|
||||
("-2147483649", "invalid"),
|
||||
("2g", "invalid"),
|
||||
] {
|
||||
run_isolated_source_test(
|
||||
TEST_NAME,
|
||||
@@ -838,6 +968,73 @@ async fn blocking_and_async_source_authorization_share_the_same_include_policy()
|
||||
assert_eq!(asynchronous.kind(), blocking.kind());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn rejects_process_relative_procfs_includes_across_the_include_graph() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
for (key, value, leaf) in [
|
||||
(
|
||||
"include.path",
|
||||
"/proc/self/cwd/direct.gitconfig",
|
||||
"direct.gitconfig",
|
||||
),
|
||||
(
|
||||
"includeIf.gitdir:/definitely/not/this/repository/**.path",
|
||||
"/proc/thread-self/cwd/conditional.gitconfig",
|
||||
"conditional.gitconfig",
|
||||
),
|
||||
] {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join(leaf), "[unsafe]\nhelper = worktree\n")
|
||||
.expect("write process-relative include target");
|
||||
add_include(root, key, value);
|
||||
assert_process_relative_include_rejection(
|
||||
guard(root).expect_err("process-relative repository include"),
|
||||
);
|
||||
}
|
||||
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(
|
||||
root.join("command.gitconfig"),
|
||||
"[unsafe]\nhelper = worktree\n",
|
||||
)
|
||||
.expect("write command include target");
|
||||
let git = GitRunner::for_cwd_io(root).expect("Git runner");
|
||||
let args = vec![
|
||||
"-c".to_string(),
|
||||
"include.path=/proc/self/cwd/command.gitconfig".to_string(),
|
||||
];
|
||||
assert_process_relative_include_rejection(
|
||||
ensure_no_worktree_config_sources(&git, root, &args)
|
||||
.expect_err("process-relative command-scoped include"),
|
||||
);
|
||||
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(
|
||||
root.join("nested.gitconfig"),
|
||||
"[unsafe]\nhelper = worktree\n",
|
||||
)
|
||||
.expect("write nested include target");
|
||||
let external = tempfile::tempdir().expect("external include directory");
|
||||
let parent = external.path().join("parent.gitconfig");
|
||||
let alias = external.path().join("procfs-alias");
|
||||
symlink("/proc/self/cwd", &alias).expect("create procfs alias");
|
||||
std::fs::write(&parent, "[include]\npath = procfs-alias/nested.gitconfig\n")
|
||||
.expect("write external parent config");
|
||||
add_include(
|
||||
root,
|
||||
"include.path",
|
||||
parent.to_str().expect("UTF-8 parent config path"),
|
||||
);
|
||||
assert_process_relative_include_rejection(
|
||||
guard(root).expect_err("nested aliased process-relative include"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_every_duplicate_and_nested_include_target() {
|
||||
for unsafe_first in [true, false] {
|
||||
|
||||
@@ -28,6 +28,256 @@ command\0command line:\0merge.Name.driver\nhelper %A %B\0";
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_config_parser_distinguishes_implicit_from_explicit_empty() {
|
||||
let scoped = b"local\0file:/repo/.git/config\0core.sharedrepository\0\
|
||||
local\0file:/repo/.git/config\0core.other\n\0";
|
||||
let parsed = parse_config_value_entries(scoped).expect("parse typed scoped config");
|
||||
assert_eq!(parsed[0].key, "core.sharedrepository");
|
||||
assert_eq!(parsed[0].value, GitConfigValue::Implicit);
|
||||
assert_eq!(parsed[1].key, "core.other");
|
||||
assert_eq!(parsed[1].value, GitConfigValue::Explicit(String::new()));
|
||||
|
||||
let legacy = b"file:/repo/.git/config\0core.sharedrepository\0\
|
||||
file:/repo/.git/config\0core.other\n\0";
|
||||
let parsed =
|
||||
parse_config_value_entries_with_origins(legacy).expect("parse typed legacy config");
|
||||
assert_eq!(parsed[0].value, GitConfigValue::Implicit);
|
||||
assert_eq!(parsed[1].value, GitConfigValue::Explicit(String::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_config_parser_still_rejects_implicit_values() {
|
||||
for output in [
|
||||
b"local\0file:/repo/.git/config\0filter.demo.clean\0".as_slice(),
|
||||
b"file:/repo/.git/config\0include.path\0".as_slice(),
|
||||
] {
|
||||
let result = if output.starts_with(b"local\0") {
|
||||
parse_config_entries(output)
|
||||
} else {
|
||||
parse_config_entries_with_origins(output)
|
||||
};
|
||||
assert!(result.is_err(), "implicit value unexpectedly accepted");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_config_parser_splits_only_the_first_value_delimiter() {
|
||||
let output = b"local\0file:/repo/.git/config\0core.demo\nfirst\nsecond\0";
|
||||
let parsed = parse_config_value_entries(output).expect("parse multiline explicit value");
|
||||
assert_eq!(
|
||||
parsed[0].value,
|
||||
GitConfigValue::Explicit("first\nsecond".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_merge_config_reader_preserves_ordered_typed_records() {
|
||||
use std::io::Write as _;
|
||||
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
let mut init = std::process::Command::new("git");
|
||||
crate::safe_git::isolate_git_command_environment(&mut init);
|
||||
let output = init
|
||||
.args(["init", "-q"])
|
||||
.current_dir(root)
|
||||
.output()
|
||||
.expect("initialize repo");
|
||||
assert!(output.status.success());
|
||||
let mut config = std::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(root.join(".git/config"))
|
||||
.expect("open local config");
|
||||
write!(
|
||||
config,
|
||||
"\n[merge \"codex-reader\"]\n\tname\n\tname = later\n\tarbitrary\n\
|
||||
[merge \"codex.reader.dotted\"]\n\tunknown\n\
|
||||
[merge]\n\tcodexscalar = ignored\n"
|
||||
)
|
||||
.expect("append merge config records");
|
||||
drop(config);
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("runner");
|
||||
let all_records = read_merge_config_records_with_fallback(&git, root, &[])
|
||||
.expect("read fixed merge config records");
|
||||
assert!(
|
||||
all_records
|
||||
.iter()
|
||||
.all(|record| record.key != "merge.codexscalar"),
|
||||
"top-level merge scalar must not be returned as a user namespace"
|
||||
);
|
||||
let records = all_records
|
||||
.into_iter()
|
||||
.filter(|record| {
|
||||
record.key.starts_with("merge.codex-reader.")
|
||||
|| record.key.starts_with("merge.codex.reader.dotted.")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
records,
|
||||
vec![
|
||||
MergeConfigRecord {
|
||||
key: "merge.codex-reader.name".to_string(),
|
||||
value: GitConfigValue::Implicit,
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge.codex-reader.name".to_string(),
|
||||
value: GitConfigValue::Explicit("later".to_string()),
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge.codex-reader.arbitrary".to_string(),
|
||||
value: GitConfigValue::Implicit,
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge.codex.reader.dotted.unknown".to_string(),
|
||||
value: GitConfigValue::Implicit,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_shared_repository_reader_preserves_implicit_and_empty_values() {
|
||||
use std::io::Write as _;
|
||||
|
||||
for (line, expected) in [
|
||||
("\tsharedRepository\n", GitConfigValue::Implicit),
|
||||
(
|
||||
"\tsharedRepository =\n",
|
||||
GitConfigValue::Explicit(String::new()),
|
||||
),
|
||||
] {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
let mut init = std::process::Command::new("git");
|
||||
crate::safe_git::isolate_git_command_environment(&mut init);
|
||||
let initialized = init
|
||||
.args(["init", "-q"])
|
||||
.current_dir(root)
|
||||
.output()
|
||||
.expect("initialize repo");
|
||||
assert!(
|
||||
initialized.status.success(),
|
||||
"initialize repo: {}",
|
||||
String::from_utf8_lossy(&initialized.stderr)
|
||||
);
|
||||
let mut config = std::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(root.join(".git/config"))
|
||||
.expect("open local config");
|
||||
write!(config, "\n[core]\n{line}").expect("append shared-repository value");
|
||||
drop(config);
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("Git runner");
|
||||
assert_eq!(
|
||||
read_effective_shared_repository_with_fallback(&git, root, &[])
|
||||
.expect("read shared repository"),
|
||||
Some(expected),
|
||||
"config line {line:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_boolean_accepts_native_git_spellings() {
|
||||
for (value, expected) in [
|
||||
(b"true".as_slice(), true),
|
||||
(b"TRUE".as_slice(), true),
|
||||
(b"yes".as_slice(), true),
|
||||
(b"On".as_slice(), true),
|
||||
(b"1".as_slice(), true),
|
||||
(b"2".as_slice(), true),
|
||||
(b"-1".as_slice(), true),
|
||||
(b"+1".as_slice(), true),
|
||||
(b"01".as_slice(), true),
|
||||
(b"0x1".as_slice(), true),
|
||||
(b"0Xf".as_slice(), true),
|
||||
(b"010".as_slice(), true),
|
||||
(b"1k".as_slice(), true),
|
||||
(b"1M".as_slice(), true),
|
||||
(b"1g".as_slice(), true),
|
||||
(b" 1".as_slice(), true),
|
||||
(b"2147483647".as_slice(), true),
|
||||
(b"-2147483648".as_slice(), true),
|
||||
(b"-2g".as_slice(), true),
|
||||
(b"false".as_slice(), false),
|
||||
(b"FALSE".as_slice(), false),
|
||||
(b"no".as_slice(), false),
|
||||
(b"Off".as_slice(), false),
|
||||
(b"".as_slice(), false),
|
||||
(b"0".as_slice(), false),
|
||||
(b"-0".as_slice(), false),
|
||||
(b"+0".as_slice(), false),
|
||||
(b"00".as_slice(), false),
|
||||
(b"0x0".as_slice(), false),
|
||||
(b"0k".as_slice(), false),
|
||||
] {
|
||||
assert_eq!(parse_git_boolean(value), Some(expected), "value {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_boolean_rejects_values_native_git_rejects() {
|
||||
for value in [
|
||||
b"08".as_slice(),
|
||||
b"-08".as_slice(),
|
||||
b"2147483648".as_slice(),
|
||||
b"-2147483649".as_slice(),
|
||||
b"9223372036854775807".as_slice(),
|
||||
b"2g".as_slice(),
|
||||
b"-3g".as_slice(),
|
||||
b"0x".as_slice(),
|
||||
b"0b1".as_slice(),
|
||||
b"1kb".as_slice(),
|
||||
b"1foo".as_slice(),
|
||||
b"1_0".as_slice(),
|
||||
b"1 ".as_slice(),
|
||||
b" ".as_slice(),
|
||||
b"+".as_slice(),
|
||||
b"-".as_slice(),
|
||||
b"not-a-bool".as_slice(),
|
||||
b"\xff".as_slice(),
|
||||
] {
|
||||
assert_eq!(parse_git_boolean(value), None, "value {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symmetric_git_boolean_parser_excludes_only_int_min_spellings() {
|
||||
for value in [
|
||||
b"-2147483648".as_slice(),
|
||||
b"-0x80000000".as_slice(),
|
||||
b"-020000000000".as_slice(),
|
||||
b"-2097152k".as_slice(),
|
||||
b"-2048m".as_slice(),
|
||||
b"-2g".as_slice(),
|
||||
b" -2G".as_slice(),
|
||||
] {
|
||||
assert_eq!(parse_git_boolean(value), Some(true), "value {value:?}");
|
||||
assert_eq!(
|
||||
parse_git_boolean_symmetric_i32(value),
|
||||
None,
|
||||
"value {value:?}"
|
||||
);
|
||||
}
|
||||
|
||||
for value in [
|
||||
b"0x1".as_slice(),
|
||||
b"010".as_slice(),
|
||||
b"1k".as_slice(),
|
||||
b"-1g".as_slice(),
|
||||
b" 1".as_slice(),
|
||||
b"-2147483647".as_slice(),
|
||||
] {
|
||||
assert_eq!(
|
||||
parse_git_boolean_symmetric_i32(value),
|
||||
parse_git_boolean(value),
|
||||
"value {value:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_parsers_preserve_duplicate_include_directives_in_order() {
|
||||
let scoped = b"local\0file:.git/config\0include.path\n../unsafe.gitconfig\0\
|
||||
@@ -80,7 +330,7 @@ fn rejects_malformed_config_records() {
|
||||
b"global\0\0key\nvalue\0".as_slice(),
|
||||
b"global\0file:/tmp/config\0\nvalue\0".as_slice(),
|
||||
] {
|
||||
assert!(parse_effective_config(output).is_err(), "{output:?}");
|
||||
assert!(parse_config_entries(output).is_err(), "{output:?}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -2,11 +2,10 @@ use super::*;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::safe_git::isolate_git_command_environment;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::ffi::OsStr;
|
||||
|
||||
fn run_git(cwd: &Path, args: &[&str]) {
|
||||
let mut command = std::process::Command::new("git");
|
||||
isolate_git_command_environment(&mut command);
|
||||
let output = command.current_dir(cwd).args(args).output().expect("Git");
|
||||
let output = git_output(cwd, args);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"git {args:?}: {}",
|
||||
@@ -14,6 +13,210 @@ fn run_git(cwd: &Path, args: &[&str]) {
|
||||
);
|
||||
}
|
||||
|
||||
fn git_output(cwd: &Path, args: &[&str]) -> std::process::Output {
|
||||
let mut command = std::process::Command::new("git");
|
||||
isolate_git_command_environment(&mut command);
|
||||
command.current_dir(cwd).args(args).output().expect("Git")
|
||||
}
|
||||
|
||||
fn config_file_value(_cwd: &Path, config: &Path, key: &str) -> Option<String> {
|
||||
let mut command = std::process::Command::new("git");
|
||||
isolate_git_command_environment(&mut command);
|
||||
let output = command
|
||||
.current_dir(config.parent().expect("config parent"))
|
||||
.args(["config", "--file"])
|
||||
.arg(config)
|
||||
.args(["--get", key])
|
||||
.output()
|
||||
.expect("read config file");
|
||||
if output.status.code() == Some(1) {
|
||||
return None;
|
||||
}
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"read {key:?}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
fn run_isolated_overlay_test(test_name: &str, env: &[(&str, &OsStr)]) {
|
||||
let mut command = std::process::Command::new(std::env::current_exe().expect("test binary"));
|
||||
isolate_git_command_environment(&mut command);
|
||||
command
|
||||
.arg(test_name)
|
||||
.arg("--exact")
|
||||
.arg("--nocapture")
|
||||
.env("CODEX_GIT_UTILS_MERGE_OVERLAY_CHILD", "1")
|
||||
.env("RUST_TEST_THREADS", "1");
|
||||
for (name, value) in env {
|
||||
command.env(name, value);
|
||||
}
|
||||
let output = command.output().expect("run isolated overlay test");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"isolated test {test_name} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
fn unspecified_safe_attributes() -> SafeApplyAttributes {
|
||||
SafeApplyAttributes {
|
||||
whitespace: ProjectedAttribute::Unspecified,
|
||||
conflict_marker_size: ProjectedAttribute::Unspecified,
|
||||
text: ProjectedAttribute::Unspecified,
|
||||
crlf: ProjectedAttribute::Unspecified,
|
||||
eol: ProjectedAttribute::Unspecified,
|
||||
ident: ProjectedAttribute::Unspecified,
|
||||
working_tree_encoding: ProjectedAttribute::Unspecified,
|
||||
_filter: ProjectedAttribute::Unspecified,
|
||||
}
|
||||
}
|
||||
|
||||
fn frozen_path(merge: BuiltinMergeDriver) -> FrozenPathApplyAttributes {
|
||||
FrozenPathApplyAttributes {
|
||||
merge: MergeSelection::Builtin(merge),
|
||||
safe: unspecified_safe_attributes(),
|
||||
}
|
||||
}
|
||||
|
||||
fn complete_attribute_output(path: &str, overrides: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let names = [
|
||||
"merge",
|
||||
"whitespace",
|
||||
"conflict-marker-size",
|
||||
"text",
|
||||
"crlf",
|
||||
"eol",
|
||||
"ident",
|
||||
"filter",
|
||||
"working-tree-encoding",
|
||||
];
|
||||
let mut output = Vec::new();
|
||||
for name in names {
|
||||
let value = overrides
|
||||
.iter()
|
||||
.find_map(|(candidate, value)| (*candidate == name).then_some(*value))
|
||||
.unwrap_or(b"unspecified");
|
||||
output.extend_from_slice(path.as_bytes());
|
||||
output.push(0);
|
||||
output.extend_from_slice(name.as_bytes());
|
||||
output.push(0);
|
||||
output.extend_from_slice(value);
|
||||
output.push(0);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_stage_snapshot_parser_enforces_canonical_framing_and_format() {
|
||||
let paths = ["file.txt".to_string()];
|
||||
let sha1 = "1".repeat(40);
|
||||
let sha256 = "a".repeat(64);
|
||||
let sha1_record = format!("100644 {sha1} 0\tfile.txt\0");
|
||||
let sha256_record = format!("100644 {sha256} 0\tfile.txt\0");
|
||||
|
||||
assert_eq!(
|
||||
parse_index_stage_snapshot(&[], &paths, IndexObjectFormat::Sha1).expect("empty snapshot"),
|
||||
IndexStageSnapshot::new()
|
||||
);
|
||||
assert!(
|
||||
parse_index_stage_snapshot(sha1_record.as_bytes(), &paths, IndexObjectFormat::Sha1).is_ok()
|
||||
);
|
||||
assert!(
|
||||
parse_index_stage_snapshot(sha256_record.as_bytes(), &paths, IndexObjectFormat::Sha256)
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
parse_index_stage_snapshot(sha1_record.as_bytes(), &paths, IndexObjectFormat::Sha256)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
parse_index_stage_snapshot(sha256_record.as_bytes(), &paths, IndexObjectFormat::Sha1)
|
||||
.is_err()
|
||||
);
|
||||
let tab_path = ["tab\tpath.txt".to_string()];
|
||||
let tab_record = format!("100644 {sha1} 0\ttab\tpath.txt\0");
|
||||
assert!(
|
||||
parse_index_stage_snapshot(tab_record.as_bytes(), &tab_path, IndexObjectFormat::Sha1)
|
||||
.is_ok()
|
||||
);
|
||||
|
||||
let uppercase = format!("100644 {} 0\tfile.txt\0", "A".repeat(40));
|
||||
let zero_stage_zero = format!("100644 {} 0\tfile.txt\0", "0".repeat(40));
|
||||
let lone_unmerged = format!("100644 {sha1} 2\tfile.txt\0");
|
||||
let stage_zero_and_one = format!("100644 {sha1} 0\tfile.txt\0100644 {sha1} 1\tfile.txt\0");
|
||||
let malformed = [
|
||||
b"\0".to_vec(),
|
||||
format!("\0{sha1_record}").into_bytes(),
|
||||
format!("{sha1_record}\0").into_bytes(),
|
||||
sha1_record.trim_end_matches('\0').as_bytes().to_vec(),
|
||||
format!("100644 {sha1} 0\tfile.txt\0").into_bytes(),
|
||||
format!("100644 {sha1} 0\tfile.txt\0").into_bytes(),
|
||||
format!("10064 {sha1} 0\tfile.txt\0").into_bytes(),
|
||||
format!("100600 {sha1} 0\tfile.txt\0").into_bytes(),
|
||||
format!("100644 {sha1} 4\tfile.txt\0").into_bytes(),
|
||||
format!("100644 {sha1} 0\tfile.txt\textra\0").into_bytes(),
|
||||
uppercase.into_bytes(),
|
||||
zero_stage_zero.into_bytes(),
|
||||
lone_unmerged.into_bytes(),
|
||||
stage_zero_and_one.into_bytes(),
|
||||
];
|
||||
for value in malformed {
|
||||
assert!(
|
||||
parse_index_stage_snapshot(&value, &paths, IndexObjectFormat::Sha1).is_err(),
|
||||
"accepted malformed stage output {value:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_one_completion_witness_requires_new_noncustom_unmerged_state() {
|
||||
fn entry(byte: u8) -> IndexStageEntry {
|
||||
IndexStageEntry {
|
||||
mode: 0o100644,
|
||||
object_id: IndexObjectId::Sha1([byte; 20]),
|
||||
}
|
||||
}
|
||||
|
||||
let custom = BTreeSet::from(["custom.txt".to_string()]);
|
||||
let clean_before = BTreeMap::from([("peer.txt".to_string(), BTreeMap::from([(0, entry(1))]))]);
|
||||
let newly_conflicted = BTreeMap::from([(
|
||||
"peer.txt".to_string(),
|
||||
BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]),
|
||||
)]);
|
||||
assert!(newly_unmerged_noncustom_path(
|
||||
&clean_before,
|
||||
&newly_conflicted,
|
||||
&custom
|
||||
));
|
||||
|
||||
let already_unmerged = BTreeMap::from([(
|
||||
"peer.txt".to_string(),
|
||||
BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]),
|
||||
)]);
|
||||
let changed_unmerged = BTreeMap::from([(
|
||||
"peer.txt".to_string(),
|
||||
BTreeMap::from([(1, entry(4)), (2, entry(5)), (3, entry(6))]),
|
||||
)]);
|
||||
assert!(!newly_unmerged_noncustom_path(
|
||||
&already_unmerged,
|
||||
&changed_unmerged,
|
||||
&custom
|
||||
));
|
||||
|
||||
let custom_conflict = BTreeMap::from([(
|
||||
"custom.txt".to_string(),
|
||||
BTreeMap::from([(1, entry(1)), (2, entry(2)), (3, entry(3))]),
|
||||
)]);
|
||||
assert!(!newly_unmerged_noncustom_path(
|
||||
&IndexStageSnapshot::new(),
|
||||
&custom_conflict,
|
||||
&custom
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sealed_merge_override_rejects_another_operation_identity() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
@@ -33,12 +236,769 @@ fn sealed_merge_override_rejects_another_operation_identity() {
|
||||
.expect("second apply snapshot");
|
||||
|
||||
let snapshot = first.read_merge_config_snapshot().expect("merge snapshot");
|
||||
let attributes = MergeAttributeSnapshot::from_effective(
|
||||
&first.identity,
|
||||
&snapshot,
|
||||
BTreeMap::from([(
|
||||
"file.txt".to_string(),
|
||||
ParsedPathApplyAttributes {
|
||||
merge: "unspecified".to_string(),
|
||||
safe: unspecified_safe_attributes(),
|
||||
},
|
||||
)]),
|
||||
&BTreeMap::new(),
|
||||
)
|
||||
.expect("merge attribute snapshot");
|
||||
let neutralizer = first
|
||||
.build_merge_override(&snapshot)
|
||||
.expect("build merge override")
|
||||
.expect("physical merge override");
|
||||
.build_merge_override(
|
||||
&snapshot,
|
||||
&attributes,
|
||||
vec!["file.txt".to_string()],
|
||||
BTreeMap::new(),
|
||||
BTreeSet::new(),
|
||||
)
|
||||
.expect("build isolated merge config");
|
||||
let error = second
|
||||
.attach_merge_override(Some(neutralizer))
|
||||
.attach_merge_override(neutralizer)
|
||||
.expect_err("cross-operation override must refuse");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_config_snapshot_tracks_namespaces_and_sticky_conditional_invalidity() {
|
||||
let owner = Arc::new(CapabilityIdentity);
|
||||
let snapshot = MergeConfigSnapshot::from_records(
|
||||
&owner,
|
||||
vec![
|
||||
MergeConfigRecord {
|
||||
key: "merge.default".to_string(),
|
||||
value: GitConfigValue::Explicit("union".to_string()),
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge.demo.name".to_string(),
|
||||
value: GitConfigValue::Implicit,
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge.demo.name".to_string(),
|
||||
value: GitConfigValue::Explicit("later display name".to_string()),
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge.dotted.name.unknown".to_string(),
|
||||
value: GitConfigValue::Implicit,
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge..unknown".to_string(),
|
||||
value: GitConfigValue::Implicit,
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge.default".to_string(),
|
||||
value: GitConfigValue::Implicit,
|
||||
},
|
||||
MergeConfigRecord {
|
||||
key: "merge.default".to_string(),
|
||||
value: GitConfigValue::Explicit("binary".to_string()),
|
||||
},
|
||||
],
|
||||
)
|
||||
.expect("merge config snapshot");
|
||||
|
||||
assert_eq!(snapshot.default_driver(), Some("binary"));
|
||||
assert_eq!(
|
||||
snapshot.namespaces(),
|
||||
&BTreeSet::from([String::new(), "demo".to_string(), "dotted.name".to_string(),])
|
||||
);
|
||||
assert!(
|
||||
snapshot.conditional_invalid(),
|
||||
"a later explicit value must not cure an earlier implicit known value"
|
||||
);
|
||||
|
||||
let unknown_only = MergeConfigSnapshot::from_records(
|
||||
&owner,
|
||||
vec![MergeConfigRecord {
|
||||
key: "merge.unknown.arbitrary".to_string(),
|
||||
value: GitConfigValue::Implicit,
|
||||
}],
|
||||
)
|
||||
.expect("implicit unknown snapshot");
|
||||
assert_eq!(
|
||||
unknown_only.namespaces(),
|
||||
&BTreeSet::from(["unknown".to_string()])
|
||||
);
|
||||
assert!(!unknown_only.conditional_invalid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_invalid_merge_marker_is_fixed_and_valueless() {
|
||||
let directory = tempfile::tempdir().expect("config directory");
|
||||
let config = directory.path().join("config");
|
||||
std::fs::write(&config, b"[core]\n\tbare = false\n").expect("write base config");
|
||||
|
||||
append_conditional_invalid_merge_config(&config).expect("append fixed marker");
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read(&config).expect("read marker config"),
|
||||
b"[core]\n\tbare = false\n\n[merge \"codex-conditional-invalid\"]\n\tdriver\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_merge_attribute_patterns_are_rooted_and_literal() {
|
||||
let target = "dir/literal *?[]\"quote\"\\slash\tline\n.txt".to_string();
|
||||
#[cfg(not(windows))]
|
||||
let wildcard_decoy = target.replacen('*', "X", 1);
|
||||
#[cfg(not(windows))]
|
||||
let nested_decoy = format!("nested/{target}");
|
||||
#[cfg(not(windows))]
|
||||
let projected_target = target.clone();
|
||||
#[cfg(windows)]
|
||||
let projected_target = target;
|
||||
let projection = projected_merge_attributes(&BTreeMap::from([(
|
||||
projected_target,
|
||||
frozen_path(BuiltinMergeDriver::Union),
|
||||
)]))
|
||||
.expect("literal projection");
|
||||
#[cfg(not(windows))]
|
||||
let projection_for_git = projection.clone();
|
||||
let rendered = String::from_utf8(projection).expect("UTF-8 projection");
|
||||
assert!(rendered.starts_with("\"/dir/"), "{rendered:?}");
|
||||
assert!(rendered.contains("\\\\*"), "{rendered:?}");
|
||||
assert!(rendered.contains("\\\\?"), "{rendered:?}");
|
||||
assert!(rendered.contains("\\\\["), "{rendered:?}");
|
||||
assert!(rendered.contains("\\\\]"), "{rendered:?}");
|
||||
assert!(rendered.contains("\\\"quote\\\""), "{rendered:?}");
|
||||
assert!(rendered.contains("\\\\\\\\slash"), "{rendered:?}");
|
||||
assert!(rendered.contains("\\tline\\n.txt"), "{rendered:?}");
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
run_git(repo.path(), &["init", "-q"]);
|
||||
std::fs::write(repo.path().join(".git/info/attributes"), projection_for_git)
|
||||
.expect("write projected attributes");
|
||||
let output = git_output(
|
||||
repo.path(),
|
||||
&[
|
||||
"check-attr",
|
||||
"-z",
|
||||
"merge",
|
||||
"--",
|
||||
&target,
|
||||
&wildcard_decoy,
|
||||
&nested_decoy,
|
||||
],
|
||||
);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"check projected attributes: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let paths = vec![target.clone(), wildcard_decoy.clone(), nested_decoy.clone()];
|
||||
let parsed = crate::merge_driver::parse_merge_attributes(&output.stdout, &paths)
|
||||
.expect("parse projected attributes");
|
||||
assert_eq!(parsed.get(&target).map(String::as_str), Some("union"));
|
||||
assert_eq!(
|
||||
parsed.get(&wildcard_decoy).map(String::as_str),
|
||||
Some("unspecified")
|
||||
);
|
||||
assert_eq!(
|
||||
parsed.get(&nested_decoy).map(String::as_str),
|
||||
Some("unspecified")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_whitespace_states_mask_lower_sources() {
|
||||
let paths = ["set.txt", "unset.txt", "unspecified.txt", "value.txt"].map(str::to_string);
|
||||
let whitespace = [
|
||||
ProjectedAttribute::Set,
|
||||
ProjectedAttribute::Unset,
|
||||
ProjectedAttribute::Unspecified,
|
||||
ProjectedAttribute::Value(b"indent-with-non-tab,tabwidth=4".to_vec()),
|
||||
];
|
||||
let attributes = paths
|
||||
.iter()
|
||||
.cloned()
|
||||
.zip(whitespace.iter().cloned())
|
||||
.map(|(path, whitespace)| {
|
||||
let mut attributes = frozen_path(BuiltinMergeDriver::Text);
|
||||
attributes.safe.whitespace = whitespace;
|
||||
(path, attributes)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let projection =
|
||||
projected_merge_attributes(&attributes).expect("project all whitespace states");
|
||||
let rendered = String::from_utf8(projection.clone()).expect("UTF-8 projection");
|
||||
assert!(rendered.contains("/set.txt\" merge=text !filter whitespace "));
|
||||
assert!(rendered.contains("/unset.txt\" merge=text !filter -whitespace "));
|
||||
assert!(rendered.contains("/unspecified.txt\" merge=text !filter !whitespace "));
|
||||
assert!(
|
||||
rendered
|
||||
.contains("/value.txt\" merge=text !filter whitespace=indent-with-non-tab,tabwidth=4 ")
|
||||
);
|
||||
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
run_git(root, &["init", "-q"]);
|
||||
let lower = tempfile::NamedTempFile::new().expect("core attributes file");
|
||||
std::fs::write(
|
||||
lower.path(),
|
||||
"set.txt -whitespace\nunset.txt whitespace\nunspecified.txt -whitespace\nvalue.txt whitespace\n",
|
||||
)
|
||||
.expect("write lower core attributes");
|
||||
run_git(
|
||||
root,
|
||||
&[
|
||||
"config",
|
||||
"core.attributesFile",
|
||||
lower.path().to_str().expect("UTF-8 attributes path"),
|
||||
],
|
||||
);
|
||||
std::fs::write(
|
||||
root.join(".gitattributes"),
|
||||
"set.txt -whitespace\nunset.txt whitespace\nunspecified.txt whitespace\nvalue.txt -whitespace\n",
|
||||
)
|
||||
.expect("write lower worktree attributes");
|
||||
std::fs::write(root.join(".git/info/attributes"), projection)
|
||||
.expect("write highest-precedence projection");
|
||||
|
||||
let output = git_output(
|
||||
root,
|
||||
&[
|
||||
"check-attr",
|
||||
"-z",
|
||||
"merge",
|
||||
"whitespace",
|
||||
"conflict-marker-size",
|
||||
"text",
|
||||
"crlf",
|
||||
"eol",
|
||||
"ident",
|
||||
"filter",
|
||||
"working-tree-encoding",
|
||||
"--",
|
||||
&paths[0],
|
||||
&paths[1],
|
||||
&paths[2],
|
||||
&paths[3],
|
||||
],
|
||||
);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"check projected attributes: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let actual =
|
||||
parse_three_way_attributes(&output.stdout, &paths).expect("parse projected attributes");
|
||||
assert!(actual.values().all(|attributes| attributes.merge == "text"));
|
||||
assert_eq!(
|
||||
actual
|
||||
.values()
|
||||
.map(|attributes| attributes.safe.whitespace.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
whitespace
|
||||
);
|
||||
assert!(
|
||||
actual
|
||||
.values()
|
||||
.all(|attributes| attributes.safe._filter == ProjectedAttribute::Unspecified)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_way_attribute_parser_rejects_malformed_or_unrepresentable_values() {
|
||||
let paths = vec!["file.txt".to_string()];
|
||||
let valid = complete_attribute_output(
|
||||
"file.txt",
|
||||
&[
|
||||
("whitespace", b"native-unknown,,tabwidth=4junk"),
|
||||
("conflict-marker-size", b"12"),
|
||||
("eol", b"crlf"),
|
||||
("working-tree-encoding", b"UTF-16LE"),
|
||||
("filter", b"selected-but-never-projected"),
|
||||
],
|
||||
);
|
||||
let attributes = parse_three_way_attributes(&valid, &paths).expect("valid attribute snapshot");
|
||||
let safe = &attributes.get("file.txt").expect("file attributes").safe;
|
||||
assert_eq!(
|
||||
safe.whitespace,
|
||||
ProjectedAttribute::Value(b"native-unknown,,tabwidth=4junk".to_vec())
|
||||
);
|
||||
assert_eq!(
|
||||
safe.conflict_marker_size,
|
||||
ProjectedAttribute::Value(b"12".to_vec())
|
||||
);
|
||||
assert_eq!(
|
||||
safe._filter,
|
||||
ProjectedAttribute::Value(b"selected-but-never-projected".to_vec())
|
||||
);
|
||||
assert_eq!(
|
||||
ProjectedAttribute::from_check_attr(b"").expect("native empty value"),
|
||||
ProjectedAttribute::Value(Vec::new())
|
||||
);
|
||||
assert_eq!(
|
||||
ProjectedAttribute::Value(Vec::new()).projected_token("whitespace"),
|
||||
b"whitespace="
|
||||
);
|
||||
|
||||
let mut duplicate = valid.clone();
|
||||
duplicate.extend_from_slice(b"file.txt\0text\0set\0");
|
||||
let mut unexpected_name = valid.clone();
|
||||
let name_start = unexpected_name
|
||||
.windows(b"whitespace".len())
|
||||
.position(|window| window == b"whitespace")
|
||||
.expect("whitespace name");
|
||||
unexpected_name.splice(
|
||||
name_start..name_start + b"whitespace".len(),
|
||||
b"other".iter().copied(),
|
||||
);
|
||||
let mut unrepresentable = valid;
|
||||
let value_start = unrepresentable
|
||||
.windows(b"native-unknown,,tabwidth=4junk".len())
|
||||
.position(|window| window == b"native-unknown,,tabwidth=4junk")
|
||||
.expect("whitespace value");
|
||||
unrepresentable[value_start] = b' ';
|
||||
for malformed in [
|
||||
duplicate,
|
||||
unexpected_name,
|
||||
complete_attribute_output("other.txt", &[]),
|
||||
complete_attribute_output("file.txt", &[])[..20].to_vec(),
|
||||
unrepresentable,
|
||||
] {
|
||||
assert!(
|
||||
parse_three_way_attributes(&malformed, &paths).is_err(),
|
||||
"accepted malformed attribute output {malformed:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_safe_attributes_preserve_raw_values_and_neutralize_filter() {
|
||||
let mut attributes = frozen_path(BuiltinMergeDriver::Union);
|
||||
attributes.safe = SafeApplyAttributes {
|
||||
whitespace: ProjectedAttribute::Value(b"unknown,,tabwidth=4junk".to_vec()),
|
||||
conflict_marker_size: ProjectedAttribute::Value(b"12".to_vec()),
|
||||
text: ProjectedAttribute::Set,
|
||||
crlf: ProjectedAttribute::Unset,
|
||||
eol: ProjectedAttribute::Value(b"crlf".to_vec()),
|
||||
ident: ProjectedAttribute::Set,
|
||||
working_tree_encoding: ProjectedAttribute::Value(b"UTF-16LE".to_vec()),
|
||||
_filter: ProjectedAttribute::Value(b"executable".to_vec()),
|
||||
};
|
||||
let projection =
|
||||
projected_merge_attributes(&BTreeMap::from([("file.txt".to_string(), attributes)]))
|
||||
.expect("project safe attributes");
|
||||
let rendered = String::from_utf8(projection).expect("ASCII projection");
|
||||
assert!(rendered.contains("merge=union"), "{rendered}");
|
||||
assert!(rendered.contains("!filter"), "{rendered}");
|
||||
assert!(!rendered.contains("filter=executable"), "{rendered}");
|
||||
assert!(
|
||||
rendered.contains("whitespace=unknown,,tabwidth=4junk"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(rendered.contains("conflict-marker-size=12"), "{rendered}");
|
||||
assert!(rendered.contains(" text "), "{rendered}");
|
||||
assert!(rendered.contains(" -crlf "), "{rendered}");
|
||||
assert!(rendered.contains(" eol=crlf "), "{rendered}");
|
||||
assert!(rendered.contains(" ident "), "{rendered}");
|
||||
assert!(
|
||||
rendered.contains("working-tree-encoding=UTF-16LE"),
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_attribute_lines_split_below_git_limit_or_fail_closed() {
|
||||
let mut split = frozen_path(BuiltinMergeDriver::Text);
|
||||
split.safe.whitespace = ProjectedAttribute::Value(vec![b'w'; 1_500]);
|
||||
split.safe.conflict_marker_size = ProjectedAttribute::Value(vec![b'1'; 1_500]);
|
||||
let projection = projected_merge_attributes(&BTreeMap::from([("file.txt".to_string(), split)]))
|
||||
.expect("split long projection");
|
||||
let lines = projection
|
||||
.strip_suffix(b"\n")
|
||||
.expect("terminated projection")
|
||||
.split(|byte| *byte == b'\n')
|
||||
.collect::<Vec<_>>();
|
||||
assert!(lines.len() >= 2, "projection did not split");
|
||||
assert!(
|
||||
lines
|
||||
.iter()
|
||||
.all(|line| line.len() < GIT_ATTRIBUTE_LINE_LENGTH_LIMIT),
|
||||
"oversized projected line"
|
||||
);
|
||||
|
||||
let mut too_long = frozen_path(BuiltinMergeDriver::Text);
|
||||
too_long.safe.whitespace = ProjectedAttribute::Value(vec![b'w'; 2_048]);
|
||||
assert_eq!(
|
||||
projected_merge_attributes(&BTreeMap::from([("file.txt".to_string(), too_long,)]))
|
||||
.expect_err("reject unprojectable value")
|
||||
.kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_check_attr_conflates_sentinels_for_every_projected_name() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
run_git(root, &["init", "-q"]);
|
||||
let names = [
|
||||
"merge",
|
||||
"whitespace",
|
||||
"conflict-marker-size",
|
||||
"text",
|
||||
"crlf",
|
||||
"eol",
|
||||
"ident",
|
||||
"filter",
|
||||
"working-tree-encoding",
|
||||
];
|
||||
let bare_set = names.join(" ");
|
||||
let literal_set = names
|
||||
.iter()
|
||||
.map(|name| format!("{name}=set"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let bare_unset = names
|
||||
.iter()
|
||||
.map(|name| format!("-{name}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let literal_unset = names
|
||||
.iter()
|
||||
.map(|name| format!("{name}=unset"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let bare_unspecified = names
|
||||
.iter()
|
||||
.map(|name| format!("!{name}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let literal_unspecified = names
|
||||
.iter()
|
||||
.map(|name| format!("{name}=unspecified"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
std::fs::write(
|
||||
root.join(".gitattributes"),
|
||||
format!(
|
||||
"bare-set {bare_set}\nliteral-set {literal_set}\nbare-unset {bare_unset}\nliteral-unset {literal_unset}\nbare-unspecified {bare_unspecified}\nliteral-unspecified {literal_unspecified}\n"
|
||||
),
|
||||
)
|
||||
.expect("write sentinel fixtures");
|
||||
let paths = [
|
||||
"bare-set",
|
||||
"literal-set",
|
||||
"bare-unset",
|
||||
"literal-unset",
|
||||
"bare-unspecified",
|
||||
"literal-unspecified",
|
||||
];
|
||||
let mut args = vec!["check-attr", "-z"];
|
||||
args.extend(names);
|
||||
args.push("--");
|
||||
args.extend(paths);
|
||||
let output = git_output(root, &args);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"check sentinel attributes: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let fields = output.stdout.split(|byte| *byte == 0).collect::<Vec<_>>();
|
||||
assert_eq!(fields.len(), paths.len() * names.len() * 3 + 1);
|
||||
let values = fields[..fields.len() - 1]
|
||||
.chunks_exact(3)
|
||||
.map(|record| record[2])
|
||||
.collect::<Vec<_>>();
|
||||
for (path_index, expected) in [
|
||||
b"set".as_slice(),
|
||||
b"set".as_slice(),
|
||||
b"unset".as_slice(),
|
||||
b"unset".as_slice(),
|
||||
b"unspecified".as_slice(),
|
||||
b"unspecified".as_slice(),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
assert!(
|
||||
values[path_index * names.len()..(path_index + 1) * names.len()]
|
||||
.iter()
|
||||
.all(|actual| *actual == expected),
|
||||
"path {} did not render as {:?}",
|
||||
paths[path_index],
|
||||
String::from_utf8_lossy(expected)
|
||||
);
|
||||
}
|
||||
|
||||
let expected_paths = paths.map(str::to_string).to_vec();
|
||||
let parsed = parse_three_way_attributes(&output.stdout, &expected_paths)
|
||||
.expect("parse conventional sentinel rendering");
|
||||
// The bounded implementation accepts this documented residual: literal
|
||||
// sentinel values are projected as their same-spelled special states.
|
||||
assert_eq!(parsed["literal-set"].safe.text, ProjectedAttribute::Set);
|
||||
assert_eq!(
|
||||
parsed["literal-unset"].safe.ident,
|
||||
ProjectedAttribute::Unset
|
||||
);
|
||||
assert_eq!(
|
||||
parsed["literal-unspecified"].safe._filter,
|
||||
ProjectedAttribute::Unspecified
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_attribute_snapshot_normalizes_only_builtin_semantics() {
|
||||
for (attribute, default, expected) in [
|
||||
("set", "union", BuiltinMergeDriver::Text),
|
||||
("text", "binary", BuiltinMergeDriver::Text),
|
||||
("unset", "text", BuiltinMergeDriver::Binary),
|
||||
("binary", "union", BuiltinMergeDriver::Binary),
|
||||
("union", "binary", BuiltinMergeDriver::Union),
|
||||
("missing-custom", "union", BuiltinMergeDriver::Text),
|
||||
("unspecified", "binary", BuiltinMergeDriver::Binary),
|
||||
("unspecified", "union", BuiltinMergeDriver::Union),
|
||||
("unspecified", "other", BuiltinMergeDriver::Text),
|
||||
] {
|
||||
assert_eq!(
|
||||
BuiltinMergeDriver::from_effective_attribute(attribute, default),
|
||||
expected,
|
||||
"attribute={attribute:?}, default={default:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolated_format_snapshot_ignores_non_common_and_included_spoofs() {
|
||||
const TEST_NAME: &str = "guarded_config::merge_overlay::tests::isolated_format_snapshot_ignores_non_common_and_included_spoofs";
|
||||
if std::env::var_os("CODEX_GIT_UTILS_MERGE_OVERLAY_CHILD").is_none() {
|
||||
let environment = tempfile::tempdir().expect("config environment");
|
||||
let global = environment.path().join("global.gitconfig");
|
||||
let system = environment.path().join("system.gitconfig");
|
||||
std::fs::write(
|
||||
&global,
|
||||
"[core]\n\trepositoryFormatVersion = 1\n\tsharedRepository = world\n[extensions]\n\tobjectFormat = sha256\n",
|
||||
)
|
||||
.expect("write global spoof");
|
||||
std::fs::write(&system, "").expect("write system config");
|
||||
run_isolated_overlay_test(
|
||||
TEST_NAME,
|
||||
&[
|
||||
("GIT_CONFIG_GLOBAL", global.as_os_str()),
|
||||
("GIT_CONFIG_SYSTEM", system.as_os_str()),
|
||||
(
|
||||
"CODEX_APPLY_GIT_CFG",
|
||||
OsStr::new("core.repositoryFormatVersion=1,extensions.objectFormat=sha256"),
|
||||
),
|
||||
],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
run_git(root, &["init", "-q"]);
|
||||
run_git(root, &["config", "core.sharedRepository", "0660"]);
|
||||
run_git(root, &["config", "extensions.worktreeConfig", "true"]);
|
||||
run_git(
|
||||
root,
|
||||
&["config", "--worktree", "core.repositoryFormatVersion", "1"],
|
||||
);
|
||||
run_git(
|
||||
root,
|
||||
&["config", "--worktree", "extensions.objectFormat", "sha256"],
|
||||
);
|
||||
let included = tempfile::NamedTempFile::new().expect("included config");
|
||||
std::fs::write(
|
||||
included.path(),
|
||||
"[core]\n\trepositoryFormatVersion = 1\n[extensions]\n\tobjectFormat = sha256\n",
|
||||
)
|
||||
.expect("write included spoof");
|
||||
run_git(
|
||||
root,
|
||||
&[
|
||||
"config",
|
||||
"--add",
|
||||
"include.path",
|
||||
included.path().to_str().expect("UTF-8 include path"),
|
||||
],
|
||||
);
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("runner");
|
||||
let mut guarded =
|
||||
GuardedGitConfig::authorize(&git, root, crate::apply::configured_git_config_parts())
|
||||
.expect("guarded config");
|
||||
guarded
|
||||
.authorize_filter_paths(&["file.txt".to_string()])
|
||||
.expect("filter snapshot");
|
||||
guarded
|
||||
.install_three_way_merge_policy(&["file.txt".to_string()])
|
||||
.expect("install merge policy");
|
||||
let isolated = guarded
|
||||
.merge_common_config_path()
|
||||
.expect("isolated common config");
|
||||
|
||||
assert_eq!(
|
||||
config_file_value(root, &isolated, "core.repositoryFormatVersion"),
|
||||
Some("0".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
config_file_value(root, &isolated, "extensions.objectFormat"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
config_file_value(root, &isolated, "core.sharedRepository"),
|
||||
Some("0660".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_repository_values_are_normalized_or_rejected() {
|
||||
assert_eq!(
|
||||
normalize_shared_repository(&GitConfigValue::Implicit)
|
||||
.expect("valid implicit shared repository value"),
|
||||
"group"
|
||||
);
|
||||
for (input, expected) in [
|
||||
("", "umask"),
|
||||
("true", "group"),
|
||||
("YES", "group"),
|
||||
("false", "umask"),
|
||||
("off", "umask"),
|
||||
("group", "group"),
|
||||
("world", "all"),
|
||||
("everybody", "all"),
|
||||
("0", "umask"),
|
||||
("00", "umask"),
|
||||
("1", "group"),
|
||||
("01", "group"),
|
||||
("2", "all"),
|
||||
("02", "all"),
|
||||
("600", "0600"),
|
||||
("0600", "0600"),
|
||||
("640", "0640"),
|
||||
("0640", "0640"),
|
||||
("660", "0660"),
|
||||
("0660", "0660"),
|
||||
("664", "0664"),
|
||||
("0777", "0666"),
|
||||
("000660", "0660"),
|
||||
("06600", "0600"),
|
||||
("+0660", "0660"),
|
||||
("-0", "umask"),
|
||||
("-1", "0666"),
|
||||
("-2", "0666"),
|
||||
("-3", "0664"),
|
||||
("8", "group"),
|
||||
("9", "group"),
|
||||
("0x1", "group"),
|
||||
("0x2", "group"),
|
||||
("1k", "group"),
|
||||
("-1k", "group"),
|
||||
("0x0", "umask"),
|
||||
("0k", "umask"),
|
||||
(" 0660", "0660"),
|
||||
("2147483647", "group"),
|
||||
] {
|
||||
let value = GitConfigValue::Explicit(input.to_string());
|
||||
assert_eq!(
|
||||
normalize_shared_repository(&value).expect("valid shared repository value"),
|
||||
expected,
|
||||
"{input:?}"
|
||||
);
|
||||
}
|
||||
for invalid in [
|
||||
"UMASK",
|
||||
"GROUP",
|
||||
"ALL",
|
||||
"WORLD",
|
||||
"EVERYBODY",
|
||||
"3",
|
||||
"7",
|
||||
"10",
|
||||
"20",
|
||||
"100",
|
||||
"0444",
|
||||
"0003",
|
||||
"-0660",
|
||||
"-0777",
|
||||
"invalid",
|
||||
"0999",
|
||||
"0o660",
|
||||
"0660 ",
|
||||
" 0660 ",
|
||||
" true",
|
||||
"true ",
|
||||
" ",
|
||||
"2147483648",
|
||||
"777777777777777777777777777777777777777",
|
||||
] {
|
||||
let value = GitConfigValue::Explicit(invalid.to_string());
|
||||
assert_eq!(
|
||||
normalize_shared_repository(&value)
|
||||
.expect_err("reject malformed shared repository value")
|
||||
.kind(),
|
||||
io::ErrorKind::InvalidData,
|
||||
"{invalid:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_direct_common_reader_preserves_compat_object_format_without_repo_setup() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
run_git(root, &["init", "-q", "--object-format=sha256"]);
|
||||
let git = GitRunner::for_cwd_io(root).expect("runner before compat extension");
|
||||
let guarded = GuardedGitConfig::authorize(&git, root, Vec::new()).expect("guarded config");
|
||||
let config_path = root.join(".git/config");
|
||||
let mut config = std::fs::read_to_string(&config_path).expect("read common config");
|
||||
config.push_str("\n[extensions]\n\tcompatObjectFormat = sha1\n");
|
||||
std::fs::write(&config_path, config).expect("append compat format");
|
||||
|
||||
let (output, expected_origin) = git
|
||||
.read_active_common_config_without_includes(
|
||||
REPOSITORY_FORMAT_CONFIG_PATTERN,
|
||||
/*show_scope*/ true,
|
||||
)
|
||||
.expect("read direct common format without repository setup");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"direct format read: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let entries = crate::git_config::parse_config_entries(&output.stdout)
|
||||
.expect("parse direct common format");
|
||||
assert!(entries.iter().all(|entry| {
|
||||
entry.origin == crate::git_config::GitConfigOrigin::File(expected_origin.clone())
|
||||
}));
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|entry| { entry.key == "core.repositoryformatversion" && entry.value == "1" })
|
||||
);
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|entry| entry.key == "extensions.objectformat" && entry.value == "sha256")
|
||||
);
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|entry| { entry.key == "extensions.compatobjectformat" && entry.value == "sha1" })
|
||||
);
|
||||
|
||||
let isolated = git
|
||||
.create_isolated_common_dir()
|
||||
.expect("isolated common directory");
|
||||
let isolated_config = isolated.config_path();
|
||||
for entry in &entries {
|
||||
guarded
|
||||
.write_sanitized_config_value(&isolated_config, &entry.key, &entry.value)
|
||||
.expect("project direct format entry");
|
||||
}
|
||||
assert_eq!(
|
||||
config_file_value(root, &isolated_config, "extensions.compatObjectFormat"),
|
||||
Some("sha1".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsStr;
|
||||
use std::ffi::OsString;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::CapabilityIdentity;
|
||||
use super::GuardedGitConfig;
|
||||
use super::command_failure;
|
||||
use crate::git_command::IsolatedGitReadContext;
|
||||
use crate::git_command::MAX_INTERNAL_GIT_OUTPUT_BYTES;
|
||||
use crate::git_config::parse_git_boolean;
|
||||
const STATUS_SAFE_CONFIG_PATTERN: &str = r"^(attr\.tree|core\.(filemode|symlinks|ignorecase|precomposeunicode|protecthfs|protectntfs|trustctime|checkstat|longpaths|fscache|splitindex|sparsecheckout|sparsecheckoutcone|autocrlf|eol|safecrlf|checkroundtripencoding|bigfilethreshold|quotepath|abbrev)|index\.(sparse|version))$";
|
||||
const REPOSITORY_FORMAT_CONFIG_PATTERN: &str =
|
||||
r"^(core\.repositoryformatversion|extensions\.(objectformat|compatobjectformat))$";
|
||||
const MAX_STATUS_ATTRIBUTE_SOURCE_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_STATUS_PROJECTED_CONFIG_BYTES: usize = 1024 * 1024;
|
||||
const MAX_STATUS_PROJECTED_CONFIG_ENTRIES: usize = 256;
|
||||
|
||||
pub(super) struct SealedStatusReadContext {
|
||||
owner: Arc<CapabilityIdentity>,
|
||||
context: IsolatedGitReadContext,
|
||||
has_untracked: bool,
|
||||
}
|
||||
|
||||
impl SealedStatusReadContext {
|
||||
pub(super) fn context(
|
||||
&self,
|
||||
owner: &Arc<CapabilityIdentity>,
|
||||
) -> io::Result<&IsolatedGitReadContext> {
|
||||
if !Arc::ptr_eq(&self.owner, owner) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"sealed Status read context belongs to another operation",
|
||||
));
|
||||
}
|
||||
Ok(&self.context)
|
||||
}
|
||||
|
||||
pub(super) fn has_untracked(&self, owner: &Arc<CapabilityIdentity>) -> io::Result<bool> {
|
||||
let _ = self.context(owner)?;
|
||||
Ok(self.has_untracked)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn config_path(&self, owner: &Arc<CapabilityIdentity>) -> io::Result<std::path::PathBuf> {
|
||||
Ok(self.context(owner)?.config_path())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn attributes_path(
|
||||
&self,
|
||||
owner: &Arc<CapabilityIdentity>,
|
||||
) -> io::Result<std::path::PathBuf> {
|
||||
Ok(self.context(owner)?.attributes_path())
|
||||
}
|
||||
}
|
||||
|
||||
impl GuardedGitConfig<'_> {
|
||||
pub(super) async fn build_status_read_context_async(
|
||||
&self,
|
||||
head_oid: Option<&str>,
|
||||
has_untracked: bool,
|
||||
) -> io::Result<SealedStatusReadContext> {
|
||||
if self.sources.git.attribute_source_is_custom() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"frozen Status is unavailable with GIT_ATTR_SOURCE",
|
||||
));
|
||||
}
|
||||
let info_attributes = self
|
||||
.sources
|
||||
.git
|
||||
.read_active_info_attributes_bounded_async(MAX_STATUS_ATTRIBUTE_SOURCE_BYTES)
|
||||
.await?;
|
||||
let core_attributes_file = self.read_status_core_attributes_file_async().await?;
|
||||
let operation_identity = self.operation_identity();
|
||||
let context = self
|
||||
.sources
|
||||
.git
|
||||
.create_isolated_read_context(head_oid, &operation_identity)?;
|
||||
self.write_status_projection_config_async(&context, core_attributes_file.as_deref())
|
||||
.await?;
|
||||
std::fs::write(
|
||||
context.attributes_path(),
|
||||
status_info_attributes(info_attributes)?,
|
||||
)?;
|
||||
let context = context.seal_projected_files()?;
|
||||
Ok(SealedStatusReadContext {
|
||||
owner: Arc::clone(&self.identity),
|
||||
context,
|
||||
has_untracked,
|
||||
})
|
||||
}
|
||||
|
||||
async fn write_status_projection_config_async(
|
||||
&self,
|
||||
context: &IsolatedGitReadContext,
|
||||
core_attributes_file: Option<&OsStr>,
|
||||
) -> io::Result<()> {
|
||||
let entries = self
|
||||
.sources
|
||||
.read_effective_async(STATUS_SAFE_CONFIG_PATTERN, "status allowlist")
|
||||
.await?;
|
||||
let repository_format = self
|
||||
.sources
|
||||
.read_direct_common_config_async(
|
||||
REPOSITORY_FORMAT_CONFIG_PATTERN,
|
||||
"repository format",
|
||||
)
|
||||
.await?;
|
||||
if entries.len().saturating_add(repository_format.len())
|
||||
> MAX_STATUS_PROJECTED_CONFIG_ENTRIES
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"status config projection exceeds its entry limit",
|
||||
));
|
||||
}
|
||||
refuse_sparse_status(&entries)?;
|
||||
let projected_bytes = entries
|
||||
.iter()
|
||||
.chain(repository_format.iter())
|
||||
.try_fold(0_usize, |total, (key, entry)| {
|
||||
total
|
||||
.checked_add(key.len())
|
||||
.and_then(|total| total.checked_add(entry.value.len()))
|
||||
.and_then(|total| total.checked_add(2))
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"status config projection size overflow",
|
||||
)
|
||||
})
|
||||
})?;
|
||||
if projected_bytes > MAX_STATUS_PROJECTED_CONFIG_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"status config projection exceeds its byte limit",
|
||||
));
|
||||
}
|
||||
for entry in entries.values() {
|
||||
self.write_status_config_value_async(
|
||||
&context.config_path(),
|
||||
&entry.key,
|
||||
&entry.value,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
for entry in repository_format.values() {
|
||||
self.write_status_config_value_async(
|
||||
&context.config_path(),
|
||||
&entry.key,
|
||||
&entry.value,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
self.write_status_config_value_async(&context.config_path(), "core.bare", "false")
|
||||
.await?;
|
||||
if let Some(core_attributes_file) = core_attributes_file {
|
||||
self.write_status_config_value_async(
|
||||
&context.config_path(),
|
||||
"core.attributesfile",
|
||||
core_attributes_file,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
if std::fs::metadata(context.config_path())?.len()
|
||||
> MAX_STATUS_PROJECTED_CONFIG_BYTES as u64
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"serialized status config projection exceeds its byte limit",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write_status_config_value_async(
|
||||
&self,
|
||||
config_path: &Path,
|
||||
key: &str,
|
||||
value: impl AsRef<OsStr>,
|
||||
) -> io::Result<()> {
|
||||
let mut command = self
|
||||
.sources
|
||||
.git
|
||||
.async_config_file_write_command(config_path);
|
||||
command.arg(key).arg(value);
|
||||
let output = self
|
||||
.sources
|
||||
.git
|
||||
.output_async_bounded(command, MAX_INTERNAL_GIT_OUTPUT_BYTES)
|
||||
.await?;
|
||||
if output.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(command_failure("status config projection write", &output))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the effective configured-global attribute selector using the
|
||||
/// path semantics available on the oldest supported Git. The returned
|
||||
/// absolute bytes are written into the owned config so a relative or `~`
|
||||
/// spelling cannot be reinterpreted against the synthetic config file.
|
||||
async fn read_status_core_attributes_file_async(&self) -> io::Result<Option<OsString>> {
|
||||
let mut command = self.pending_status_command(
|
||||
crate::FsmonitorOverride::Disabled,
|
||||
/*neutralizer*/ None,
|
||||
)?;
|
||||
command.disable_optional_locks().args([
|
||||
"config",
|
||||
"--null",
|
||||
"--path",
|
||||
"--get",
|
||||
"core.attributesFile",
|
||||
]);
|
||||
let output = command.output().await?;
|
||||
if output.status.code() == Some(1)
|
||||
&& output.stdout.is_empty()
|
||||
&& output.stderr.is_empty()
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
if !output.status.success() {
|
||||
return Err(command_failure(
|
||||
"status core.attributesFile discovery",
|
||||
&output,
|
||||
));
|
||||
}
|
||||
let configured = parse_status_config_path(&output.stdout)?;
|
||||
if configured.is_empty() {
|
||||
return Ok(Some(configured));
|
||||
}
|
||||
let configured_path = std::path::PathBuf::from(&configured);
|
||||
if configured_path.is_absolute() {
|
||||
return Ok(Some(configured));
|
||||
}
|
||||
if configured_path
|
||||
.components()
|
||||
.any(|component| matches!(component, std::path::Component::Prefix(_)))
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"frozen Status is unavailable with a drive-relative core.attributesFile",
|
||||
));
|
||||
}
|
||||
Ok(Some(
|
||||
self.sources
|
||||
.canonical_root
|
||||
.join(configured_path)
|
||||
.into_os_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn refuse_sparse_status(
|
||||
entries: &BTreeMap<String, crate::git_config::GitConfigEntry>,
|
||||
) -> io::Result<()> {
|
||||
if entries.contains_key("attr.tree") {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"frozen Status is unavailable with attr.tree",
|
||||
));
|
||||
}
|
||||
for key in [
|
||||
"core.sparsecheckout",
|
||||
"core.sparsecheckoutcone",
|
||||
"index.sparse",
|
||||
] {
|
||||
let Some(entry) = entries.get(key) else {
|
||||
continue;
|
||||
};
|
||||
match parse_git_boolean(entry.value.as_bytes()) {
|
||||
Some(false) | Some(true) if key == "core.sparsecheckoutcone" => {}
|
||||
Some(false) => {}
|
||||
Some(true) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"frozen Status is unavailable for sparse-checkout repositories",
|
||||
));
|
||||
}
|
||||
None => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("invalid sparse Status config value for {key}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn status_info_attributes(mut original: Vec<u8>) -> io::Result<Vec<u8>> {
|
||||
const RESET: &[u8] = b"* !filter !diff\n";
|
||||
if !original.is_empty() && !original.ends_with(b"\n") {
|
||||
original.push(b'\n');
|
||||
}
|
||||
if original.len().saturating_add(RESET.len()) > MAX_STATUS_ATTRIBUTE_SOURCE_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"owned Git info attributes exceed their byte limit",
|
||||
));
|
||||
}
|
||||
original.extend_from_slice(RESET);
|
||||
Ok(original)
|
||||
}
|
||||
|
||||
fn parse_status_config_path(output: &[u8]) -> io::Result<OsString> {
|
||||
let value = output.strip_suffix(&[0]).ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"unterminated Git core.attributesFile path output",
|
||||
)
|
||||
})?;
|
||||
if value.contains(&0) || value.contains(&b'\n') || value.contains(&b'\r') {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"ambiguous Git core.attributesFile path output",
|
||||
));
|
||||
}
|
||||
crate::safe_git::git_path_argument(value)
|
||||
}
|
||||
@@ -40,6 +40,201 @@ fn run_isolated_config_test(test_name: &str) {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frozen_apply_policy_overrides_later_repository_config_changes() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
run_git(root, &["init", "-q"]);
|
||||
run_git(root, &["config", "user.email", "codex@example.com"]);
|
||||
run_git(root, &["config", "user.name", "Codex"]);
|
||||
run_git(root, &["config", "core.autocrlf", "false"]);
|
||||
run_git(root, &["config", "apply.whitespace", "warn"]);
|
||||
run_git(root, &["config", "apply.ignoreWhitespace", "change"]);
|
||||
run_git(root, &["config", "core.whitespace", "-trailing-space"]);
|
||||
std::fs::write(root.join("file.txt"), "old\n").expect("write base");
|
||||
run_git(root, &["add", "file.txt"]);
|
||||
run_git(root, &["commit", "-qm", "base"]);
|
||||
let patch_dir = tempfile::tempdir().expect("patch directory");
|
||||
let patch = patch_dir.path().join("change.diff");
|
||||
std::fs::write(
|
||||
&patch,
|
||||
"diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new \n",
|
||||
)
|
||||
.expect("write patch");
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("runner");
|
||||
let mut config =
|
||||
GuardedGitConfig::authorize(&git, root, Vec::new()).expect("authorized config");
|
||||
config.freeze_apply_policy().expect("freeze apply policy");
|
||||
config
|
||||
.authorize_filter_paths(&["file.txt".to_string()])
|
||||
.expect("authorize filter path");
|
||||
let patch = patch.to_str().expect("UTF-8 patch path");
|
||||
let (rendered, gate) = config
|
||||
.run_apply_policy_gate(false, patch)
|
||||
.expect("run policy gate");
|
||||
assert!(rendered.contains("apply.whitespace=warn"), "{rendered}");
|
||||
assert!(
|
||||
rendered.contains("apply.ignoreWhitespace=change"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains("core.whitespace=-trailing-space"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
gate.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&gate.stderr)
|
||||
);
|
||||
|
||||
run_git(root, &["config", "apply.whitespace", "error"]);
|
||||
run_git(root, &["config", "apply.ignoreWhitespace", "false"]);
|
||||
run_git(root, &["config", "core.whitespace", "trailing-space"]);
|
||||
|
||||
let final_apply = config
|
||||
.run_direct_apply(false, patch)
|
||||
.expect("run final apply");
|
||||
assert!(
|
||||
final_apply.status.success(),
|
||||
"frozen policy must survive config mutation: {}",
|
||||
String::from_utf8_lossy(&final_apply.stderr)
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("file.txt")).expect("read result"),
|
||||
"new \n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frozen_apply_policy_materializes_git_defaults() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
run_git(repo.path(), &["init", "-q"]);
|
||||
let git = GitRunner::for_cwd_io(repo.path()).expect("runner");
|
||||
let mut config =
|
||||
GuardedGitConfig::authorize(&git, repo.path(), Vec::new()).expect("authorized config");
|
||||
config.freeze_apply_policy().expect("freeze apply policy");
|
||||
|
||||
let rendered = config
|
||||
.render_apply_command_for_log(&["apply".to_string(), "--check".to_string()])
|
||||
.expect("render frozen defaults");
|
||||
assert!(rendered.contains("apply.whitespace=warn"), "{rendered}");
|
||||
assert!(
|
||||
rendered.contains("apply.ignoreWhitespace=false"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains("core.whitespace=blank-at-eol,blank-at-eof,space-before-tab"),
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_whitespace_modes_are_typed_and_case_sensitive_at_the_gate() {
|
||||
for (value, expected) in [
|
||||
("warn", ApplyWhitespaceMode::Warn),
|
||||
("nowarn", ApplyWhitespaceMode::Nowarn),
|
||||
("error", ApplyWhitespaceMode::Error),
|
||||
("error-all", ApplyWhitespaceMode::ErrorAll),
|
||||
("fix", ApplyWhitespaceMode::Fix),
|
||||
("strip", ApplyWhitespaceMode::Fix),
|
||||
("ERROR", ApplyWhitespaceMode::Invalid),
|
||||
("unknown", ApplyWhitespaceMode::Invalid),
|
||||
] {
|
||||
assert_eq!(ApplyWhitespaceMode::normalize(value), expected, "{value}");
|
||||
}
|
||||
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
run_git(root, &["init", "-q"]);
|
||||
run_git(root, &["config", "user.email", "codex@example.com"]);
|
||||
run_git(root, &["config", "user.name", "Codex"]);
|
||||
run_git(root, &["config", "apply.whitespace", "ERROR"]);
|
||||
std::fs::write(root.join("file.txt"), "old\n").expect("write base");
|
||||
run_git(root, &["add", "file.txt"]);
|
||||
run_git(root, &["commit", "-qm", "base"]);
|
||||
let patch_dir = tempfile::tempdir().expect("patch directory");
|
||||
let patch = patch_dir.path().join("change.diff");
|
||||
std::fs::write(
|
||||
&patch,
|
||||
"diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new\n",
|
||||
)
|
||||
.expect("write patch");
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("runner");
|
||||
let mut config =
|
||||
GuardedGitConfig::authorize(&git, root, Vec::new()).expect("authorized config");
|
||||
config.freeze_apply_policy().expect("freeze invalid policy");
|
||||
config
|
||||
.authorize_filter_paths(&["file.txt".to_string()])
|
||||
.expect("authorize filter path");
|
||||
assert!(
|
||||
config
|
||||
.final_apply_whitespace_mode(false, patch.to_str().expect("UTF-8 patch path"))
|
||||
.is_err()
|
||||
);
|
||||
let (_, gate) = config
|
||||
.run_apply_policy_gate(false, patch.to_str().expect("UTF-8 patch path"))
|
||||
.expect("run invalid policy gate");
|
||||
assert!(!gate.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&gate.stderr).contains("unrecognized whitespace"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&gate.stderr)
|
||||
);
|
||||
assert!(
|
||||
config
|
||||
.final_apply_whitespace_mode(false, patch.to_str().expect("UTF-8 patch path"))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_apply_policy_gate_is_one_shot_and_bound_to_patch_orientation() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let root = repo.path();
|
||||
run_git(root, &["init", "-q"]);
|
||||
run_git(root, &["config", "user.email", "codex@example.com"]);
|
||||
run_git(root, &["config", "user.name", "Codex"]);
|
||||
run_git(root, &["config", "apply.whitespace", "error"]);
|
||||
std::fs::write(root.join("file.txt"), "old\n").expect("write base");
|
||||
run_git(root, &["add", "file.txt"]);
|
||||
run_git(root, &["commit", "-qm", "base"]);
|
||||
let patch_dir = tempfile::tempdir().expect("patch directory");
|
||||
let patch = patch_dir.path().join("change.diff");
|
||||
std::fs::write(
|
||||
&patch,
|
||||
"diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new\n",
|
||||
)
|
||||
.expect("write patch");
|
||||
let patch = patch.to_str().expect("UTF-8 patch path");
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("runner");
|
||||
let mut config =
|
||||
GuardedGitConfig::authorize(&git, root, Vec::new()).expect("authorized config");
|
||||
config.freeze_apply_policy().expect("freeze policy");
|
||||
config
|
||||
.authorize_filter_paths(&["file.txt".to_string()])
|
||||
.expect("authorize filter path");
|
||||
let (_, gate) = config
|
||||
.run_apply_policy_gate(false, patch)
|
||||
.expect("run successful policy gate");
|
||||
assert!(gate.status.success());
|
||||
assert_eq!(
|
||||
config
|
||||
.final_apply_whitespace_mode(false, patch)
|
||||
.expect("matching proof"),
|
||||
ApplyWhitespaceMode::Error
|
||||
);
|
||||
assert!(config.final_apply_whitespace_mode(true, patch).is_err());
|
||||
assert!(
|
||||
config
|
||||
.final_apply_whitespace_mode(false, "different.patch")
|
||||
.is_err()
|
||||
);
|
||||
assert!(config.run_apply_policy_gate(false, patch).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attached_filter_snapshots_retain_multiple_owned_overrides() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
@@ -125,7 +320,7 @@ fn attached_filter_snapshots_retain_multiple_owned_overrides() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composed_staging_subset_proof_requires_exactly_one_apply_snapshot() {
|
||||
fn reverse_staging_subset_proof_requires_exactly_one_apply_snapshot() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
run_git(repo.path(), &["init", "-q"]);
|
||||
let git = GitRunner::for_cwd_io(repo.path()).expect("runner");
|
||||
@@ -172,7 +367,7 @@ fn zero_driver_merge_policy_still_occupies_the_single_install_slot() {
|
||||
GuardedGitConfig::authorize(&git, repo.path(), Vec::new()).expect("authorized config");
|
||||
|
||||
let error = config
|
||||
.install_three_way_merge_policy()
|
||||
.install_three_way_merge_policy(&[])
|
||||
.expect_err("merge policy without apply snapshot must refuse");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
|
||||
@@ -180,22 +375,22 @@ fn zero_driver_merge_policy_still_occupies_the_single_install_slot() {
|
||||
.authorize_filter_paths(&["file.txt".to_string()])
|
||||
.expect("apply snapshot");
|
||||
config
|
||||
.install_three_way_merge_policy()
|
||||
.install_three_way_merge_policy(&["file.txt".to_string()])
|
||||
.expect("zero-driver merge policy");
|
||||
assert!(config.merge_policy_installed);
|
||||
assert!(config.merge.is_none());
|
||||
assert!(config.merge.is_some());
|
||||
|
||||
let error = config
|
||||
.install_three_way_merge_policy()
|
||||
.install_three_way_merge_policy(&["file.txt".to_string()])
|
||||
.expect_err("second merge policy must refuse");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_order_is_apply_filter_then_merge_then_git_add_filter() {
|
||||
fn isolated_merge_config_is_not_attached_to_preparatory_commands() {
|
||||
if std::env::var_os("CODEX_GIT_UTILS_GUARDED_CONFIG_ENV_CHILD").is_none() {
|
||||
run_isolated_config_test(
|
||||
"guarded_config::tests::command_order_is_apply_filter_then_merge_then_git_add_filter",
|
||||
"guarded_config::tests::isolated_merge_config_is_not_attached_to_preparatory_commands",
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -215,7 +410,7 @@ fn command_order_is_apply_filter_then_merge_then_git_add_filter() {
|
||||
.authorize_filter_paths(&["file.txt".to_string()])
|
||||
.expect("apply filter policy");
|
||||
config
|
||||
.install_three_way_merge_policy()
|
||||
.install_three_way_merge_policy(&["file.txt".to_string()])
|
||||
.expect("merge policy");
|
||||
config
|
||||
.authorize_git_add_filter_paths(&["file.txt".to_string()])
|
||||
@@ -226,26 +421,24 @@ fn command_order_is_apply_filter_then_merge_then_git_add_filter() {
|
||||
.expect("apply filter overlay")
|
||||
.include_arg
|
||||
.clone();
|
||||
let merge_include = config
|
||||
.merge_include_arg()
|
||||
.expect("merge overlay")
|
||||
.to_string();
|
||||
let merge_config = config
|
||||
.merge_common_config_path()
|
||||
.expect("isolated merge config");
|
||||
let git_add_include = config.filters[1]
|
||||
.neutralizer()
|
||||
.expect("Git-add filter overlay")
|
||||
.include_arg
|
||||
.clone();
|
||||
let overlay_paths = [&apply_include, &merge_include, &git_add_include]
|
||||
let overlay_paths = [&apply_include, &git_add_include]
|
||||
.map(|include| PathBuf::from(include.strip_prefix("include.path=").expect("include path")));
|
||||
|
||||
let rendered = config
|
||||
.render_command_for_log(&["ls-files".to_string()])
|
||||
.expect("render command");
|
||||
let apply_offset = rendered.find(&apply_include).expect("apply include");
|
||||
let merge_offset = rendered.find(&merge_include).expect("merge include");
|
||||
let git_add_offset = rendered.find(&git_add_include).expect("Git-add include");
|
||||
assert!(apply_offset < merge_offset && merge_offset < git_add_offset);
|
||||
assert_eq!(rendered.matches(&merge_include).count(), 1);
|
||||
assert!(apply_offset < git_add_offset);
|
||||
assert!(!rendered.contains(&merge_config.display().to_string()));
|
||||
|
||||
let output = config
|
||||
.ls_files_command()
|
||||
@@ -254,9 +447,11 @@ fn command_order_is_apply_filter_then_merge_then_git_add_filter() {
|
||||
.expect("execute bound command");
|
||||
assert!(output.status.success());
|
||||
assert!(overlay_paths.iter().all(|path| path.is_file()));
|
||||
assert!(merge_config.is_file());
|
||||
|
||||
drop(config);
|
||||
assert!(overlay_paths.iter().all(|path| !path.exists()));
|
||||
assert!(!merge_config.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -385,7 +580,10 @@ async fn zero_driver_status_occupies_its_slot_and_excludes_every_mutation_policy
|
||||
.expect("zero-driver status policy");
|
||||
assert_eq!(status_filter_policy_read_count(), 1);
|
||||
let status = config.status.as_ref().expect("occupied status slot");
|
||||
assert!(status.neutralizer.is_none());
|
||||
status
|
||||
.context
|
||||
.context(&config.identity)
|
||||
.expect("sealed zero-driver Status context");
|
||||
assert_eq!(status.fsmonitor, None);
|
||||
|
||||
let error = config
|
||||
@@ -403,15 +601,23 @@ async fn zero_driver_status_occupies_its_slot_and_excludes_every_mutation_policy
|
||||
.expect_err("status plus GitAdd must fail");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
let error = config
|
||||
.install_three_way_merge_policy()
|
||||
.install_three_way_merge_policy(&[])
|
||||
.expect_err("status plus merge must fail");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
let error = config
|
||||
.freeze_apply_policy()
|
||||
.expect_err("status plus frozen apply policy must fail");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert!(config.apply_policy.is_none());
|
||||
assert!(matches!(
|
||||
config.apply_policy_gate,
|
||||
ApplyPolicyGateState::NotRun
|
||||
));
|
||||
let error = config
|
||||
.status_output_async()
|
||||
.await
|
||||
.expect_err("status sink requires a retained fsmonitor decision");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
|
||||
let first = config.detect_status_fsmonitor_async().await;
|
||||
let second = config.detect_status_fsmonitor_async().await;
|
||||
assert_eq!(first, second);
|
||||
@@ -433,13 +639,27 @@ async fn zero_driver_status_occupies_its_slot_and_excludes_every_mutation_policy
|
||||
.expect_err("Apply plus status must fail before a status read");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(status_filter_policy_read_count(), reads_before);
|
||||
|
||||
let mut apply_policy_only =
|
||||
GuardedGitConfig::authorize(&git, repo.path(), Vec::new()).expect("apply capability");
|
||||
apply_policy_only
|
||||
.freeze_apply_policy()
|
||||
.expect("frozen apply policy");
|
||||
let reads_before = status_filter_policy_read_count();
|
||||
let error = apply_policy_only
|
||||
.install_status_policy_async()
|
||||
.await
|
||||
.expect_err("frozen apply policy plus status must fail before a status read");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(status_filter_policy_read_count(), reads_before);
|
||||
assert!(apply_policy_only.status.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_uses_the_shared_four_entry_overlay_and_retains_it_through_the_sink() {
|
||||
async fn status_replaces_filter_config_with_an_owned_helper_free_context() {
|
||||
if std::env::var_os("CODEX_GIT_UTILS_GUARDED_CONFIG_ENV_CHILD").is_none() {
|
||||
run_isolated_config_test(
|
||||
"guarded_config::tests::status_uses_the_shared_four_entry_overlay_and_retains_it_through_the_sink",
|
||||
"guarded_config::tests::status_replaces_filter_config_with_an_owned_helper_free_context",
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -463,42 +683,30 @@ async fn status_uses_the_shared_four_entry_overlay_and_retains_it_through_the_si
|
||||
.install_status_policy_async()
|
||||
.await
|
||||
.expect("optional smudge policy");
|
||||
let neutralizer = config
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|status| status.neutralizer.as_ref())
|
||||
.expect("status neutralizer");
|
||||
let overlay = PathBuf::from(
|
||||
neutralizer
|
||||
.include_arg
|
||||
.strip_prefix("include.path=")
|
||||
.expect("sealed include path"),
|
||||
);
|
||||
assert!(overlay.is_file());
|
||||
let mut actual = Vec::new();
|
||||
for (name, expected) in FILTER_NEUTRALIZATION_PLAN {
|
||||
let output = std::process::Command::new("git")
|
||||
.args(["config", "--file"])
|
||||
.arg(&overlay)
|
||||
.args(["--get", &format!("filter.demo.{name}")])
|
||||
.output()
|
||||
.expect("read neutralization entry");
|
||||
assert!(output.status.success(), "read {name}");
|
||||
actual.push((
|
||||
name,
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_string(),
|
||||
));
|
||||
assert_eq!(actual.last().map(|entry| entry.1.as_str()), Some(expected));
|
||||
}
|
||||
assert_eq!(actual.len(), FILTER_NEUTRALIZATION_PLAN.len());
|
||||
let status = config.status.as_ref().expect("Status context");
|
||||
let owned_config = status
|
||||
.context
|
||||
.config_path(&config.identity)
|
||||
.expect("owned config path");
|
||||
let owned_attributes = status
|
||||
.context
|
||||
.attributes_path(&config.identity)
|
||||
.expect("owned attributes path");
|
||||
let config_contents = std::fs::read_to_string(&owned_config).expect("read owned config");
|
||||
assert!(!config_contents.contains("filter.demo"));
|
||||
let attribute_contents =
|
||||
std::fs::read_to_string(&owned_attributes).expect("read owned attributes");
|
||||
assert!(attribute_contents.contains("!filter"));
|
||||
|
||||
config.detect_status_fsmonitor_async().await;
|
||||
let output = config.status_output_async().await.expect("guarded status");
|
||||
assert!(output.status.success());
|
||||
assert!(overlay.is_file(), "overlay must outlive the final child");
|
||||
drop(config);
|
||||
assert!(owned_config.is_file(), "owned config must outlive final child");
|
||||
assert!(
|
||||
!overlay.exists(),
|
||||
"overlay must be removed with the capability"
|
||||
owned_attributes.is_file(),
|
||||
"owned attributes must outlive final child"
|
||||
);
|
||||
drop(config);
|
||||
assert!(!owned_config.exists(), "owned config must be removed");
|
||||
assert!(!owned_attributes.exists(), "owned attributes must be removed");
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#[cfg(test)]
|
||||
use crate::git_config::GitConfigEntry;
|
||||
#[cfg(test)]
|
||||
use crate::safe_git::isolate_git_command_environment;
|
||||
@@ -5,6 +6,7 @@ use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::io;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn parse_merge_attributes(
|
||||
output: &[u8],
|
||||
expected_paths: &[String],
|
||||
@@ -52,34 +54,66 @@ pub(crate) fn parse_merge_attributes(
|
||||
Ok(attributes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn untrusted_driver_selection(
|
||||
entries: &BTreeMap<String, GitConfigEntry>,
|
||||
attributes: &BTreeMap<String, String>,
|
||||
) -> io::Result<Option<(String, String)>> {
|
||||
let mut drivers = BTreeMap::new();
|
||||
let mut driver_names = BTreeSet::new();
|
||||
for entry in entries.values() {
|
||||
if entry.key == "merge.default" {
|
||||
continue;
|
||||
if let Some(name) = merge_driver_subsection(&entry.key)? {
|
||||
driver_names.insert(name.to_string());
|
||||
}
|
||||
let name = entry
|
||||
.key
|
||||
.strip_prefix("merge.")
|
||||
.and_then(|key| key.strip_suffix(".driver"))
|
||||
.ok_or_else(|| invalid_config_entry("malformed merge driver key"))?;
|
||||
drivers.insert(name.to_string(), entry.value.as_str());
|
||||
}
|
||||
|
||||
let default = entries
|
||||
.get("merge.default")
|
||||
.map(|entry| entry.value.as_str());
|
||||
Ok(
|
||||
untrusted_driver_selections(&driver_names, default, attributes)
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|(path, driver)| (driver, path)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Return every path whose effective merge selection names a configured user
|
||||
/// driver namespace. Git creates that namespace for any subsection key, even
|
||||
/// when `.driver` is missing or explicitly empty; those cases fail or attempt
|
||||
/// an empty command rather than falling back to built-in text. The complete
|
||||
/// set is required by the scratch classifier so every selected namespace is
|
||||
/// quarantined.
|
||||
pub(crate) fn untrusted_driver_selections(
|
||||
driver_names: &BTreeSet<String>,
|
||||
default: Option<&str>,
|
||||
attributes: &BTreeMap<String, String>,
|
||||
) -> BTreeMap<String, String> {
|
||||
let mut selected = BTreeMap::new();
|
||||
for (path, attribute) in attributes {
|
||||
for name in candidate_driver_names(attribute, default) {
|
||||
if drivers.get(name).is_some_and(|value| !value.is_empty()) {
|
||||
return Ok(Some((name.to_string(), path.clone())));
|
||||
if driver_names.contains(name) {
|
||||
selected.insert(path.clone(), name.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
selected
|
||||
}
|
||||
|
||||
/// Parse the user-driver subsection using Git 2.54's last-dot behavior.
|
||||
/// Empty and dotted subsection names are valid; only `merge.default` has no
|
||||
/// user-driver subsection in the fixed query.
|
||||
pub(crate) fn merge_driver_subsection(key: &str) -> io::Result<Option<&str>> {
|
||||
if key == "merge.default" {
|
||||
return Ok(None);
|
||||
}
|
||||
let (name, final_key) = key
|
||||
.strip_prefix("merge.")
|
||||
.and_then(|key| key.rsplit_once('.'))
|
||||
.ok_or_else(|| invalid_config_entry("malformed merge driver key"))?;
|
||||
if final_key.is_empty() {
|
||||
return Err(invalid_config_entry("empty merge driver configuration key"));
|
||||
}
|
||||
Ok(Some(name))
|
||||
}
|
||||
|
||||
fn candidate_driver_names<'a>(attribute: &'a str, default: Option<&'a str>) -> BTreeSet<&'a str> {
|
||||
@@ -92,6 +126,7 @@ fn candidate_driver_names<'a>(attribute: &'a str, default: Option<&'a str>) -> B
|
||||
names
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn invalid_attribute_output(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::*;
|
||||
use crate::apply::ApplyGitRequest;
|
||||
use crate::apply::apply_git_patch;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
@@ -10,8 +11,8 @@ use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
const OLD_DRIVER_COMMAND: &str = "git config codex.oldmergeran true && false";
|
||||
const NEW_DRIVER_COMMAND: &str = "git config codex.newmergeran true && false";
|
||||
const OLD_DRIVER_COMMAND: &str = "git config --file .git/config codex.oldmergeran true && false";
|
||||
const NEW_DRIVER_COMMAND: &str = "git config --file .git/config codex.newmergeran true && false";
|
||||
const TRACE_MUTATION_MARKER: &str = "CODEX_MERGE_DRIVER_TEST_MUTATION";
|
||||
|
||||
fn run(cwd: &Path, args: &[&str]) -> (i32, String, String) {
|
||||
@@ -109,6 +110,10 @@ fn index_tree(root: &Path) -> String {
|
||||
}
|
||||
|
||||
fn run_isolated_test(test_name: &str) {
|
||||
run_isolated_test_with_env(test_name, &[]);
|
||||
}
|
||||
|
||||
fn run_isolated_test_with_env(test_name: &str, extra_env: &[(&str, &OsStr)]) {
|
||||
let environment = tempfile::tempdir().expect("isolated Git environment");
|
||||
let global_config = environment.path().join("global.gitconfig");
|
||||
let system_config = environment.path().join("system.gitconfig");
|
||||
@@ -119,7 +124,7 @@ fn run_isolated_test(test_name: &str) {
|
||||
|
||||
let mut command = std::process::Command::new(std::env::current_exe().expect("test binary"));
|
||||
isolate_git_command_environment(&mut command);
|
||||
let output = command
|
||||
command
|
||||
.arg(test_name)
|
||||
.arg("--exact")
|
||||
.arg("--nocapture")
|
||||
@@ -127,9 +132,11 @@ fn run_isolated_test(test_name: &str) {
|
||||
.env("GIT_CONFIG_GLOBAL", &global_config)
|
||||
.env("GIT_CONFIG_SYSTEM", &system_config)
|
||||
.env("GIT_TRACE2_EVENT", &trace)
|
||||
.env("RUST_TEST_THREADS", "1")
|
||||
.output()
|
||||
.expect("run isolated test process");
|
||||
.env("RUST_TEST_THREADS", "1");
|
||||
for (name, value) in extra_env {
|
||||
command.env(name, value);
|
||||
}
|
||||
let output = command.output().expect("run isolated test process");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"isolated test {test_name} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
@@ -189,6 +196,26 @@ fn append_driver_config(root: &Path, driver: &str, command: &str) {
|
||||
.expect("append replacement merge driver");
|
||||
}
|
||||
|
||||
fn append_default_and_driver_config(root: &Path, driver: &str, command: &str) {
|
||||
let mut config = OpenOptions::new()
|
||||
.append(true)
|
||||
.open(root.join(".git/config"))
|
||||
.expect("open local config");
|
||||
writeln!(
|
||||
config,
|
||||
"\n[merge]\n\tdefault = {driver}\n[merge \"{driver}\"]\n\tdriver = {command}"
|
||||
)
|
||||
.expect("append replacement default merge driver");
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum DriverNamespaceRace {
|
||||
KnownEmpty,
|
||||
SelectedMissing,
|
||||
BrandNewAttribute,
|
||||
BrandNewDefault,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_reverse_checks_worktree_before_staging_and_skips_merge_driver() {
|
||||
let repo = init_repo();
|
||||
@@ -378,6 +405,209 @@ fn post_probe_attribute_and_same_driver_command_change_stays_neutralized() {
|
||||
assert!(!configured_marker_exists(root, "codex.newmergeran"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_probe_worktree_attribute_change_preserves_probed_union_semantics() {
|
||||
if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() {
|
||||
run_isolated_test(
|
||||
"merge_driver::race_tests::post_probe_worktree_attribute_change_preserves_probed_union_semantics",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
let patch = build_conflicting_patch(root, "target.txt merge=union\n");
|
||||
let trace = trace_path();
|
||||
std::fs::write(&trace, "").expect("clear fixture trace");
|
||||
let watcher_trace = trace.clone();
|
||||
let attributes = root.join(".gitattributes");
|
||||
let watcher = thread::spawn(move || {
|
||||
let observed = wait_for_merge_attribute_probe(&watcher_trace);
|
||||
if observed {
|
||||
std::fs::write(attributes, "target.txt -merge\n")
|
||||
.expect("replace union with binary merge semantics");
|
||||
record_trace_mutation(&watcher_trace);
|
||||
}
|
||||
observed
|
||||
});
|
||||
|
||||
let result = apply_git_patch(&request(root, patch, /*revert*/ false))
|
||||
.expect("run frozen union three-way apply");
|
||||
assert!(watcher.join().expect("attribute watcher"));
|
||||
|
||||
assert_mutation_happened_between_probe_and_three_way(&trace);
|
||||
assert_eq!(result.exit_code, 0, "{}", result.stderr);
|
||||
let contents = read_file_normalized(&root.join("target.txt"));
|
||||
assert!(contents.contains("ours\n"), "{contents}");
|
||||
assert!(contents.contains("theirs\n"), "{contents}");
|
||||
assert!(!contents.contains("<<<<<<<"), "{contents}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolated_three_way_config_blocks_driver_namespace_introduction_races() {
|
||||
if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() {
|
||||
run_isolated_test(
|
||||
"merge_driver::race_tests::isolated_three_way_config_blocks_driver_namespace_introduction_races",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
for race in [
|
||||
DriverNamespaceRace::KnownEmpty,
|
||||
DriverNamespaceRace::SelectedMissing,
|
||||
DriverNamespaceRace::BrandNewAttribute,
|
||||
DriverNamespaceRace::BrandNewDefault,
|
||||
] {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
let attributes = match race {
|
||||
DriverNamespaceRace::KnownEmpty | DriverNamespaceRace::SelectedMissing => {
|
||||
"target.txt merge=demo\n"
|
||||
}
|
||||
DriverNamespaceRace::BrandNewAttribute | DriverNamespaceRace::BrandNewDefault => {
|
||||
"# initially safe\n"
|
||||
}
|
||||
};
|
||||
let patch = build_conflicting_patch(root, attributes);
|
||||
if matches!(race, DriverNamespaceRace::KnownEmpty) {
|
||||
configure_driver(root, "demo", "");
|
||||
}
|
||||
let trace = trace_path();
|
||||
std::fs::write(&trace, "").expect("clear fixture trace");
|
||||
let watcher_trace = trace.clone();
|
||||
let watcher_root = root.to_path_buf();
|
||||
let watcher = thread::spawn(move || {
|
||||
let observed = wait_for_merge_attribute_probe(&watcher_trace);
|
||||
if observed {
|
||||
match race {
|
||||
DriverNamespaceRace::KnownEmpty | DriverNamespaceRace::SelectedMissing => {
|
||||
append_driver_config(&watcher_root, "demo", NEW_DRIVER_COMMAND);
|
||||
}
|
||||
DriverNamespaceRace::BrandNewAttribute => {
|
||||
append_driver_config(&watcher_root, "brandnew", NEW_DRIVER_COMMAND);
|
||||
std::fs::write(
|
||||
watcher_root.join(".gitattributes"),
|
||||
"target.txt merge=brandnew\n",
|
||||
)
|
||||
.expect("select brand-new merge driver");
|
||||
}
|
||||
DriverNamespaceRace::BrandNewDefault => {
|
||||
append_default_and_driver_config(
|
||||
&watcher_root,
|
||||
"brandnew",
|
||||
NEW_DRIVER_COMMAND,
|
||||
);
|
||||
}
|
||||
}
|
||||
record_trace_mutation(&watcher_trace);
|
||||
}
|
||||
observed
|
||||
});
|
||||
|
||||
let outcome = apply_git_patch(&request(root, patch, /*revert*/ false));
|
||||
assert!(watcher.join().expect("namespace watcher"), "{race:?}");
|
||||
|
||||
assert_mutation_happened_between_probe_and_three_way(&trace);
|
||||
if matches!(race, DriverNamespaceRace::KnownEmpty) {
|
||||
let error = outcome.expect_err(
|
||||
"an explicit empty driver is a selected namespace and must refuse when reachable",
|
||||
);
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported, "{error}");
|
||||
} else {
|
||||
let result = outcome.expect("run isolated three-way apply");
|
||||
assert_ne!(result.exit_code, 0, "{race:?}");
|
||||
assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=<isolated>"));
|
||||
}
|
||||
assert!(!configured_marker_exists(root, "codex.oldmergeran"));
|
||||
assert!(!configured_marker_exists(root, "codex.newmergeran"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolated_three_way_config_scrubs_command_config_channels() {
|
||||
if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() {
|
||||
run_isolated_test_with_env(
|
||||
"merge_driver::race_tests::isolated_three_way_config_scrubs_command_config_channels",
|
||||
&[
|
||||
("GIT_CONFIG_COUNT", OsStr::new("1")),
|
||||
("GIT_CONFIG_KEY_0", OsStr::new("merge.env-selected.driver")),
|
||||
(
|
||||
"GIT_CONFIG_VALUE_0",
|
||||
OsStr::new("git config --file .git/config codex.envmergeran true && false"),
|
||||
),
|
||||
(
|
||||
"CODEX_APPLY_GIT_CFG",
|
||||
OsStr::new(
|
||||
"merge.base-selected.driver=git config --file .git/config codex.basemergeran true && false",
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
for driver in ["env-selected", "base-selected"] {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
let patch = build_conflicting_patch(root, "# initially safe\n");
|
||||
let trace = trace_path();
|
||||
std::fs::write(&trace, "").expect("clear fixture trace");
|
||||
let watcher_trace = trace.clone();
|
||||
let attributes = root.join(".gitattributes");
|
||||
let watcher = thread::spawn(move || {
|
||||
let observed = wait_for_merge_attribute_probe(&watcher_trace);
|
||||
if observed {
|
||||
std::fs::write(attributes, format!("target.txt merge={driver}\n"))
|
||||
.expect("select command-config merge driver");
|
||||
record_trace_mutation(&watcher_trace);
|
||||
}
|
||||
observed
|
||||
});
|
||||
|
||||
let result = apply_git_patch(&request(root, patch, /*revert*/ false))
|
||||
.expect("run isolated three-way apply");
|
||||
assert!(watcher.join().expect("config-channel watcher"), "{driver}");
|
||||
|
||||
assert_mutation_happened_between_probe_and_three_way(&trace);
|
||||
assert_ne!(result.exit_code, 0, "{driver}");
|
||||
assert!(!configured_marker_exists(root, "codex.envmergeran"));
|
||||
assert!(!configured_marker_exists(root, "codex.basemergeran"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolated_three_way_config_updates_the_linked_worktree_index() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("seed.txt"), "seed\n").expect("write seed");
|
||||
run_success(root, &["add", "seed.txt"]);
|
||||
run_success(root, &["commit", "-m", "seed"]);
|
||||
|
||||
let linked_parent = tempfile::tempdir().expect("linked worktree parent");
|
||||
let linked_root = linked_parent.path().join("linked");
|
||||
run_success(
|
||||
root,
|
||||
&[
|
||||
"worktree",
|
||||
"add",
|
||||
"-b",
|
||||
"isolated-three-way-linked",
|
||||
linked_root.to_str().expect("UTF-8 linked path"),
|
||||
],
|
||||
);
|
||||
let patch = build_conflicting_patch(&linked_root, "# no custom merge driver\n");
|
||||
|
||||
let result = apply_git_patch(&request(&linked_root, patch, /*revert*/ false))
|
||||
.expect("run linked-worktree three-way apply");
|
||||
|
||||
assert_ne!(result.exit_code, 0);
|
||||
assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=<isolated>"));
|
||||
let unmerged = run_success(&linked_root, &["ls-files", "--unmerged", "target.txt"]);
|
||||
assert!(unmerged.contains(" 1\ttarget.txt"), "{unmerged}");
|
||||
assert!(unmerged.contains(" 2\ttarget.txt"), "{unmerged}");
|
||||
assert!(unmerged.contains(" 3\ttarget.txt"), "{unmerged}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_patch_attribute_activation_does_not_run_merge_driver() {
|
||||
let repo = init_repo();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::io;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -13,6 +14,11 @@ use crate::guarded_config::GuardedGitConfig;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct PatchPathInventory {
|
||||
/// Requested-orientation destination records in patch order. Unlike
|
||||
/// `primary_paths`, duplicates are retained so security-sensitive merge
|
||||
/// classification can reject a later record that would hide an earlier
|
||||
/// low-level merge result for the same path.
|
||||
pub(crate) primary_records: Vec<String>,
|
||||
pub(crate) primary_paths: Vec<String>,
|
||||
pub(crate) effective_paths: Vec<String>,
|
||||
}
|
||||
@@ -34,14 +40,16 @@ pub(crate) fn extract_patch_path_inventory_guarded(
|
||||
"forward and reverse patch parsing returned different path counts",
|
||||
));
|
||||
}
|
||||
let primary_paths = primary_paths
|
||||
let primary_records = primary_paths
|
||||
.into_iter()
|
||||
.map(validate_patch_path)
|
||||
.collect::<io::Result<BTreeSet<_>>>()?;
|
||||
let opposite_paths = opposite_paths
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
let opposite_records = opposite_paths
|
||||
.into_iter()
|
||||
.map(validate_patch_path)
|
||||
.collect::<io::Result<BTreeSet<_>>>()?;
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
let primary_paths = primary_records.iter().cloned().collect::<BTreeSet<_>>();
|
||||
let opposite_paths = opposite_records.into_iter().collect::<BTreeSet<_>>();
|
||||
let effective_paths = primary_paths
|
||||
.iter()
|
||||
.cloned()
|
||||
@@ -54,11 +62,43 @@ pub(crate) fn extract_patch_path_inventory_guarded(
|
||||
));
|
||||
}
|
||||
Ok(PatchPathInventory {
|
||||
primary_records,
|
||||
primary_paths: primary_paths.into_iter().collect(),
|
||||
effective_paths: effective_paths.into_iter().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
enum StagePathsHookPoint {
|
||||
BindRunner = 0,
|
||||
ResolvePhysicalCwd = 1,
|
||||
PreSpawn = 2,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
#[allow(clippy::type_complexity)]
|
||||
static STAGE_PATHS_HOOKS: std::cell::RefCell<[Option<Box<dyn FnOnce()>>; 3]> =
|
||||
std::cell::RefCell::new([None, None, None]);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
fn set_stage_paths_hook(point: StagePathsHookPoint, hook: impl FnOnce() + 'static) {
|
||||
STAGE_PATHS_HOOKS.with(|slots| {
|
||||
let prior = slots.borrow_mut()[point as usize].replace(Box::new(hook));
|
||||
assert!(prior.is_none());
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn run_stage_paths_hook(point: StagePathsHookPoint) {
|
||||
let hook = STAGE_PATHS_HOOKS.with(|slots| slots.borrow_mut()[point as usize].take());
|
||||
if let Some(hook) = hook {
|
||||
hook();
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract effective patch paths through a bound operation configuration.
|
||||
pub(crate) fn extract_effective_paths_from_patch_guarded(
|
||||
config: &GuardedGitConfig<'_>,
|
||||
@@ -73,13 +113,9 @@ fn git_apply_numstat_paths_guarded(
|
||||
patch_path: &Path,
|
||||
revert: bool,
|
||||
) -> io::Result<Vec<String>> {
|
||||
let mut command = config.apply_command()?;
|
||||
command.args(["--numstat", "-z"]);
|
||||
if revert {
|
||||
command.arg("-R");
|
||||
}
|
||||
command.arg("--").arg(patch_path);
|
||||
let output = command.output()?;
|
||||
#[cfg(test)]
|
||||
run_stage_paths_hook(StagePathsHookPoint::PreSpawn);
|
||||
let output = config.run_apply_numstat_path_inventory(revert, patch_path)?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
@@ -110,10 +146,11 @@ fn extract_paths_from_patch_from_cwd(diff_text: &str, cwd: &Path) -> Vec<String>
|
||||
let paths = (|| -> io::Result<Vec<String>> {
|
||||
let git = GitRunner::for_cwd_io(cwd)?;
|
||||
let requested_cwd = std::fs::canonicalize(cwd)?;
|
||||
let git_root = crate::get_git_repo_root(&requested_cwd)
|
||||
.ok_or_else(|| io::Error::other("not a Git repository"))?;
|
||||
let git_root = std::fs::canonicalize(git_root)?;
|
||||
let config = GuardedGitConfig::authorize(&git, &git_root, Vec::new())?;
|
||||
let authorized_cwd = crate::get_git_repo_root(&requested_cwd)
|
||||
.map(std::fs::canonicalize)
|
||||
.transpose()?
|
||||
.unwrap_or(requested_cwd);
|
||||
let config = GuardedGitConfig::authorize(&git, &authorized_cwd, Vec::new())?;
|
||||
extract_effective_paths_from_patch_guarded(&config, &patch_path, /*revert*/ false)
|
||||
})()
|
||||
.unwrap_or_default();
|
||||
@@ -261,9 +298,52 @@ fn invalid_windows_patch_component(component: &str) -> bool {
|
||||
|
||||
/// Stage only the files that actually exist on disk for the given diff.
|
||||
pub fn stage_paths(git_root: &Path, diff: &str) -> io::Result<()> {
|
||||
let git = GitRunner::for_cwd_io(git_root)?;
|
||||
git.ensure_repository_root_route(git_root)?;
|
||||
let canonical_root = std::fs::canonicalize(git_root)?;
|
||||
let immutable_traversal = !git_root.is_absolute()
|
||||
&& git_root.components().next().is_some()
|
||||
&& git_root
|
||||
.components()
|
||||
.all(|component| matches!(component, Component::CurDir | Component::ParentDir));
|
||||
let (guarded_root, bound_git) = if git_root.is_absolute() {
|
||||
(git_root.to_path_buf(), None)
|
||||
} else if immutable_traversal {
|
||||
let git = GitRunner::for_cwd_io(Path::new("."))?;
|
||||
#[cfg(test)]
|
||||
run_stage_paths_hook(StagePathsHookPoint::BindRunner);
|
||||
let resolve_immutable_traversal = || -> io::Result<PathBuf> {
|
||||
let mut root = std::fs::canonicalize(Path::new("."))?;
|
||||
for component in git_root.components() {
|
||||
match component {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
root.pop();
|
||||
}
|
||||
_ => unreachable!("non-traversal component"),
|
||||
}
|
||||
}
|
||||
Ok(root)
|
||||
};
|
||||
let initial_root = resolve_immutable_traversal()?;
|
||||
git.ensure_active_worktree_root(&initial_root)?;
|
||||
#[cfg(test)]
|
||||
run_stage_paths_hook(StagePathsHookPoint::ResolvePhysicalCwd);
|
||||
let live_root = resolve_immutable_traversal()?;
|
||||
git.ensure_active_worktree_root(&live_root)?;
|
||||
(live_root, Some(git))
|
||||
} else {
|
||||
(std::env::current_dir()?.join(git_root), None)
|
||||
};
|
||||
if !guarded_root.is_absolute() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"repository root route could not be anchored to an absolute path",
|
||||
));
|
||||
}
|
||||
let git = match bound_git {
|
||||
Some(git) => git,
|
||||
None => GitRunner::for_cwd_io(&guarded_root)?,
|
||||
};
|
||||
git.ensure_repository_root_route(&guarded_root)?;
|
||||
let canonical_root = std::fs::canonicalize(&guarded_root)?;
|
||||
let mut config = GuardedGitConfig::authorize(&git, &canonical_root, Vec::new())?;
|
||||
let (tmpdir, patch_path) = write_temp_patch(diff)?;
|
||||
let paths =
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use super::*;
|
||||
use crate::apply::ApplyGitRequest;
|
||||
use crate::apply::apply_git_patch;
|
||||
use crate::apply::safe_git_config_parts;
|
||||
use crate::exact_staging::StagePathsResult;
|
||||
use crate::exact_staging::update_index_exact_paths_from_apply;
|
||||
use crate::exact_staging::prepare_index_exact_paths_for_reverse_apply;
|
||||
use crate::exact_staging::update_index_exact_paths_standalone;
|
||||
use crate::guarded_config::config_source_authorization_count;
|
||||
use crate::guarded_config::reset_config_source_authorization_count;
|
||||
@@ -84,8 +83,8 @@ fn effective_paths(diff: &str, revert: bool) -> io::Result<Vec<String>> {
|
||||
}
|
||||
|
||||
fn best_effort_paths(diff: &str) -> Vec<String> {
|
||||
let repo = init_repo();
|
||||
extract_paths_from_patch_from_cwd(diff, repo.path())
|
||||
let cwd = tempfile::tempdir().expect("non-repository cwd");
|
||||
extract_paths_from_patch_from_cwd(diff, cwd.path())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -234,6 +233,324 @@ fn standalone_stage_paths_rejects_a_route_crossing_a_related_worktree() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
fn configure_and_commit_seed(root: &Path) {
|
||||
assert_eq!(run(root, &["git", "config", "user.email", "a@b.c"]).0, 0);
|
||||
assert_eq!(run(root, &["git", "config", "user.name", "Codex"]).0, 0);
|
||||
commit_seed(root);
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
fn linked_route_fixture() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let common = fixture.path().join("repository.git");
|
||||
let primary = fixture.path().join("primary");
|
||||
let linked = fixture.path().join("linked");
|
||||
let nested = primary.join("nested");
|
||||
let c = common.to_string_lossy().into_owned();
|
||||
let p = primary.to_string_lossy().into_owned();
|
||||
assert_eq!(run(fixture.path(), &["git", "init", "--bare", &c]).0, 0);
|
||||
let primary_add = run(
|
||||
fixture.path(),
|
||||
&["git", "--git-dir", &c, "worktree", "add", "--orphan", &p],
|
||||
);
|
||||
assert_eq!(primary_add.0, 0, "add primary: {primary_add:?}");
|
||||
configure_and_commit_seed(&primary);
|
||||
let primary_head = run(&primary, &["git", "rev-parse", "HEAD"]);
|
||||
assert_eq!(primary_head.0, 0, "resolve primary HEAD: {primary_head:?}");
|
||||
let primary_head = primary_head.1.trim().to_string();
|
||||
let l = linked.to_string_lossy().into_owned();
|
||||
let linked_add = run(
|
||||
fixture.path(),
|
||||
&[
|
||||
"git",
|
||||
"--git-dir",
|
||||
&c,
|
||||
"worktree",
|
||||
"add",
|
||||
"--detach",
|
||||
&l,
|
||||
&primary_head,
|
||||
],
|
||||
);
|
||||
assert_eq!(linked_add.0, 0, "add linked: {linked_add:?}");
|
||||
std::fs::create_dir_all(&nested).expect("nested primary directory");
|
||||
std::fs::write(linked.join("routed.txt"), "routed\n").expect("write linked file");
|
||||
(fixture, primary, linked, nested)
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
#[test]
|
||||
fn standalone_stage_paths_rejects_relative_related_worktree_routes_from_nested_cwd() {
|
||||
const TEST_NAME: &str = "patch_paths::tests::standalone_stage_paths_rejects_relative_related_worktree_routes_from_nested_cwd";
|
||||
const CWD_ALIAS_ENV: &str = "CODEX_GIT_UTILS_RELATIVE_ROUTE_CWD_ALIAS";
|
||||
const INDEPENDENT_ENV: &str = "CODEX_GIT_UTILS_RELATIVE_ROUTE_INDEPENDENT";
|
||||
const PRIMARY_ENV: &str = "CODEX_GIT_UTILS_RELATIVE_ROUTE_PRIMARY";
|
||||
const NESTED_ENV: &str = "CODEX_GIT_UTILS_RELATIVE_ROUTE_NESTED";
|
||||
|
||||
if std::env::var_os(NESTED_ENV).is_none() {
|
||||
let (fixture, primary, linked, nested) = linked_route_fixture();
|
||||
let deeper = nested.join("deeper");
|
||||
let independent = primary.join("independent");
|
||||
std::fs::create_dir_all(nested.join("routes")).expect("nested primary directories");
|
||||
std::fs::create_dir_all(&deeper).expect("deeper primary directory");
|
||||
std::fs::create_dir_all(&independent).expect("independent repository directory");
|
||||
assert_eq!(run(&independent, &["git", "init", "-q"]).0, 0);
|
||||
configure_and_commit_seed(&independent);
|
||||
let linked_child = linked.join("child");
|
||||
std::fs::create_dir_all(&linked_child).expect("linked child directory");
|
||||
for path in [
|
||||
"absolute-parent-control.txt",
|
||||
"deep-curdir-control.txt",
|
||||
"deep-parent-control.txt",
|
||||
"parent-control.txt",
|
||||
"physical-cwd-control.txt",
|
||||
"root-curdir-control.txt",
|
||||
] {
|
||||
std::fs::write(primary.join(path), "control\n").expect("write control file");
|
||||
}
|
||||
let _direct_route = create_dir_alias(&linked, &nested.join("linked-route"));
|
||||
let _nested_route = create_dir_alias(&linked, &nested.join("routes/linked-route"));
|
||||
let _direct_parent_route =
|
||||
create_dir_alias(&linked_child, &nested.join("linked-child-route"));
|
||||
let _nested_parent_route =
|
||||
create_dir_alias(&linked_child, &nested.join("routes/linked-child-route"));
|
||||
let cwd_alias = fixture.path().join("nested-cwd-route");
|
||||
let _cwd_alias = create_dir_alias(&nested, &cwd_alias);
|
||||
|
||||
run_isolated_test(
|
||||
TEST_NAME,
|
||||
&[
|
||||
(CWD_ALIAS_ENV, cwd_alias.as_os_str()),
|
||||
(INDEPENDENT_ENV, independent.as_os_str()),
|
||||
(PRIMARY_ENV, primary.as_os_str()),
|
||||
(NESTED_ENV, nested.as_os_str()),
|
||||
],
|
||||
);
|
||||
assert!(
|
||||
run(&linked, &["git", "diff", "--cached", "--name-only"])
|
||||
.1
|
||||
.is_empty(),
|
||||
"relative related-worktree routes must not stage the linked index"
|
||||
);
|
||||
assert_eq!(
|
||||
run(&primary, &["git", "diff", "--cached", "--name-only"]).1,
|
||||
"absolute-parent-control.txt\ndeep-curdir-control.txt\ndeep-parent-control.txt\nparent-control.txt\nphysical-cwd-control.txt\nroot-curdir-control.txt\n"
|
||||
);
|
||||
assert!(
|
||||
run(&independent, &["git", "diff", "--cached", "--name-only"])
|
||||
.1
|
||||
.is_empty(),
|
||||
"parent traversal must not mutate the nested independent index"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let primary = PathBuf::from(std::env::var_os(PRIMARY_ENV).expect("primary route"));
|
||||
let nested = PathBuf::from(std::env::var_os(NESTED_ENV).expect("nested route"));
|
||||
let independent =
|
||||
PathBuf::from(std::env::var_os(INDEPENDENT_ENV).expect("independent repository"));
|
||||
std::env::set_current_dir(&nested).expect("enter nested primary directory");
|
||||
let primary_before = git_index_bytes(&primary);
|
||||
let linked = primary.parent().expect("fixture").join("linked");
|
||||
let linked_before = git_index_bytes(&linked);
|
||||
for route in [
|
||||
".",
|
||||
"linked-route",
|
||||
"routes/linked-route",
|
||||
"linked-child-route/..",
|
||||
"routes/linked-child-route/./..",
|
||||
] {
|
||||
let error = stage_paths(Path::new(route), &new_file_diff("routed.txt"))
|
||||
.expect_err("unsafe relative route must reject");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{route}");
|
||||
assert_eq!(git_index_bytes(&primary), primary_before, "{route}");
|
||||
assert_eq!(git_index_bytes(&linked), linked_before, "{route}");
|
||||
}
|
||||
|
||||
stage_paths(Path::new(".."), &new_file_diff("parent-control.txt"))
|
||||
.expect("parent-only route from nested cwd selects the active root");
|
||||
|
||||
std::env::set_current_dir(nested.join("deeper")).expect("enter deeper primary directory");
|
||||
stage_paths(
|
||||
Path::new("../.."),
|
||||
&new_file_diff("deep-parent-control.txt"),
|
||||
)
|
||||
.expect("deeper parent-only route selects the active root");
|
||||
stage_paths(
|
||||
Path::new("./.././.."),
|
||||
&new_file_diff("deep-curdir-control.txt"),
|
||||
)
|
||||
.expect("deeper parent and current-directory route selects the active root");
|
||||
|
||||
let cwd_alias = PathBuf::from(std::env::var_os(CWD_ALIAS_ENV).expect("cwd alias"));
|
||||
std::env::set_current_dir(cwd_alias).expect("enter aliased nested cwd");
|
||||
stage_paths(Path::new(".."), &new_file_diff("physical-cwd-control.txt"))
|
||||
.expect("parent traversal is based on the captured physical cwd");
|
||||
|
||||
std::env::set_current_dir(&primary).expect("enter primary worktree root");
|
||||
stage_paths(Path::new("."), &new_file_diff("root-curdir-control.txt"))
|
||||
.expect("ordinary relative active-worktree route remains supported");
|
||||
|
||||
std::env::set_current_dir(&independent).expect("enter nested independent repository");
|
||||
let primary_before = git_index_bytes(&primary);
|
||||
let independent_before = git_index_bytes(&independent);
|
||||
let error = stage_paths(Path::new(".."), &new_file_diff("parent-control.txt"))
|
||||
.expect_err("parent traversal must not escape a nested independent repository");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(git_index_bytes(&primary), primary_before);
|
||||
assert_eq!(git_index_bytes(&independent), independent_before);
|
||||
stage_paths(&primary, &new_file_diff("absolute-parent-control.txt"))
|
||||
.expect("explicit outer route remains supported");
|
||||
assert_eq!(git_index_bytes(&independent), independent_before);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn standalone_stage_paths_rejects_actual_cwd_reparented_into_linked_worktree() {
|
||||
const TEST_NAME: &str = "patch_paths::tests::standalone_stage_paths_rejects_actual_cwd_reparented_into_linked_worktree";
|
||||
const MODE_ENV: &str = "CODEX_GIT_UTILS_REPARENTED_CWD_MODE";
|
||||
const PRIMARY_ENV: &str = "CODEX_GIT_UTILS_REPARENTED_CWD_PRIMARY";
|
||||
const NESTED_ENV: &str = "CODEX_GIT_UTILS_REPARENTED_CWD_NESTED";
|
||||
|
||||
if std::env::var_os(MODE_ENV).is_none() {
|
||||
for mode in ["pathname", "aba", "reparent", "combined", "prespawn"] {
|
||||
let (_fixture, primary, linked, nested) = linked_route_fixture();
|
||||
if mode == "pathname" {
|
||||
std::fs::create_dir_all(linked.join("child")).expect("linked child directory");
|
||||
}
|
||||
|
||||
run_isolated_test(
|
||||
TEST_NAME,
|
||||
&[
|
||||
(MODE_ENV, OsStr::new(mode)),
|
||||
(PRIMARY_ENV, primary.as_os_str()),
|
||||
(NESTED_ENV, nested.as_os_str()),
|
||||
],
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let mode = std::env::var(MODE_ENV).expect("reparent mode");
|
||||
let primary = PathBuf::from(std::env::var_os(PRIMARY_ENV).expect("primary route"));
|
||||
let nested = PathBuf::from(std::env::var_os(NESTED_ENV).expect("nested route"));
|
||||
let linked = primary.parent().expect("fixture").join("linked");
|
||||
let moved_primary = primary.parent().expect("fixture").join("primary-moved");
|
||||
std::env::set_current_dir(&nested).expect("enter nested primary directory");
|
||||
let index_path = |root: &Path| {
|
||||
let output = run(root, &["git", "rev-parse", "--git-path", "index"]);
|
||||
assert_eq!(output.0, 0, "resolve index path: {output:?}");
|
||||
let path = PathBuf::from(output.1.trim());
|
||||
let path = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
root.join(path)
|
||||
};
|
||||
std::fs::canonicalize(path).expect("canonical index path")
|
||||
};
|
||||
let primary_index = index_path(&primary);
|
||||
let linked_index = index_path(&linked);
|
||||
let primary_before = std::fs::read(&primary_index).expect("read primary index");
|
||||
let linked_before = std::fs::read(&linked_index).expect("read linked index");
|
||||
let replacement = std::rc::Rc::new(std::cell::RefCell::new(None));
|
||||
if matches!(mode.as_str(), "combined" | "prespawn") {
|
||||
let replacement_for_hook = std::rc::Rc::clone(&replacement);
|
||||
let primary_for_hook = primary.clone();
|
||||
let linked_for_hook = linked;
|
||||
let moved_primary_for_hook = moved_primary;
|
||||
let primary_admin = PathBuf::from(
|
||||
run(&primary, &["git", "rev-parse", "--absolute-git-dir"])
|
||||
.1
|
||||
.trim(),
|
||||
);
|
||||
let hook = move || {
|
||||
std::fs::rename(&primary_for_hook, &moved_primary_for_hook)
|
||||
.expect("rename initial repository root");
|
||||
std::fs::write(
|
||||
primary_admin.join("gitdir"),
|
||||
format!("{}\n", moved_primary_for_hook.join(".git").display()),
|
||||
)
|
||||
.expect("update moved primary worktree backlink");
|
||||
std::fs::rename(
|
||||
moved_primary_for_hook.join("nested"),
|
||||
linked_for_hook.join("child"),
|
||||
)
|
||||
.expect("reparent actual cwd into linked worktree");
|
||||
replacement_for_hook
|
||||
.borrow_mut()
|
||||
.replace(create_dir_alias(&linked_for_hook, &primary_for_hook));
|
||||
};
|
||||
set_stage_paths_hook(
|
||||
if mode == "combined" {
|
||||
StagePathsHookPoint::BindRunner
|
||||
} else {
|
||||
StagePathsHookPoint::PreSpawn
|
||||
},
|
||||
hook,
|
||||
);
|
||||
} else if mode == "aba" {
|
||||
let primary_for_hook = primary;
|
||||
let linked_for_hook = linked;
|
||||
let moved_primary_for_hook = moved_primary;
|
||||
set_stage_paths_hook(StagePathsHookPoint::BindRunner, move || {
|
||||
std::fs::rename(&primary_for_hook, &moved_primary_for_hook).expect("rename root");
|
||||
drop(create_dir_alias(&linked_for_hook, &primary_for_hook));
|
||||
std::fs::rename(&moved_primary_for_hook, &primary_for_hook).expect("restore root");
|
||||
});
|
||||
} else if mode == "reparent" {
|
||||
let nested_for_hook = nested;
|
||||
let linked_child_for_hook = linked.join("child");
|
||||
set_stage_paths_hook(StagePathsHookPoint::ResolvePhysicalCwd, move || {
|
||||
std::fs::rename(&nested_for_hook, &linked_child_for_hook)
|
||||
.expect("reparent actual cwd into linked worktree");
|
||||
});
|
||||
} else {
|
||||
let replacement_for_hook = std::rc::Rc::clone(&replacement);
|
||||
let nested_for_hook = nested;
|
||||
let moved_nested_for_hook = primary.join("nested-moved");
|
||||
let linked_child_for_hook = linked.join("child");
|
||||
set_stage_paths_hook(StagePathsHookPoint::ResolvePhysicalCwd, move || {
|
||||
std::fs::rename(&nested_for_hook, &moved_nested_for_hook)
|
||||
.expect("rename actual cwd directory");
|
||||
replacement_for_hook
|
||||
.borrow_mut()
|
||||
.replace(create_dir_alias(&linked_child_for_hook, &nested_for_hook));
|
||||
});
|
||||
}
|
||||
|
||||
let result = stage_paths(Path::new(".."), &new_file_diff("routed.txt"));
|
||||
assert_eq!(
|
||||
std::fs::read(primary_index).expect("reread primary index"),
|
||||
primary_before
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(linked_index).expect("reread linked index"),
|
||||
linked_before
|
||||
);
|
||||
if matches!(mode.as_str(), "pathname" | "aba") {
|
||||
result.expect("a restored or renamed pathname must remain bound to the origin repository");
|
||||
} else {
|
||||
let error = result.expect_err("reparented cwd must fail closed");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
if matches!(mode.as_str(), "combined" | "prespawn") {
|
||||
let expected = if mode == "combined" {
|
||||
"does not match runner repository"
|
||||
} else {
|
||||
"changed before Git launch"
|
||||
};
|
||||
let message = error.to_string();
|
||||
let accepted_earlier_route_refusal = mode == "prespawn"
|
||||
&& message.contains("no longer resolves within the selected worktree");
|
||||
assert!(
|
||||
message.contains(expected) || accepted_earlier_route_refusal,
|
||||
"{mode}: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
drop(replacement.borrow_mut().take());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_paths_cover_supported_patch_headers() {
|
||||
let cases = [
|
||||
@@ -300,6 +617,31 @@ fn effective_paths_cover_supported_patch_headers() {
|
||||
assert_eq!(nul_rename_paths, vec!["new name.txt".to_string()]);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn best_effort_parser_returns_empty_for_process_relative_primary_config() {
|
||||
const TEST_NAME: &str =
|
||||
"patch_paths::tests::best_effort_parser_returns_empty_for_process_relative_primary_config";
|
||||
if std::env::var_os("CODEX_GIT_UTILS_PATH_ENV_CHILD").is_none() {
|
||||
run_isolated_test(
|
||||
TEST_NAME,
|
||||
&[
|
||||
(
|
||||
"GIT_CONFIG_GLOBAL",
|
||||
OsStr::new("/proc/self/cwd/codex-process-relative.gitconfig"),
|
||||
),
|
||||
("GIT_CONFIG_NOSYSTEM", OsStr::new("1")),
|
||||
],
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
extract_paths_from_patch(&new_file_diff("safe.txt")),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_paths_follow_git_for_mismatched_headers() {
|
||||
let mismatch = "diff --git a/safe.txt b/safe.txt\n--- a/nested/file.txt\n+++ b/nested/file.txt\n@@ -1 +1 @@\n-old\n+new\n";
|
||||
@@ -700,18 +1042,117 @@ fn exact_stage(root: &Path, paths: &[&str], content_filter_paths: &[&str]) -> St
|
||||
.expect("run exact staging primitive")
|
||||
}
|
||||
|
||||
fn stage_effective_paths(
|
||||
git: &GitRunner,
|
||||
root: &Path,
|
||||
paths: &[String],
|
||||
legacy_config_args: &[String],
|
||||
) -> io::Result<()> {
|
||||
let _ = legacy_config_args;
|
||||
fn stage_effective_paths(git: &GitRunner, root: &Path, paths: &[String]) -> io::Result<()> {
|
||||
let canonical_root = std::fs::canonicalize(root)?;
|
||||
let mut config = GuardedGitConfig::authorize(git, &canonical_root, Vec::new())?;
|
||||
stage_effective_paths_standalone(&mut config, paths)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_staging_refuses_sparse_excluded_peer_before_eligible_mutation() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::create_dir_all(root.join("inside")).expect("create included directory");
|
||||
std::fs::create_dir_all(root.join("outside")).expect("create excluded directory");
|
||||
std::fs::write(root.join("inside/base.txt"), "inside\n").expect("write included base");
|
||||
std::fs::write(root.join("outside/base.txt"), "outside\n").expect("write excluded base");
|
||||
assert_eq!(run(root, &["git", "add", "."]).0, 0);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "sparse base"]).0, 0);
|
||||
assert_eq!(
|
||||
run(root, &["git", "sparse-checkout", "init", "--cone"]).0,
|
||||
0
|
||||
);
|
||||
assert_eq!(run(root, &["git", "sparse-checkout", "set", "inside"]).0, 0);
|
||||
std::fs::write(root.join("inside/eligible.txt"), "eligible\n").expect("write eligible path");
|
||||
std::fs::create_dir_all(root.join("outside")).expect("recreate excluded directory");
|
||||
std::fs::write(root.join("outside/base.txt"), "changed outside\n")
|
||||
.expect("modify sparse-excluded tracked path");
|
||||
let paths = vec![
|
||||
"inside/eligible.txt".to_string(),
|
||||
"outside/base.txt".to_string(),
|
||||
];
|
||||
let before = git_index_bytes(root);
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
|
||||
let canonical_root = std::fs::canonicalize(root).expect("canonical root");
|
||||
let mut config =
|
||||
GuardedGitConfig::authorize(&git, &canonical_root, Vec::new()).expect("authorization");
|
||||
config
|
||||
.authorize_filter_paths(&paths)
|
||||
.expect("apply filter snapshot");
|
||||
let error = prepare_index_exact_paths_for_reverse_apply(&mut config, &paths, &paths)
|
||||
.err()
|
||||
.expect("sparse-excluded peer must refuse the whole reverse staging plan");
|
||||
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
assert!(error.to_string().contains("sparse-checkout"), "{error}");
|
||||
assert_eq!(git_index_bytes(root), before);
|
||||
assert!(
|
||||
run(root, &["git", "diff", "--cached", "--", "outside/base.txt"])
|
||||
.1
|
||||
.is_empty(),
|
||||
"sparse-excluded tracked path must retain its prior index entry"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_staging_late_filter_refusal_precedes_eligible_index_mutation() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join(".gitattributes"), "ordinary.txt filter=fresh\n")
|
||||
.expect("write attributes");
|
||||
std::fs::write(root.join("ordinary.txt"), "base\n").expect("write ordinary base");
|
||||
std::fs::write(root.join("peer.txt"), "base\n").expect("write peer base");
|
||||
assert_eq!(
|
||||
run(
|
||||
root,
|
||||
&["git", "add", ".gitattributes", "ordinary.txt", "peer.txt"]
|
||||
)
|
||||
.0,
|
||||
0
|
||||
);
|
||||
assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0);
|
||||
std::fs::write(root.join("ordinary.txt"), "changed\n").expect("modify ordinary path");
|
||||
std::fs::write(root.join("peer.txt"), "changed\n").expect("modify peer path");
|
||||
let paths = vec!["ordinary.txt".to_string(), "peer.txt".to_string()];
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
|
||||
let canonical_root = std::fs::canonicalize(root).expect("canonical root");
|
||||
reset_filter_policy_counts();
|
||||
let mut config =
|
||||
GuardedGitConfig::authorize(&git, &canonical_root, Vec::new()).expect("authorization");
|
||||
config
|
||||
.authorize_filter_paths(&paths)
|
||||
.expect("initial apply filter snapshot");
|
||||
assert_eq!(
|
||||
run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"config",
|
||||
"filter.fresh.clean",
|
||||
"git config codex.stage-filter-ran true && git hash-object --stdin",
|
||||
],
|
||||
)
|
||||
.0,
|
||||
0
|
||||
);
|
||||
let before = git_index_bytes(root);
|
||||
|
||||
let error = prepare_index_exact_paths_for_reverse_apply(&mut config, &paths, &paths)
|
||||
.err()
|
||||
.expect("fresh selected filter must refuse before staging eligible paths");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
assert!(error.to_string().contains("filter"), "{error}");
|
||||
assert_eq!(filter_policy_read_count(), 2);
|
||||
assert_eq!(git_index_bytes(root), before);
|
||||
assert_ne!(
|
||||
run(root, &["git", "config", "--get", "codex.stage-filter-ran"]).0,
|
||||
0,
|
||||
"refused filter helper must not execute"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_stage_paths_uses_one_source_authorization_and_one_filter_read() {
|
||||
if std::env::var_os("CODEX_GIT_UTILS_PATH_ENV_CHILD").is_none() {
|
||||
@@ -744,7 +1185,7 @@ fn standalone_stage_paths_uses_one_source_authorization_and_one_filter_read() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composed_staging_freshly_observes_a_new_clean_driver_and_attribute() {
|
||||
fn reverse_staging_freshly_observes_a_new_clean_driver_and_attribute() {
|
||||
if std::env::var_os("CODEX_GIT_UTILS_PATH_ENV_CHILD").is_none() {
|
||||
let config_dir = tempfile::tempdir().expect("config tempdir");
|
||||
let global_config = config_dir.path().join("global.gitconfig");
|
||||
@@ -752,7 +1193,7 @@ fn composed_staging_freshly_observes_a_new_clean_driver_and_attribute() {
|
||||
std::fs::write(&global_config, "").expect("empty global config");
|
||||
std::fs::write(&system_config, "").expect("empty system config");
|
||||
run_isolated_test(
|
||||
"patch_paths::tests::composed_staging_freshly_observes_a_new_clean_driver_and_attribute",
|
||||
"patch_paths::tests::reverse_staging_freshly_observes_a_new_clean_driver_and_attribute",
|
||||
&[
|
||||
("GIT_CONFIG_GLOBAL", global_config.as_os_str()),
|
||||
("GIT_CONFIG_SYSTEM", system_config.as_os_str()),
|
||||
@@ -794,12 +1235,13 @@ fn composed_staging_freshly_observes_a_new_clean_driver_and_attribute() {
|
||||
std::fs::write(root.join(".gitattributes"), "file.txt filter=fresh\n")
|
||||
.expect("select fresh filter");
|
||||
|
||||
let error = update_index_exact_paths_from_apply(
|
||||
let error = prepare_index_exact_paths_for_reverse_apply(
|
||||
&mut config,
|
||||
&["file.txt".to_string()],
|
||||
&["file.txt".to_string()],
|
||||
)
|
||||
.expect_err("fresh clean driver must refuse");
|
||||
.err()
|
||||
.expect("fresh clean driver must refuse");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
assert_eq!(config_source_authorization_count(), 1);
|
||||
assert_eq!(filter_policy_read_count(), 2);
|
||||
@@ -812,7 +1254,7 @@ fn composed_staging_freshly_observes_a_new_clean_driver_and_attribute() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composed_staging_required_read_ignores_the_apply_overlay_and_is_fresh() {
|
||||
fn reverse_staging_required_read_ignores_the_apply_overlay_and_is_fresh() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("file.txt"), "base\n").expect("write base file");
|
||||
@@ -850,12 +1292,13 @@ fn composed_staging_required_read_ignores_the_apply_overlay_and_is_fresh() {
|
||||
0
|
||||
);
|
||||
|
||||
let error = update_index_exact_paths_from_apply(
|
||||
let error = prepare_index_exact_paths_for_reverse_apply(
|
||||
&mut config,
|
||||
&["file.txt".to_string()],
|
||||
&["file.txt".to_string()],
|
||||
)
|
||||
.expect_err("fresh required=true must refuse");
|
||||
.err()
|
||||
.expect("fresh required=true must refuse");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
assert_eq!(config_source_authorization_count(), 1);
|
||||
assert_eq!(filter_policy_read_count(), 2);
|
||||
@@ -868,7 +1311,7 @@ fn composed_staging_required_read_ignores_the_apply_overlay_and_is_fresh() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composed_exact_staging_refuses_requested_and_mapped_paths_outside_apply_universe() {
|
||||
fn reverse_exact_staging_refuses_requested_and_mapped_paths_outside_apply_universe() {
|
||||
let requested_repo = init_repo();
|
||||
let requested_root = requested_repo.path();
|
||||
let requested_git = GitRunner::for_cwd_io(requested_root).expect("trusted Git");
|
||||
@@ -881,12 +1324,13 @@ fn composed_exact_staging_refuses_requested_and_mapped_paths_outside_apply_unive
|
||||
requested_config
|
||||
.authorize_filter_paths(&["allowed.txt".to_string()])
|
||||
.expect("apply snapshot");
|
||||
let requested_error = update_index_exact_paths_from_apply(
|
||||
let requested_error = prepare_index_exact_paths_for_reverse_apply(
|
||||
&mut requested_config,
|
||||
&["allowed.txt".to_string(), "outside.txt".to_string()],
|
||||
&["outside.txt".to_string()],
|
||||
)
|
||||
.expect_err("requested off-universe path must refuse");
|
||||
.err()
|
||||
.expect("requested off-universe path must refuse");
|
||||
assert_eq!(requested_error.kind(), io::ErrorKind::PermissionDenied);
|
||||
|
||||
let mapped_repo = init_repo();
|
||||
@@ -909,17 +1353,18 @@ fn composed_exact_staging_refuses_requested_and_mapped_paths_outside_apply_unive
|
||||
mapped_config
|
||||
.authorize_filter_paths(&["file.txt".to_string()])
|
||||
.expect("narrow apply snapshot");
|
||||
let mapped_error = update_index_exact_paths_from_apply(
|
||||
let mapped_error = prepare_index_exact_paths_for_reverse_apply(
|
||||
&mut mapped_config,
|
||||
&["File.txt".to_string(), "file.txt".to_string()],
|
||||
&["file.txt".to_string()],
|
||||
)
|
||||
.expect_err("mapped off-universe path must refuse");
|
||||
.err()
|
||||
.expect("mapped off-universe path must refuse");
|
||||
assert_eq!(mapped_error.kind(), io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composed_exact_staging_refuses_zero_or_two_prior_snapshots_even_when_empty() {
|
||||
fn reverse_exact_staging_refuses_zero_or_two_prior_snapshots_even_when_empty() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
|
||||
@@ -927,8 +1372,9 @@ fn composed_exact_staging_refuses_zero_or_two_prior_snapshots_even_when_empty()
|
||||
|
||||
let mut zero =
|
||||
GuardedGitConfig::authorize(&git, &canonical_root, Vec::new()).expect("authorization");
|
||||
let error = update_index_exact_paths_from_apply(&mut zero, &[], &[])
|
||||
.expect_err("zero snapshots must refuse");
|
||||
let error = prepare_index_exact_paths_for_reverse_apply(&mut zero, &[], &[])
|
||||
.err()
|
||||
.expect("zero snapshots must refuse");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
|
||||
let mut two =
|
||||
@@ -936,8 +1382,9 @@ fn composed_exact_staging_refuses_zero_or_two_prior_snapshots_even_when_empty()
|
||||
two.authorize_filter_paths(&[]).expect("apply snapshot");
|
||||
two.authorize_git_add_filter_paths(&[])
|
||||
.expect("Git-add snapshot");
|
||||
let error = update_index_exact_paths_from_apply(&mut two, &[], &[])
|
||||
.expect_err("two snapshots must refuse");
|
||||
let error = prepare_index_exact_paths_for_reverse_apply(&mut two, &[], &[])
|
||||
.err()
|
||||
.expect("two snapshots must refuse");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
@@ -1287,7 +1734,6 @@ fn ignored_untracked_path_returns_nonzero_without_partial_staging() {
|
||||
&git,
|
||||
root,
|
||||
&["ignored.txt".to_string(), "ordinary.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect("public staging remains best effort for ignored paths");
|
||||
assert!(
|
||||
@@ -1410,13 +1856,8 @@ fn exact_staging_refuses_skip_and_assume_unchanged_without_mutation() {
|
||||
assert_eq!(git_index_bytes(root), before);
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
|
||||
stage_effective_paths(
|
||||
&git,
|
||||
root,
|
||||
&["existing.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect("public staging remains best effort for skip-worktree paths");
|
||||
stage_effective_paths(&git, root, &["existing.txt".to_string()])
|
||||
.expect("public staging remains best effort for skip-worktree paths");
|
||||
assert_eq!(git_index_bytes(root), before);
|
||||
|
||||
assert_eq!(
|
||||
@@ -2148,13 +2589,8 @@ fn staging_rejects_global_lfs_filter_without_running_it() {
|
||||
std::env::var_os("CODEX_GIT_UTILS_TARGET_REPO").expect("target repository"),
|
||||
);
|
||||
let git = GitRunner::for_cwd_io(&root).expect("trusted Git");
|
||||
let error = stage_effective_paths(
|
||||
&git,
|
||||
&root,
|
||||
&["file.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect_err("reject global Git LFS filter");
|
||||
let error = stage_effective_paths(&git, &root, &["file.txt".to_string()])
|
||||
.expect_err("reject global Git LFS filter");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
return;
|
||||
}
|
||||
@@ -2219,25 +2655,15 @@ fn staging_rejects_selected_process_but_allows_smudge_only_filter() {
|
||||
let process_repo = init_repo_with_selected_filter("filter.selected.process");
|
||||
let process_root = process_repo.path();
|
||||
let process_git = GitRunner::for_cwd_io(process_root).expect("trusted Git");
|
||||
let error = stage_effective_paths(
|
||||
&process_git,
|
||||
process_root,
|
||||
&["file.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect_err("reject selected process filter");
|
||||
let error = stage_effective_paths(&process_git, process_root, &["file.txt".to_string()])
|
||||
.expect_err("reject selected process filter");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
|
||||
let smudge_repo = init_repo_with_selected_filter("filter.selected.smudge");
|
||||
let smudge_root = smudge_repo.path();
|
||||
let smudge_git = GitRunner::for_cwd_io(smudge_root).expect("trusted Git");
|
||||
stage_effective_paths(
|
||||
&smudge_git,
|
||||
smudge_root,
|
||||
&["file.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect("smudge-only filters do not run during staging");
|
||||
stage_effective_paths(&smudge_git, smudge_root, &["file.txt".to_string()])
|
||||
.expect("smudge-only filters do not run during staging");
|
||||
let (code, staged, stderr) = run(smudge_root, &["git", "diff", "--cached", "--name-only"]);
|
||||
assert_eq!(code, 0, "read staged paths: {stderr}");
|
||||
assert_eq!(staged, "file.txt\n");
|
||||
@@ -2279,13 +2705,8 @@ fn staging_neutralizes_off_path_racy_filters_without_changing_their_index_entry(
|
||||
std::fs::write(guarded_root.join("target.txt"), "new target\n")
|
||||
.expect("modify guarded target");
|
||||
let git = GitRunner::for_cwd_io(guarded_root).expect("trusted Git");
|
||||
stage_effective_paths(
|
||||
&git,
|
||||
guarded_root,
|
||||
&["target.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect("stage with off-path filters neutralized");
|
||||
stage_effective_paths(&git, guarded_root, &["target.txt".to_string()])
|
||||
.expect("stage with off-path filters neutralized");
|
||||
|
||||
assert!(
|
||||
!guarded.marker.exists(),
|
||||
@@ -2331,8 +2752,7 @@ fn staging_allows_selected_symlink_while_neutralizing_off_path_filters() {
|
||||
let outside_before = index_entry(root, "outside.txt");
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
|
||||
stage_effective_paths(&git, root, &["link".to_string()], &safe_git_config_parts())
|
||||
.expect("stage selected symlink");
|
||||
stage_effective_paths(&git, root, &["link".to_string()]).expect("stage selected symlink");
|
||||
|
||||
assert!(
|
||||
!fixture.marker.exists(),
|
||||
@@ -2400,12 +2820,7 @@ fn staging_allows_optional_smudge_only_but_refuses_required_or_malformed_smudge(
|
||||
.expect("modify selected target");
|
||||
let before = git_index_bytes(root);
|
||||
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
|
||||
let result = stage_effective_paths(
|
||||
&git,
|
||||
root,
|
||||
&["selected.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
);
|
||||
let result = stage_effective_paths(&git, root, &["selected.txt".to_string()]);
|
||||
|
||||
assert!(
|
||||
!fixture.marker.exists(),
|
||||
@@ -2472,13 +2887,8 @@ fn optional_smudge_target_does_not_mask_a_later_clean_target() {
|
||||
let before = git_index_bytes(root);
|
||||
|
||||
let git = GitRunner::for_cwd_io(root).expect("trusted Git");
|
||||
let error = stage_effective_paths(
|
||||
&git,
|
||||
root,
|
||||
&["a.txt".to_string(), "z.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect_err("reject the selected clean target after optional smudge");
|
||||
let error = stage_effective_paths(&git, root, &["a.txt".to_string(), "z.txt".to_string()])
|
||||
.expect_err("reject the selected clean target after optional smudge");
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
|
||||
assert_eq!(git_index_bytes(root), before);
|
||||
}
|
||||
@@ -2521,7 +2931,6 @@ fn staging_filter_probe_uses_only_existing_non_directory_leaves() {
|
||||
"deleted.txt".to_string(),
|
||||
"kept.txt".to_string(),
|
||||
],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect("probe only the surviving staging leaf");
|
||||
|
||||
@@ -2565,7 +2974,6 @@ fn staging_skips_filter_probe_when_no_leaf_will_be_staged() {
|
||||
&git,
|
||||
root,
|
||||
&["missing.txt".to_string(), "deleted.txt".to_string()],
|
||||
&safe_git_config_parts(),
|
||||
)
|
||||
.expect("skip staging when every effective leaf is absent");
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ use route_walker::RouteObservationSnapshot;
|
||||
#[cfg(windows)]
|
||||
use route_walker::invalid_data;
|
||||
use route_walker::observe_route;
|
||||
use route_walker::route_contains_process_relative_procfs_path;
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) use windows_path::windows_authority_path_is_ambiguous;
|
||||
#[cfg(any(windows, test))]
|
||||
@@ -64,6 +65,13 @@ impl RepositoryRouteBoundaries {
|
||||
&self.metadata_identities,
|
||||
)? != CandidateBoundary::Outside)
|
||||
}
|
||||
|
||||
pub(crate) fn route_contains_process_relative_procfs_path(
|
||||
&self,
|
||||
route: &Path,
|
||||
) -> io::Result<bool> {
|
||||
route_contains_process_relative_procfs_path(route)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn repository_route_boundaries(
|
||||
|
||||
@@ -107,6 +107,82 @@ fn symlink_route_hops(path: &Path) -> io::Result<Vec<SymlinkRouteHop>> {
|
||||
Ok(hops)
|
||||
}
|
||||
|
||||
/// Detect Linux procfs routes whose target can differ in a later Git process.
|
||||
///
|
||||
/// Existing procfs-hosted symlinks are process-dependent, and missing procfs
|
||||
/// descendants can materialize when the Git child's PID or descriptors exist.
|
||||
pub(super) fn route_contains_process_relative_procfs_path(path: &Path) -> io::Result<bool> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let hops = symlink_route_hops(path)?;
|
||||
for hop in &hops {
|
||||
if symlink_is_on_procfs(&hop.entry)? {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
if missing_descendant_is_below_procfs(path)? {
|
||||
return Ok(true);
|
||||
}
|
||||
for hop in hops {
|
||||
if missing_descendant_is_below_procfs(&hop.target)?
|
||||
|| missing_descendant_is_below_procfs(&hop.projected)?
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let _ = path;
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn symlink_is_on_procfs(path: &Path) -> io::Result<bool> {
|
||||
filesystem_is_procfs(
|
||||
path,
|
||||
rustix::fs::OFlags::PATH | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn missing_descendant_is_below_procfs(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(_) => return Ok(false),
|
||||
Err(error) if is_missing_path_error(&error) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
for ancestor in path.ancestors().skip(1) {
|
||||
match std::fs::symlink_metadata(ancestor) {
|
||||
Ok(_) => match filesystem_is_procfs(
|
||||
ancestor,
|
||||
rustix::fs::OFlags::PATH | rustix::fs::OFlags::CLOEXEC,
|
||||
) {
|
||||
Ok(is_procfs) => return Ok(is_procfs),
|
||||
Err(error) if is_missing_path_error(&error) => {}
|
||||
Err(error) => return Err(error),
|
||||
},
|
||||
Err(error) if is_missing_path_error(&error) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(invalid_data("authority path has no existing ancestor"))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn filesystem_is_procfs(path: &Path, flags: rustix::fs::OFlags) -> io::Result<bool> {
|
||||
let fd = rustix::fs::open(path, flags, rustix::fs::Mode::empty()).map_err(io::Error::from)?;
|
||||
let filesystem = rustix::fs::fstatfs(&fd).map_err(io::Error::from)?;
|
||||
Ok(filesystem.f_type == rustix::fs::PROC_SUPER_MAGIC)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn is_missing_path_error(error: &io::Error) -> bool {
|
||||
matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
|
||||
)
|
||||
}
|
||||
|
||||
fn collect_symlink_route_hops(
|
||||
path: &Path,
|
||||
depth: usize,
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::path::Path;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::read_link_if_symlink;
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::route_contains_process_relative_procfs_path;
|
||||
|
||||
#[test]
|
||||
fn ordinary_paths_are_not_treated_as_failed_symlink_reads() {
|
||||
@@ -16,3 +22,59 @@ fn ordinary_paths_are_not_treated_as_failed_symlink_reads() {
|
||||
);
|
||||
assert_eq!(read_link_if_symlink(&file).expect("ordinary file"), None);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn process_relative_procfs_detection_follows_aliases_without_rejecting_ordinary_paths() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let external = fixture.path().join("external");
|
||||
let ordinary_alias = fixture.path().join("ordinary-alias");
|
||||
let procfs_alias = fixture.path().join("procfs-alias");
|
||||
let procfs_root_alias = fixture.path().join("procfs-root-alias");
|
||||
let chained_alias = fixture.path().join("chained-alias");
|
||||
let literal = fixture.path().join("proc/self/cwd/config");
|
||||
std::fs::create_dir_all(&external).expect("external directory");
|
||||
std::fs::create_dir_all(literal.parent().expect("literal parent"))
|
||||
.expect("literal directories");
|
||||
std::fs::write(&literal, "[safe]\n").expect("literal config");
|
||||
symlink(&external, &ordinary_alias).expect("ordinary alias");
|
||||
symlink("/proc/self/cwd", &procfs_alias).expect("procfs alias");
|
||||
symlink("/proc", &procfs_root_alias).expect("procfs root alias");
|
||||
symlink("procfs-alias", &chained_alias).expect("chained alias");
|
||||
|
||||
let mut procfs_paths = vec![
|
||||
PathBuf::from("/proc/self/cwd/missing-config"),
|
||||
PathBuf::from("/proc/thread-self/cwd/missing-config"),
|
||||
PathBuf::from("/proc/self/fd/1048575/missing-config"),
|
||||
PathBuf::from("/proc/self/exe"),
|
||||
PathBuf::from(format!("/proc/{}/cwd/missing-config", std::process::id())),
|
||||
PathBuf::from("/proc/4294967295/cwd/missing-config"),
|
||||
procfs_alias.join("missing-config"),
|
||||
procfs_root_alias.join("4294967295/cwd/missing-config"),
|
||||
chained_alias.join("missing-config"),
|
||||
];
|
||||
if Path::new("/dev/fd").exists() {
|
||||
procfs_paths.push(PathBuf::from("/dev/fd/1048575/missing-config"));
|
||||
}
|
||||
for path in procfs_paths {
|
||||
assert!(
|
||||
route_contains_process_relative_procfs_path(&path).expect("inspect procfs route"),
|
||||
"expected process-relative procfs route in {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
|
||||
for path in [
|
||||
PathBuf::from("/proc/version"),
|
||||
ordinary_alias.join("missing-config"),
|
||||
literal,
|
||||
] {
|
||||
assert!(
|
||||
!route_contains_process_relative_procfs_path(&path).expect("inspect ordinary route"),
|
||||
"unexpected process-relative procfs route in {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use same_file::Handle;
|
||||
|
||||
use crate::errors::GitReadError;
|
||||
use crate::git_config::path_is_within;
|
||||
use crate::path_authority::RepositoryRouteBoundaries;
|
||||
@@ -25,11 +27,37 @@ use super::resolve_repository_metadata;
|
||||
|
||||
mod policy;
|
||||
|
||||
fn open_active_worktree_identity(path: &Path) -> io::Result<Handle> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::fs::OpenOptions;
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
|
||||
|
||||
// Deliberately omit FILE_SHARE_DELETE so the repository root cannot
|
||||
// be renamed or replaced between validation and the guarded child.
|
||||
let directory = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
||||
.open(path)?;
|
||||
Handle::from_file(directory)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
Handle::from_path(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Repository and filesystem authority retained for the lifetime of one
|
||||
/// trusted Git runner.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RepositoryAuthority {
|
||||
active_worktree_root: PathBuf,
|
||||
active_worktree_identity: Option<Handle>,
|
||||
roots: Vec<PathBuf>,
|
||||
worktree_roots: Vec<PathBuf>,
|
||||
common_dirs: Vec<PathBuf>,
|
||||
@@ -58,8 +86,11 @@ impl RepositoryAuthority {
|
||||
let worktree_root = crate::get_git_repo_root(&canonical_cwd)
|
||||
.and_then(|root| std::fs::canonicalize(root).ok())
|
||||
.unwrap_or_else(|| canonical_cwd.clone());
|
||||
let active_worktree_identity = open_active_worktree_identity(&worktree_root)
|
||||
.map_err(|error| invalid_metadata(&worktree_root, error))?;
|
||||
let mut authority = Self {
|
||||
active_worktree_root: worktree_root.clone(),
|
||||
active_worktree_identity: Some(active_worktree_identity),
|
||||
roots: Vec::new(),
|
||||
worktree_roots: Vec::new(),
|
||||
common_dirs: Vec::new(),
|
||||
@@ -123,6 +154,7 @@ impl RepositoryAuthority {
|
||||
}
|
||||
|
||||
pub(crate) fn revalidate_active_repository_metadata(&self) -> io::Result<()> {
|
||||
self.revalidate_active_worktree_identity()?;
|
||||
let Some(expected) = &self.active_metadata else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -148,11 +180,15 @@ impl RepositoryAuthority {
|
||||
|
||||
pub(crate) fn ensure_active_worktree_root(&self, root: &Path) -> io::Result<()> {
|
||||
let canonical_root = std::fs::canonicalize(root)?;
|
||||
let same_root = canonical_root == self.active_worktree_root
|
||||
|| same_file::is_same_file(&canonical_root, &self.active_worktree_root)?;
|
||||
let same_root = if let Some(expected) = &self.active_worktree_identity {
|
||||
Handle::from_path(&canonical_root)? == *expected
|
||||
} else {
|
||||
canonical_root == self.active_worktree_root
|
||||
|| same_file::is_same_file(&canonical_root, &self.active_worktree_root)?
|
||||
};
|
||||
if !same_root {
|
||||
return Err(authority_refusal(format!(
|
||||
"guarded Git repository root {} does not match runner repository {}",
|
||||
"guarded Git repository identity {} does not match runner repository {}",
|
||||
canonical_root.display(),
|
||||
self.active_worktree_root.display()
|
||||
)));
|
||||
@@ -160,6 +196,23 @@ impl RepositoryAuthority {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn revalidate_active_worktree_identity(&self) -> io::Result<()> {
|
||||
let Some(expected) = &self.active_worktree_identity else {
|
||||
return Ok(());
|
||||
};
|
||||
let actual = Handle::from_path(&self.active_worktree_root).map_err(|error| {
|
||||
authority_refusal(format!(
|
||||
"guarded Git repository identity could not be revalidated: {error}"
|
||||
))
|
||||
})?;
|
||||
if &actual != expected {
|
||||
return Err(authority_refusal(
|
||||
"guarded Git repository identity changed before Git launch",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn from_test_locations(
|
||||
roots: Vec<PathBuf>,
|
||||
@@ -168,12 +221,15 @@ impl RepositoryAuthority {
|
||||
) -> Result<Self, GitReadError> {
|
||||
let route_boundaries = repository_route_boundaries(&worktree_roots, &common_dirs)
|
||||
.map_err(|error| invalid_metadata(Path::new("<test>"), error))?;
|
||||
let active_worktree_root = worktree_roots
|
||||
.first()
|
||||
.or_else(|| roots.first())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let active_worktree_identity = open_active_worktree_identity(&active_worktree_root).ok();
|
||||
Ok(Self {
|
||||
active_worktree_root: worktree_roots
|
||||
.first()
|
||||
.or_else(|| roots.first())
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
active_worktree_root,
|
||||
active_worktree_identity,
|
||||
roots,
|
||||
worktree_roots,
|
||||
common_dirs,
|
||||
@@ -185,13 +241,18 @@ impl RepositoryAuthority {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
pub(crate) fn active_git_dir(&self) -> Option<&Path> {
|
||||
self.active_metadata
|
||||
.as_ref()
|
||||
.map(|metadata| metadata.git_dir.as_path())
|
||||
}
|
||||
|
||||
pub(crate) fn active_common_dir(&self) -> Option<&Path> {
|
||||
self.active_metadata
|
||||
.as_ref()
|
||||
.map(|metadata| metadata.common_dir.as_path())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn contains_root(&self, root: &Path) -> bool {
|
||||
self.roots
|
||||
|
||||
@@ -70,6 +70,12 @@ impl RepositoryAuthority {
|
||||
if !path.is_absolute() {
|
||||
return Err(worktree_controlled_config_source(path, description));
|
||||
}
|
||||
if self
|
||||
.route_boundaries
|
||||
.route_contains_process_relative_procfs_path(path)?
|
||||
{
|
||||
return Err(process_relative_config_source(path, description));
|
||||
}
|
||||
let inspection = self.route_boundaries.inspect_route(path)?;
|
||||
if inspection.crosses_worktree {
|
||||
return Err(worktree_controlled_config_source(path, description));
|
||||
@@ -204,3 +210,10 @@ fn worktree_controlled_config_source(path: &Path, description: &str) -> io::Erro
|
||||
path.display()
|
||||
))
|
||||
}
|
||||
|
||||
fn process_relative_config_source(path: &Path, description: &str) -> io::Error {
|
||||
authority_refusal(format!(
|
||||
"refusing to use process-relative {description}: {}",
|
||||
path.display()
|
||||
))
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::path::PathBuf;
|
||||
|
||||
use super::bytes_to_path;
|
||||
use super::read_bounded_file;
|
||||
use crate::git_config::parse_git_boolean;
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub(crate) enum CommonConfigAuthority {
|
||||
@@ -50,7 +51,7 @@ pub(crate) fn inspect_plain_common_config_authority(
|
||||
return Ok(CommonConfigAuthority::Unproven);
|
||||
}
|
||||
let bare = match unique_explicit_value(&config, "core", "bare") {
|
||||
Ok(Some(value)) => match explicit_boolean(value.as_ref()) {
|
||||
Ok(Some(value)) => match parse_git_boolean(value.as_ref()) {
|
||||
Some(value) => Some(value),
|
||||
None => return Ok(CommonConfigAuthority::Unproven),
|
||||
},
|
||||
@@ -58,7 +59,7 @@ pub(crate) fn inspect_plain_common_config_authority(
|
||||
Err(()) => return Ok(CommonConfigAuthority::Unproven),
|
||||
};
|
||||
match unique_explicit_value(&config, "extensions", "worktreeConfig") {
|
||||
Ok(Some(value)) if explicit_boolean(value.as_ref()) == Some(false) => {}
|
||||
Ok(Some(value)) if parse_git_boolean(value.as_ref()) == Some(false) => {}
|
||||
Ok(None) => {}
|
||||
Ok(Some(_)) | Err(()) => return Ok(CommonConfigAuthority::Unproven),
|
||||
}
|
||||
@@ -99,39 +100,29 @@ fn unique_explicit_value(
|
||||
let Some(sections) = config.sections_by_name(section_name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut occurrences = 0usize;
|
||||
let mut explicit_values = Vec::new();
|
||||
let mut occurrence = None;
|
||||
for section in sections {
|
||||
if section.header().subsection_name().is_some() {
|
||||
return Err(());
|
||||
}
|
||||
occurrences += section
|
||||
.value_names()
|
||||
.filter(|name| {
|
||||
let name: &str = name.as_ref();
|
||||
name.eq_ignore_ascii_case(value_name)
|
||||
})
|
||||
.count();
|
||||
explicit_values.extend(
|
||||
section
|
||||
.values(value_name)
|
||||
.into_iter()
|
||||
.map(|value| value.as_ref().to_vec()),
|
||||
);
|
||||
for name in section.value_names() {
|
||||
let name: &str = name.as_ref();
|
||||
if !name.eq_ignore_ascii_case(value_name) {
|
||||
continue;
|
||||
}
|
||||
if occurrence.is_some() {
|
||||
return Err(());
|
||||
}
|
||||
let value = section
|
||||
.value_implicit(name)
|
||||
.ok_or(())?
|
||||
.map(|value| value.as_ref().to_vec());
|
||||
occurrence = Some(value);
|
||||
}
|
||||
}
|
||||
match (occurrences, explicit_values.len()) {
|
||||
(0, 0) => Ok(None),
|
||||
(1, 1) => Ok(explicit_values.pop()),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn explicit_boolean(value: &[u8]) -> Option<bool> {
|
||||
if value.eq_ignore_ascii_case(b"true") {
|
||||
Some(true)
|
||||
} else if value.eq_ignore_ascii_case(b"false") {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
match occurrence {
|
||||
None => Ok(None),
|
||||
Some(Some(value)) => Ok(Some(value)),
|
||||
Some(None) => Err(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,36 @@ fn plain_common_bare_parser_matches_native_boolean_syntax_and_is_stricter_on_dup
|
||||
CommonConfigAuthority::Bare,
|
||||
Some(true),
|
||||
),
|
||||
(
|
||||
"yes",
|
||||
b"[core]\n\tbare = yes\n".as_slice(),
|
||||
CommonConfigAuthority::Bare,
|
||||
Some(true),
|
||||
),
|
||||
(
|
||||
"on",
|
||||
b"[core]\n\tbare = on\n".as_slice(),
|
||||
CommonConfigAuthority::Bare,
|
||||
Some(true),
|
||||
),
|
||||
(
|
||||
"numeric true",
|
||||
b"[core]\n\tbare = 1\n".as_slice(),
|
||||
CommonConfigAuthority::Bare,
|
||||
Some(true),
|
||||
),
|
||||
(
|
||||
"hex true",
|
||||
b"[core]\n\tbare = 0x1\n".as_slice(),
|
||||
CommonConfigAuthority::Bare,
|
||||
Some(true),
|
||||
),
|
||||
(
|
||||
"suffixed true",
|
||||
b"[core]\n\tbare = 1k\n".as_slice(),
|
||||
CommonConfigAuthority::Bare,
|
||||
Some(true),
|
||||
),
|
||||
(
|
||||
"false",
|
||||
b"[core]\n\tbare = false\n".as_slice(),
|
||||
@@ -133,13 +163,13 @@ fn plain_common_bare_parser_matches_native_boolean_syntax_and_is_stricter_on_dup
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_bare_proof_accepts_only_explicit_boolean_literals() {
|
||||
fn common_bare_proof_rejects_invalid_git_boolean_values() {
|
||||
for (name, body) in [
|
||||
("empty", b"[core]\n\tbare =\n".as_slice()),
|
||||
("yes", b"[core]\n\tbare = yes\n".as_slice()),
|
||||
("on", b"[core]\n\tbare = on\n".as_slice()),
|
||||
("one", b"[core]\n\tbare = 1\n".as_slice()),
|
||||
("leading zero", b"[core]\n\tbare = 08\n".as_slice()),
|
||||
(
|
||||
"negative leading zero",
|
||||
b"[core]\n\tbare = -08\n".as_slice(),
|
||||
),
|
||||
(
|
||||
"positive overflow",
|
||||
b"[core]\n\tbare = 2147483648\n".as_slice(),
|
||||
@@ -152,6 +182,8 @@ fn common_bare_proof_accepts_only_explicit_boolean_literals() {
|
||||
"i64 max",
|
||||
b"[core]\n\tbare = 9223372036854775807\n".as_slice(),
|
||||
),
|
||||
("suffix overflow", b"[core]\n\tbare = 2g\n".as_slice()),
|
||||
("trailing junk", b"[core]\n\tbare = 1foo\n".as_slice()),
|
||||
] {
|
||||
let common = write_common_config(body);
|
||||
assert_eq!(
|
||||
@@ -162,6 +194,34 @@ fn common_bare_proof_accepts_only_explicit_boolean_literals() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_bare_proof_accepts_explicit_false_worktree_config_spellings() {
|
||||
for value in ["false", "no", "off", "", "0", "-0", "+0", "00", "0x0"] {
|
||||
let common = write_common_config(
|
||||
format!("[core]\n\tbare = yes\n[extensions]\n\tworktreeConfig = {value}\n").as_bytes(),
|
||||
);
|
||||
assert_eq!(
|
||||
inspect_plain_common_config_authority(common.path()).expect(value),
|
||||
CommonConfigAuthority::Bare,
|
||||
"authority result for worktreeConfig={value:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_bare_proof_rejects_explicit_true_worktree_config_spellings() {
|
||||
for value in ["true", "yes", "on", "1", "-1", "0x1", "1k"] {
|
||||
let common = write_common_config(
|
||||
format!("[core]\n\tbare = yes\n[extensions]\n\tworktreeConfig = {value}\n").as_bytes(),
|
||||
);
|
||||
assert_eq!(
|
||||
inspect_plain_common_config_authority(common.path()).expect(value),
|
||||
CommonConfigAuthority::Unproven,
|
||||
"authority result for worktreeConfig={value:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_bare_proof_rejects_includes_worktree_config_and_relative_worktree() {
|
||||
let include_target = tempfile::NamedTempFile::new().expect("included config");
|
||||
@@ -226,6 +286,25 @@ fn common_config_absolute_worktree_is_returned_as_authority() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_config_false_bare_spellings_allow_absolute_worktree() {
|
||||
let worktree = tempfile::tempdir().expect("worktree");
|
||||
for bare in ["false", "no", "off", "", "0", "-0", "+0", "00", "0x0"] {
|
||||
let common = write_common_config(
|
||||
format!(
|
||||
"[core]\n\tbare = {bare}\n\tworktree = {}\n",
|
||||
git_config_path(worktree.path())
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
assert_eq!(
|
||||
inspect_plain_common_config_authority(common.path()).expect(bare),
|
||||
CommonConfigAuthority::Worktree(worktree.path().to_path_buf()),
|
||||
"authority result for core.bare={bare:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_config_rejects_contradictory_or_malformed_bare_with_absolute_worktree() {
|
||||
let worktree = tempfile::tempdir().expect("worktree");
|
||||
|
||||
@@ -92,6 +92,52 @@ fn request(root: &Path, patch: &str) -> ApplyGitRequest {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_preflight_refuses_the_same_divergent_staged_blob_without_mutation() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("file.txt"), b"old\n").expect("base file");
|
||||
run_success(root, &["add", "file.txt"]);
|
||||
run_success(root, &["commit", "-qm", "base"]);
|
||||
std::fs::write(root.join("file.txt"), b"staged\n").expect("staged file");
|
||||
run_success(root, &["add", "file.txt"]);
|
||||
std::fs::write(root.join("file.txt"), b"new\n").expect("reverse worktree");
|
||||
let patch = "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new\n";
|
||||
let index_before = std::fs::read(root.join(".git/index")).expect("read index");
|
||||
let worktree_before = std::fs::read(root.join("file.txt")).expect("read worktree");
|
||||
|
||||
let mut preflight = request(root, patch);
|
||||
preflight.preflight = true;
|
||||
let preflight_error = apply_git_patch(&preflight).expect_err("preflight must refuse");
|
||||
assert_eq!(preflight_error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert!(
|
||||
preflight_error
|
||||
.to_string()
|
||||
.contains("would replace existing staged data"),
|
||||
"{preflight_error}"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".git/index")).expect("index after preflight"),
|
||||
index_before
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(root.join("file.txt")).expect("worktree after preflight"),
|
||||
worktree_before
|
||||
);
|
||||
|
||||
let apply_error = apply_git_patch(&request(root, patch)).expect_err("apply must refuse");
|
||||
assert_eq!(apply_error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(apply_error.to_string(), preflight_error.to_string());
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".git/index")).expect("index after apply"),
|
||||
index_before
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(root.join("file.txt")).expect("worktree after apply"),
|
||||
worktree_before
|
||||
);
|
||||
}
|
||||
|
||||
fn topology_fixture(topology: Topology) -> (tempfile::TempDir, String) {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
@@ -158,6 +204,8 @@ fn assert_refused_without_mutation(root: &Path, patch: &str) {
|
||||
let before_leaves = [
|
||||
leaf_snapshot(root, "old.txt"),
|
||||
leaf_snapshot(root, "new.txt"),
|
||||
leaf_snapshot(root, "file.txt"),
|
||||
leaf_snapshot(root, "other.txt"),
|
||||
];
|
||||
let error = apply_git_patch(&request(root, patch)).expect_err("unsafe reverse must fail");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
|
||||
@@ -165,7 +213,9 @@ fn assert_refused_without_mutation(root: &Path, patch: &str) {
|
||||
assert_eq!(
|
||||
[
|
||||
leaf_snapshot(root, "old.txt"),
|
||||
leaf_snapshot(root, "new.txt")
|
||||
leaf_snapshot(root, "new.txt"),
|
||||
leaf_snapshot(root, "file.txt"),
|
||||
leaf_snapshot(root, "other.txt")
|
||||
],
|
||||
before_leaves
|
||||
);
|
||||
@@ -195,6 +245,65 @@ fn reverse_delete_and_rename_preserve_divergent_staged_blobs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_three_way_refuses_staged_content_change_matching_the_worktree() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("file.txt"), b"top\nbase\nbottom\n").expect("base file");
|
||||
run_success(root, &["add", "file.txt"]);
|
||||
run_success(root, &["commit", "-qm", "base"]);
|
||||
let base = String::from_utf8(run_success(root, &["rev-parse", "HEAD"])).expect("base OID");
|
||||
std::fs::write(root.join("file.txt"), b"top\ntheirs\nbottom\n").expect("theirs file");
|
||||
run_success(root, &["add", "file.txt"]);
|
||||
run_success(root, &["commit", "-qm", "theirs"]);
|
||||
let patch = String::from_utf8(run_success(
|
||||
root,
|
||||
&[
|
||||
"diff",
|
||||
"--full-index",
|
||||
base.trim(),
|
||||
"HEAD",
|
||||
"--",
|
||||
"file.txt",
|
||||
],
|
||||
))
|
||||
.expect("patch");
|
||||
std::fs::write(root.join("file.txt"), b"top\nuser-staged\nbottom\n").expect("user staged file");
|
||||
run_success(root, &["add", "file.txt"]);
|
||||
|
||||
assert_refused_without_mutation(root, &patch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_three_way_refuses_staged_non_candidate_before_staging_another_path() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
for path in ["file.txt", "other.txt"] {
|
||||
std::fs::write(root.join(path), b"top\nbase\nbottom\n").expect("base file");
|
||||
}
|
||||
run_success(root, &["add", "."]);
|
||||
run_success(root, &["commit", "-qm", "base"]);
|
||||
let base = String::from_utf8(run_success(root, &["rev-parse", "HEAD"])).expect("base OID");
|
||||
for path in ["file.txt", "other.txt"] {
|
||||
std::fs::write(root.join(path), b"top\ntheirs\nbottom\n").expect("theirs file");
|
||||
}
|
||||
run_success(root, &["add", "."]);
|
||||
run_success(root, &["commit", "-qm", "theirs"]);
|
||||
let patch = String::from_utf8(run_success(
|
||||
root,
|
||||
&["diff", "--full-index", base.trim(), "HEAD"],
|
||||
))
|
||||
.expect("patch");
|
||||
|
||||
std::fs::write(root.join("file.txt"), b"top\nuser-staged\nbottom\n")
|
||||
.expect("staged non-candidate");
|
||||
run_success(root, &["add", "file.txt"]);
|
||||
std::fs::write(root.join("other.txt"), b"top\nunstaged\nbottom\n")
|
||||
.expect("unstaged staging candidate");
|
||||
|
||||
assert_refused_without_mutation(root, &patch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_rename_accepts_each_partially_staged_form() {
|
||||
for staged_endpoints in ["old", "new", "both"] {
|
||||
@@ -470,6 +579,47 @@ fn reverse_refuses_ignored_untracked_rename_endpoint_without_mutation() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_refuses_ignored_endpoint_before_staging_eligible_peer() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("old.txt"), b"old\n").unwrap();
|
||||
std::fs::write(root.join("other.txt"), b"old\n").unwrap();
|
||||
run_success(root, &["add", "old.txt", "other.txt"]);
|
||||
run_success(root, &["commit", "-qm", "base"]);
|
||||
run_success(root, &["mv", "old.txt", "new.txt"]);
|
||||
std::fs::write(root.join("other.txt"), b"new\n").unwrap();
|
||||
run_success(root, &["add", "other.txt"]);
|
||||
let patch = String::from_utf8(run_success(
|
||||
root,
|
||||
&["diff", "--cached", "--full-index", "--binary", "-M"],
|
||||
))
|
||||
.unwrap();
|
||||
run_success(root, &["reset", "--hard", "-q", "HEAD"]);
|
||||
|
||||
std::fs::write(root.join(".gitignore"), b"new.txt\n").unwrap();
|
||||
std::fs::rename(root.join("old.txt"), root.join("new.txt")).unwrap();
|
||||
std::fs::write(root.join("other.txt"), b"new\n").unwrap();
|
||||
|
||||
let before_index = index_snapshot(root);
|
||||
let before_leaves = [
|
||||
leaf_snapshot(root, "old.txt"),
|
||||
leaf_snapshot(root, "new.txt"),
|
||||
leaf_snapshot(root, "other.txt"),
|
||||
];
|
||||
let error = apply_git_patch(&request(root, &patch)).expect_err("ignored endpoint");
|
||||
assert!(error.to_string().contains("ignored"), "{error}");
|
||||
assert_eq!(index_snapshot(root), before_index);
|
||||
assert_eq!(
|
||||
[
|
||||
leaf_snapshot(root, "old.txt"),
|
||||
leaf_snapshot(root, "new.txt"),
|
||||
leaf_snapshot(root, "other.txt")
|
||||
],
|
||||
before_leaves
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_handles_unborn_empty_index_and_refuses_unborn_index_state() {
|
||||
const DELETE_PATCH: &str = "diff --git a/old.txt b/old.txt\ndeleted file mode 100644\n--- a/old.txt\n+++ /dev/null\n@@ -1 +0,0 @@\n-old\n";
|
||||
|
||||
@@ -4,16 +4,52 @@ use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::io;
|
||||
|
||||
use crate::exact_staging::update_index_exact_paths_from_apply;
|
||||
use crate::exact_staging::PreparedReverseIndexUpdate;
|
||||
use crate::exact_staging::execute_prepared_reverse_index_update;
|
||||
use crate::exact_staging::prepare_index_exact_paths_for_reverse_apply;
|
||||
use crate::git_command::IsolatedGitStorage;
|
||||
use crate::guarded_config::GuardedGitConfig;
|
||||
use crate::guarded_config::GuardedOperationIdentity;
|
||||
use crate::patch_paths::confine_patch_paths_guarded;
|
||||
use crate::patch_paths::leaf_is_traversable_directory;
|
||||
use crate::patch_paths::leaf_may_run_git_content_filter;
|
||||
|
||||
pub(crate) fn stage_effective_paths_for_reverse(
|
||||
config: &mut GuardedGitConfig<'_>,
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ReverseApplyMode {
|
||||
Direct,
|
||||
ThreeWay,
|
||||
}
|
||||
|
||||
pub(crate) struct ReverseStagingPlan {
|
||||
staging_candidates: Vec<String>,
|
||||
content_filter_paths: Vec<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct SealedReverseStagingPlan {
|
||||
owner: GuardedOperationIdentity,
|
||||
update: PreparedReverseIndexUpdate,
|
||||
scratch_use_available: bool,
|
||||
}
|
||||
|
||||
/// Validate every reverse-staging precondition without changing the index.
|
||||
///
|
||||
/// Preflight uses the same plan builder as the real operation so an
|
||||
/// applicability-only `git apply --check -R` cannot report success when
|
||||
/// preparing the index would overwrite staged data.
|
||||
pub(crate) fn validate_effective_paths_for_reverse(
|
||||
config: &GuardedGitConfig<'_>,
|
||||
paths: &[String],
|
||||
mode: ReverseApplyMode,
|
||||
) -> io::Result<()> {
|
||||
let _ = prepare_reverse_staging_plan(config, paths, mode)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_reverse_staging_plan(
|
||||
config: &GuardedGitConfig<'_>,
|
||||
paths: &[String],
|
||||
mode: ReverseApplyMode,
|
||||
) -> io::Result<ReverseStagingPlan> {
|
||||
let confined = confine_patch_paths_guarded(config, paths)?;
|
||||
let mut worktree_paths = BTreeMap::new();
|
||||
for path in confined.into_exact_leaves()? {
|
||||
@@ -82,6 +118,15 @@ pub(crate) fn stage_effective_paths_for_reverse(
|
||||
"refusing to stage reverse patch path {path:?} because it has intent-to-add index state"
|
||||
)));
|
||||
}
|
||||
if mode == ReverseApplyMode::ThreeWay
|
||||
&& let Some(path) = exact_paths
|
||||
.iter()
|
||||
.find(|path| cached_visible_status.contains_key(*path))
|
||||
{
|
||||
return Err(reverse_staging_error(format!(
|
||||
"refusing a three-way reverse patch because it would replace existing staged data for {path:?}"
|
||||
)));
|
||||
}
|
||||
let worktree_changed_paths = read_changed_paths(config, &exact_paths)?;
|
||||
|
||||
let mut staging_candidates = Vec::new();
|
||||
@@ -101,7 +146,10 @@ pub(crate) fn stage_effective_paths_for_reverse(
|
||||
}
|
||||
}
|
||||
if staging_candidates.is_empty() {
|
||||
return Ok(());
|
||||
return Ok(ReverseStagingPlan {
|
||||
staging_candidates,
|
||||
content_filter_paths: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(path) = staging_candidates
|
||||
@@ -122,8 +170,54 @@ pub(crate) fn stage_effective_paths_for_reverse(
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let result =
|
||||
update_index_exact_paths_from_apply(config, &staging_candidates, &content_filter_paths)?;
|
||||
Ok(ReverseStagingPlan {
|
||||
staging_candidates,
|
||||
content_filter_paths,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn execute_reverse_staging_plan_in_scratch(
|
||||
config: &GuardedGitConfig<'_>,
|
||||
plan: &mut SealedReverseStagingPlan,
|
||||
storage: &IsolatedGitStorage,
|
||||
) -> io::Result<()> {
|
||||
config.ensure_operation_identity(&plan.owner)?;
|
||||
if !std::mem::replace(&mut plan.scratch_use_available, false) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"sealed reverse staging plan scratch use was already consumed",
|
||||
));
|
||||
}
|
||||
let result = execute_prepared_reverse_index_update(config, &plan.update, Some(storage))?;
|
||||
reverse_staging_result(result)
|
||||
}
|
||||
|
||||
pub(crate) fn seal_reverse_staging_plan(
|
||||
config: &mut GuardedGitConfig<'_>,
|
||||
plan: ReverseStagingPlan,
|
||||
) -> io::Result<SealedReverseStagingPlan> {
|
||||
let update = prepare_index_exact_paths_for_reverse_apply(
|
||||
config,
|
||||
&plan.staging_candidates,
|
||||
&plan.content_filter_paths,
|
||||
)?;
|
||||
Ok(SealedReverseStagingPlan {
|
||||
owner: config.operation_identity(),
|
||||
update,
|
||||
scratch_use_available: true,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn execute_reverse_staging_plan(
|
||||
config: &GuardedGitConfig<'_>,
|
||||
plan: SealedReverseStagingPlan,
|
||||
) -> io::Result<()> {
|
||||
config.ensure_operation_identity(&plan.owner)?;
|
||||
let result = execute_prepared_reverse_index_update(config, &plan.update, None)?;
|
||||
reverse_staging_result(result)
|
||||
}
|
||||
|
||||
fn reverse_staging_result(result: crate::exact_staging::StagePathsResult) -> io::Result<()> {
|
||||
if result.exit_code == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
@@ -469,6 +469,25 @@ pub(crate) fn executable_filter_drivers(
|
||||
Ok(ExecutableFilterDrivers(executable_drivers))
|
||||
}
|
||||
|
||||
/// Status must also inspect required-only namespaces. A selected
|
||||
/// `filter.<name>.required=true` with no clean/process command makes native
|
||||
/// status fail closed, so silently resetting it would turn an unavailable
|
||||
/// result into a potentially misleading Boolean.
|
||||
pub(crate) fn status_policy_filter_drivers(
|
||||
entries: &BTreeMap<String, GitConfigEntry>,
|
||||
) -> io::Result<ExecutableFilterDrivers> {
|
||||
let mut drivers = executable_filter_drivers(entries)?.0;
|
||||
for entry in entries.values() {
|
||||
let Some(remainder) = entry.key.strip_prefix("filter.") else {
|
||||
return Err(invalid_filter_output("malformed filter config key"));
|
||||
};
|
||||
if let Some(driver) = remainder.strip_suffix(".required") {
|
||||
drivers.insert(driver.to_string());
|
||||
}
|
||||
}
|
||||
Ok(ExecutableFilterDrivers(drivers))
|
||||
}
|
||||
|
||||
fn effective_filter_value<'a>(
|
||||
entries: &'a BTreeMap<String, GitConfigEntry>,
|
||||
driver: &str,
|
||||
|
||||
@@ -670,6 +670,19 @@ async fn get_has_changes_rejects_configured_clean_filter_without_running_it() {
|
||||
assert!(!configured_filter_ran(&repo_path).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_has_changes_pins_normal_untracked_files_over_repository_config() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo_path = create_test_git_repo(&temp_dir).await;
|
||||
run_git_async(&repo_path, &["config", "status.showUntrackedFiles", "no"]).await;
|
||||
std::fs::write(repo_path.join("untracked.txt"), "untracked\n").expect("write untracked file");
|
||||
|
||||
assert_eq!(
|
||||
try_get_has_changes_with_test_timeout(&repo_path).await,
|
||||
Ok(true)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_has_changes_distinguishes_filter_sentinels_from_literal_driver_names() {
|
||||
for (driver, sentinel_attribute) in
|
||||
|
||||
@@ -62,7 +62,12 @@ pub(crate) async fn read_status(config: &GuardedGitConfig<'_>) -> Result<bool, G
|
||||
exit_code: output.status.code(),
|
||||
});
|
||||
}
|
||||
Ok(!output.stdout.is_empty())
|
||||
if !output.stdout.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
config
|
||||
.status_has_untracked_snapshot()
|
||||
.map_err(|error| map_io_error("statusUntracked", error))
|
||||
}
|
||||
|
||||
pub(crate) fn map_io_error(operation: &str, error: io::Error) -> GitReadError {
|
||||
|
||||
@@ -26,6 +26,23 @@ async fn run_git(cwd: &Path, args: &[&str]) -> std::process::Output {
|
||||
output
|
||||
}
|
||||
|
||||
async fn run_git_without_attr_source(cwd: &Path, args: &[&str]) -> std::process::Output {
|
||||
let output = Command::new("git")
|
||||
.env_remove("GIT_ATTR_SOURCE")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.await
|
||||
.expect("run Git without GIT_ATTR_SOURCE");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"git {args:?} without GIT_ATTR_SOURCE failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
output
|
||||
}
|
||||
|
||||
async fn init_repo(temp_dir: &tempfile::TempDir, file_count: usize) -> PathBuf {
|
||||
let repo = temp_dir.path().join("repo");
|
||||
std::fs::create_dir(&repo).expect("create repository");
|
||||
@@ -100,6 +117,76 @@ fn run_isolated_config_test(test_name: &str) {
|
||||
);
|
||||
}
|
||||
|
||||
fn run_isolated_environment_test(
|
||||
test_name: &str,
|
||||
marker: &str,
|
||||
variables: &[(&str, &str)],
|
||||
global_attributes: Option<&str>,
|
||||
) {
|
||||
let environment = tempfile::tempdir().expect("isolated Git environment");
|
||||
let global_config = environment.path().join("global.gitconfig");
|
||||
let system_config = environment.path().join("system.gitconfig");
|
||||
let home = environment.path().join("home");
|
||||
let xdg = environment.path().join("xdg");
|
||||
std::fs::create_dir_all(xdg.join("git")).expect("create isolated XDG Git directory");
|
||||
std::fs::create_dir_all(&home).expect("create isolated HOME");
|
||||
std::fs::write(&global_config, "").expect("empty global config");
|
||||
std::fs::write(&system_config, "").expect("empty system config");
|
||||
if let Some(contents) = global_attributes {
|
||||
std::fs::write(xdg.join("git/attributes"), contents)
|
||||
.expect("write isolated global attributes");
|
||||
}
|
||||
|
||||
let mut command = std::process::Command::new(std::env::current_exe().expect("test binary"));
|
||||
crate::safe_git::isolate_git_command_environment(&mut command);
|
||||
command
|
||||
.arg(test_name)
|
||||
.arg("--exact")
|
||||
.arg("--nocapture")
|
||||
.env(marker, "1")
|
||||
.env("GIT_CONFIG_GLOBAL", &global_config)
|
||||
.env("GIT_CONFIG_SYSTEM", &system_config)
|
||||
.env("GIT_CONFIG_NOSYSTEM", "0")
|
||||
.env("GIT_CONFIG_COUNT", "0")
|
||||
.env("GIT_ATTR_NOSYSTEM", "0")
|
||||
.env("HOME", &home)
|
||||
.env("XDG_CONFIG_HOME", &xdg)
|
||||
.env_remove("GIT_CONFIG_PARAMETERS")
|
||||
.env("RUST_TEST_THREADS", "1");
|
||||
for (name, value) in variables {
|
||||
command.env(name, value);
|
||||
}
|
||||
let output = command.output().expect("run isolated test process");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"isolated test {test_name} failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
async fn guarded_status(repo: &Path, git: &GitRunner) -> Result<bool, GitReadError> {
|
||||
let mut guard = prepare_status_config(git, repo).await?;
|
||||
detect_status_fsmonitor(&mut guard).await;
|
||||
read_status(&guard).await
|
||||
}
|
||||
|
||||
async fn replacement_fixture(repo: &Path) -> (String, String) {
|
||||
let original = String::from_utf8(run_git(repo, &["rev-parse", "HEAD"]).await.stdout)
|
||||
.expect("original commit UTF-8")
|
||||
.trim()
|
||||
.to_string();
|
||||
std::fs::write(repo.join("test.txt"), "replacement\n").expect("write replacement contents");
|
||||
run_git(repo, &["add", "test.txt"]).await;
|
||||
run_git(repo, &["commit", "-m", "replacement commit"]).await;
|
||||
let replacement = String::from_utf8(run_git(repo, &["rev-parse", "HEAD"]).await.stdout)
|
||||
.expect("replacement commit UTF-8")
|
||||
.trim()
|
||||
.to_string();
|
||||
run_git(repo, &["checkout", "--detach", &original]).await;
|
||||
(original, replacement)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn io_error_mapping_preserves_authority_provenance() {
|
||||
for error in [
|
||||
@@ -129,6 +216,27 @@ fn io_error_mapping_preserves_authority_provenance() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[tokio::test]
|
||||
async fn process_relative_config_policy_maps_to_authority_refusal() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
let error = git
|
||||
.ensure_config_source_is_not_worktree_controlled(
|
||||
Path::new("/proc/self/cwd/config"),
|
||||
"Git config include",
|
||||
)
|
||||
.expect_err("process-relative config must be refused");
|
||||
|
||||
assert_eq!(
|
||||
map_io_error("statusFilterPreparation", error),
|
||||
GitReadError::AuthorityRefused {
|
||||
operation: "statusFilterPreparation".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_status_preparation_kills_the_active_git_child() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
@@ -238,6 +346,375 @@ async fn prepared_guard_neutralizes_filter_selected_after_the_probe() {
|
||||
assert!(!filter_marker_is_set(&repo, "codex.race-ran").await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frozen_status_blocks_a_new_filter_namespace_and_attribute_after_preparation() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
let mut guard = prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("prepare zero-driver status guard");
|
||||
|
||||
run_git(
|
||||
&repo,
|
||||
&[
|
||||
"config",
|
||||
"filter.fresh.clean",
|
||||
"git config codex.fresh-ran true && git hash-object --stdin",
|
||||
],
|
||||
)
|
||||
.await;
|
||||
std::fs::write(repo.join(".gitattributes"), "test.txt filter=fresh\n")
|
||||
.expect("select new filter namespace after preparation");
|
||||
std::fs::write(repo.join("test.txt"), "changed\n").expect("modify tracked path");
|
||||
|
||||
detect_status_fsmonitor(&mut guard).await;
|
||||
assert_eq!(read_status(&guard).await, Ok(true));
|
||||
assert!(!filter_marker_is_set(&repo, "codex.fresh-ran").await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frozen_status_preserves_info_global_core_and_system_attribute_selection() {
|
||||
const MARKER: &str = "CODEX_GIT_UTILS_STATUS_ATTRIBUTE_ENV_CHILD";
|
||||
if std::env::var_os(MARKER).is_none() {
|
||||
run_isolated_environment_test(
|
||||
"status_guard::tests::frozen_status_preserves_info_global_core_and_system_attribute_selection",
|
||||
MARKER,
|
||||
&[],
|
||||
Some("global.txt ident\n"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
let core_attributes = temp_dir.path().join("core.attributes");
|
||||
std::fs::write(&core_attributes, "core.txt ident\n").expect("write core attributes file");
|
||||
std::fs::write(repo.join(".git/info/attributes"), "info.txt ident\n")
|
||||
.expect("write info attributes");
|
||||
for name in ["global.txt", "core.txt", "info.txt", "literal.txt"] {
|
||||
std::fs::write(repo.join(name), "$Id$\n").expect("write source-parity fixture");
|
||||
}
|
||||
run_git(&repo, &["add", "."]).await;
|
||||
run_git(&repo, &["commit", "-m", "attribute source fixtures"]).await;
|
||||
for name in ["global.txt", "info.txt"] {
|
||||
std::fs::remove_file(repo.join(name)).expect("remove source-parity fixture");
|
||||
run_git(&repo, &["checkout", "--", name]).await;
|
||||
assert!(
|
||||
std::fs::read_to_string(repo.join(name))
|
||||
.expect("read expanded ident fixture")
|
||||
.starts_with("$Id: "),
|
||||
"{name} did not select its attribute source"
|
||||
);
|
||||
}
|
||||
let stock = run_git(&repo, &["status", "--porcelain"]).await;
|
||||
assert!(
|
||||
stock.stdout.is_empty(),
|
||||
"global/info source-parity fixture must be clean under stock Git: {}",
|
||||
String::from_utf8_lossy(&stock.stdout),
|
||||
);
|
||||
|
||||
let wrapper = temp_dir.path().join("git-wrapper");
|
||||
let log = temp_dir.path().join("git-wrapper.log");
|
||||
let real_git = shell_quote(&real_git());
|
||||
write_wrapper(
|
||||
&wrapper,
|
||||
&format!(
|
||||
"#!/bin/sh\nprintf '%s|%s|%s|%s\\n' \"${{GIT_ATTR_NOSYSTEM-unset}}\" \"${{HOME-unset}}\" \"${{XDG_CONFIG_HOME-unset}}\" \"$*\" >>{}\nexec {real_git} \"$@\"\n",
|
||||
shell_quote(&log),
|
||||
),
|
||||
);
|
||||
let git = GitRunner::from_executable_for_test(&repo, wrapper).expect("test Git runner");
|
||||
let mut global_info_guard = prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("prepare global/info source-parity guard");
|
||||
detect_status_fsmonitor(&mut global_info_guard).await;
|
||||
let global_info_output = global_info_guard
|
||||
.status_output_async()
|
||||
.await
|
||||
.expect("run global/info source-parity status");
|
||||
assert!(global_info_output.status.success());
|
||||
assert!(
|
||||
global_info_output.stdout.is_empty(),
|
||||
"isolated global/info source parity diverged: {}",
|
||||
String::from_utf8_lossy(&global_info_output.stdout)
|
||||
);
|
||||
assert!(!global_info_guard.status_has_untracked_snapshot().expect("untracked snapshot"));
|
||||
|
||||
let home = std::env::var("HOME").expect("isolated HOME");
|
||||
let xdg = std::env::var("XDG_CONFIG_HOME").expect("isolated XDG config home");
|
||||
let log_contents =
|
||||
std::fs::read_to_string(&log).expect("read attribute environment log");
|
||||
let final_status = log_contents
|
||||
.lines()
|
||||
.find(|line| line.contains(" status --porcelain"))
|
||||
.expect("final status environment");
|
||||
assert!(
|
||||
final_status.starts_with(&format!("0|{home}|{xdg}|")),
|
||||
"captured system/global attribute selectors were not restored: {final_status}"
|
||||
);
|
||||
|
||||
run_git(&repo, &["config", "core.attributesFile", "../core.attributes"]).await;
|
||||
std::fs::remove_file(repo.join("global.txt")).expect("remove global attribute fixture");
|
||||
run_git(&repo, &["checkout", "--", "global.txt"]).await;
|
||||
std::fs::remove_file(repo.join("core.txt")).expect("remove core attribute fixture");
|
||||
run_git(&repo, &["checkout", "--", "core.txt"]).await;
|
||||
assert!(
|
||||
std::fs::read_to_string(repo.join("core.txt"))
|
||||
.expect("read expanded core ident fixture")
|
||||
.starts_with("$Id: "),
|
||||
"relative core.attributesFile did not select ident"
|
||||
);
|
||||
let stock = run_git(&repo, &["status", "--porcelain"]).await;
|
||||
assert!(
|
||||
stock.stdout.is_empty(),
|
||||
"core.attributesFile fixture must be clean under stock Git: {}",
|
||||
String::from_utf8_lossy(&stock.stdout)
|
||||
);
|
||||
let mut core_guard = prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("prepare core.attributesFile source-parity guard");
|
||||
detect_status_fsmonitor(&mut core_guard).await;
|
||||
let core_output = core_guard
|
||||
.status_output_async()
|
||||
.await
|
||||
.expect("run core.attributesFile source-parity status");
|
||||
assert!(core_output.status.success());
|
||||
assert!(
|
||||
core_output.stdout.is_empty(),
|
||||
"isolated core.attributesFile source parity diverged: {}",
|
||||
String::from_utf8_lossy(&core_output.stdout)
|
||||
);
|
||||
assert!(!core_guard.status_has_untracked_snapshot().expect("untracked snapshot"));
|
||||
|
||||
std::fs::write(
|
||||
repo.join(".git/info/attributes"),
|
||||
"info.txt ident\nliteral.txt ident=set\n",
|
||||
)
|
||||
.expect("write literal sentinel info attribute");
|
||||
std::fs::write(repo.join("literal.txt"), "$Id: fake $\n")
|
||||
.expect("write literal-sentinel ident fixture");
|
||||
assert_eq!(
|
||||
guarded_status(&repo, &git).await,
|
||||
Ok(true),
|
||||
"literal ident=set must not be reserialized as special Set"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frozen_status_refuses_git_attr_source_and_attr_tree() {
|
||||
const MARKER: &str = "CODEX_GIT_UTILS_STATUS_ATTR_SOURCE_CHILD";
|
||||
if std::env::var_os(MARKER).is_some() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = temp_dir.path().join("repo");
|
||||
std::fs::create_dir(&repo).expect("create repository");
|
||||
run_git_without_attr_source(&repo, &["init", "-q"]).await;
|
||||
run_git_without_attr_source(&repo, &["config", "user.name", "Test User"]).await;
|
||||
run_git_without_attr_source(&repo, &["config", "user.email", "test@example.com"]).await;
|
||||
std::fs::write(repo.join("test.txt"), "contents\n").expect("write tracked file");
|
||||
run_git_without_attr_source(&repo, &["add", "test.txt"]).await;
|
||||
run_git_without_attr_source(&repo, &["commit", "-m", "seed"]).await;
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
assert!(
|
||||
prepare_status_config(&git, &repo).await.is_err(),
|
||||
"GIT_ATTR_SOURCE must make frozen Status unavailable"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
run_isolated_environment_test(
|
||||
"status_guard::tests::frozen_status_refuses_git_attr_source_and_attr_tree",
|
||||
MARKER,
|
||||
&[("GIT_ATTR_SOURCE", "HEAD")],
|
||||
None,
|
||||
);
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
run_git(&repo, &["config", "attr.tree", "HEAD"]).await;
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
assert!(
|
||||
prepare_status_config(&git, &repo).await.is_err(),
|
||||
"attr.tree must make frozen Status unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frozen_untracked_presence_honors_all_standard_ignore_sources() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
std::fs::write(repo.join(".gitignore"), "root-ignored.txt\n")
|
||||
.expect("write root ignore");
|
||||
run_git(&repo, &["add", ".gitignore"]).await;
|
||||
run_git(&repo, &["commit", "-m", "ignore rules"]).await;
|
||||
std::fs::write(repo.join(".git/info/exclude"), "info-ignored.txt\n")
|
||||
.expect("write info exclude");
|
||||
let global_excludes = temp_dir.path().join("global-excludes");
|
||||
std::fs::write(&global_excludes, "global-ignored.txt\n").expect("write global excludes");
|
||||
run_git(
|
||||
&repo,
|
||||
&[
|
||||
"config",
|
||||
"core.excludesFile",
|
||||
global_excludes.to_str().expect("UTF-8 excludes path"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
for name in [
|
||||
"root-ignored.txt",
|
||||
"info-ignored.txt",
|
||||
"global-ignored.txt",
|
||||
] {
|
||||
std::fs::write(repo.join(name), "ignored\n").expect("write ignored file");
|
||||
}
|
||||
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
let mut guard = prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("prepare ignored-only status");
|
||||
detect_status_fsmonitor(&mut guard).await;
|
||||
assert_eq!(read_status(&guard).await, Ok(false));
|
||||
|
||||
std::fs::write(repo.join("visible.txt"), "visible\n").expect("write visible untracked file");
|
||||
run_git(&repo, &["config", "status.showUntrackedFiles", "no"]).await;
|
||||
let mut guard = prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("prepare visible-untracked status");
|
||||
detect_status_fsmonitor(&mut guard).await;
|
||||
assert_eq!(read_status(&guard).await, Ok(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frozen_status_reports_an_ordinary_unmerged_index_as_dirty() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
let base_branch = String::from_utf8(
|
||||
run_git(&repo, &["rev-parse", "--abbrev-ref", "HEAD"])
|
||||
.await
|
||||
.stdout,
|
||||
)
|
||||
.expect("base branch UTF-8")
|
||||
.trim()
|
||||
.to_string();
|
||||
run_git(&repo, &["checkout", "-b", "side"]).await;
|
||||
std::fs::write(repo.join("test.txt"), "side\n").expect("write side contents");
|
||||
run_git(&repo, &["commit", "-am", "side change"]).await;
|
||||
run_git(&repo, &["checkout", &base_branch]).await;
|
||||
std::fs::write(repo.join("test.txt"), "main\n").expect("write main contents");
|
||||
run_git(&repo, &["commit", "-am", "main change"]).await;
|
||||
let merge = Command::new("git")
|
||||
.args(["merge", "side"])
|
||||
.current_dir(&repo)
|
||||
.output()
|
||||
.await
|
||||
.expect("run conflicting merge");
|
||||
assert!(!merge.status.success(), "fixture must produce a conflict");
|
||||
let stages = run_git(&repo, &["ls-files", "--unmerged"]).await;
|
||||
assert!(
|
||||
stages.stdout.split(|byte| *byte == b'\n').count() >= 3,
|
||||
"fixture must retain multiple index stages"
|
||||
);
|
||||
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
assert_eq!(guarded_status(&repo, &git).await, Ok(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_head_snapshot_distinguishes_valid_detached_unborn_and_corrupt_states() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
let commit = String::from_utf8(run_git(&repo, &["rev-parse", "HEAD"]).await.stdout)
|
||||
.expect("commit UTF-8")
|
||||
.trim()
|
||||
.to_string();
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("normal symbolic HEAD");
|
||||
|
||||
run_git(&repo, &["checkout", "--detach", &commit]).await;
|
||||
prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("valid detached HEAD");
|
||||
run_git(&repo, &["checkout", "-B", "restored", &commit]).await;
|
||||
|
||||
let ref_path = repo.join(".git/refs/heads/restored");
|
||||
std::fs::write(&ref_path, format!("{}\n", "a".repeat(40)))
|
||||
.expect("write missing-object ref");
|
||||
assert!(
|
||||
prepare_status_config(&git, &repo).await.is_err(),
|
||||
"missing-object symbolic HEAD must not become unborn"
|
||||
);
|
||||
|
||||
let blob = String::from_utf8(run_git(&repo, &["hash-object", "-w", "test.txt"]).await.stdout)
|
||||
.expect("blob UTF-8")
|
||||
.trim()
|
||||
.to_string();
|
||||
std::fs::write(&ref_path, format!("{blob}\n")).expect("write blob ref");
|
||||
assert_eq!(
|
||||
prepare_status_config(&git, &repo).await.map(|_| ()),
|
||||
Err(GitReadError::CommandFailed {
|
||||
operation: "statusFilterPreparation".to_string(),
|
||||
exit_code: Some(1),
|
||||
})
|
||||
);
|
||||
|
||||
let unborn = temp_dir.path().join("unborn");
|
||||
std::fs::create_dir(&unborn).expect("create unborn repo");
|
||||
run_git(&unborn, &["init", "-q"]).await;
|
||||
let unborn_git = GitRunner::for_cwd(&unborn).expect("unborn Git runner");
|
||||
let mut guard = prepare_status_config(&unborn_git, &unborn)
|
||||
.await
|
||||
.expect("genuine unborn HEAD");
|
||||
detect_status_fsmonitor(&mut guard).await;
|
||||
assert_eq!(read_status(&guard).await, Ok(false));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frozen_status_refuses_active_or_custom_replacements_and_ignores_late_replacements() {
|
||||
const MARKER: &str = "CODEX_GIT_UTILS_STATUS_REPLACE_BASE_CHILD";
|
||||
if std::env::var_os(MARKER).is_some() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
assert!(
|
||||
prepare_status_config(&git, &repo).await.is_err(),
|
||||
"custom replacement-ref namespace must make frozen Status unavailable"
|
||||
);
|
||||
return;
|
||||
}
|
||||
run_isolated_environment_test(
|
||||
"status_guard::tests::frozen_status_refuses_active_or_custom_replacements_and_ignores_late_replacements",
|
||||
MARKER,
|
||||
&[("GIT_REPLACE_REF_BASE", "refs/codex-replacements")],
|
||||
None,
|
||||
);
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
let (original, replacement) = replacement_fixture(&repo).await;
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
let mut guard = prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("prepare before replacement ref exists");
|
||||
run_git(&repo, &["replace", &original, &replacement]).await;
|
||||
let stock = run_git(&repo, &["status", "--porcelain"]).await;
|
||||
assert!(
|
||||
!stock.stdout.is_empty(),
|
||||
"replacement fixture must make stock Status dirty"
|
||||
);
|
||||
detect_status_fsmonitor(&mut guard).await;
|
||||
assert_eq!(
|
||||
read_status(&guard).await,
|
||||
Ok(false),
|
||||
"late replacement must not alter the frozen no-replacement view"
|
||||
);
|
||||
assert!(
|
||||
prepare_status_config(&git, &repo).await.is_err(),
|
||||
"an active default replacement must make frozen Status unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn optional_smudge_only_filter_is_allowed_but_required_is_refused() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
@@ -273,6 +750,60 @@ async fn optional_smudge_only_filter_is_allowed_but_required_is_refused() {
|
||||
assert!(!filter_marker_is_set(&repo, "codex.smudge-ran").await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selected_required_only_filter_is_typed_and_refused_when_truthy() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo = init_repo(&temp_dir, /*file_count*/ 0).await;
|
||||
std::fs::write(repo.join(".gitattributes"), "test.txt filter=required-only\n")
|
||||
.expect("select required-only filter");
|
||||
run_git(&repo, &["add", ".gitattributes"]).await;
|
||||
run_git(&repo, &["commit", "-m", "required-only attribute"]).await;
|
||||
|
||||
run_git(
|
||||
&repo,
|
||||
&["config", "filter.required-only.required", "false"],
|
||||
)
|
||||
.await;
|
||||
let git = GitRunner::for_cwd(&repo).expect("trusted Git");
|
||||
prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("selected required=false filter is inert");
|
||||
|
||||
run_git(
|
||||
&repo,
|
||||
&["config", "filter.required-only.required", "true"],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
prepare_status_config(&git, &repo).await.map(|_| ()),
|
||||
Err(GitReadError::SelectedExecutableFilter {
|
||||
driver: "required-only".to_string(),
|
||||
path: "test.txt".to_string(),
|
||||
})
|
||||
);
|
||||
|
||||
run_git(
|
||||
&repo,
|
||||
&["config", "filter.required-only.required", "not-a-bool"],
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
prepare_status_config(&git, &repo).await.is_err(),
|
||||
"selected malformed required value must fail closed"
|
||||
);
|
||||
|
||||
std::fs::write(repo.join(".gitattributes"), "other.txt filter=required-only\n")
|
||||
.expect("move required-only filter off tracked paths");
|
||||
run_git(
|
||||
&repo,
|
||||
&["config", "filter.required-only.required", "true"],
|
||||
)
|
||||
.await;
|
||||
prepare_status_config(&git, &repo)
|
||||
.await
|
||||
.expect("unselected required-only namespace remains available");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn optional_smudge_required_value_is_queried_once_per_driver() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
@@ -464,14 +995,12 @@ async fn ordinary_driver_uses_one_bulk_path_and_attribute_probe() {
|
||||
let fsmonitor = status
|
||||
.find("core.fsmonitor=")
|
||||
.expect("fsmonitor override before status");
|
||||
let filter = status
|
||||
.find("include.path=")
|
||||
.expect("sealed filter include before status");
|
||||
let status_command = status
|
||||
.find(" status --porcelain")
|
||||
.expect("status subcommand");
|
||||
assert!(hooks < fsmonitor && fsmonitor < filter && filter < status_command);
|
||||
assert_eq!(status.matches("include.path=").count(), 1);
|
||||
assert!(hooks < fsmonitor && fsmonitor < status_command);
|
||||
assert!(!status.contains("include.path="));
|
||||
assert!(status.ends_with("--untracked-files=no"));
|
||||
assert!(!filter_marker_is_set(&repo, "codex.ordinary-filter-ran").await);
|
||||
}
|
||||
|
||||
@@ -499,11 +1028,11 @@ async fn fsmonitor_probe_is_base_only_and_the_sealed_decision_controls_final_ord
|
||||
|
||||
assert_eq!(
|
||||
detect_status_fsmonitor(&mut config).await,
|
||||
FsmonitorOverride::BuiltIn
|
||||
FsmonitorOverride::Disabled
|
||||
);
|
||||
assert_eq!(
|
||||
detect_status_fsmonitor(&mut config).await,
|
||||
FsmonitorOverride::BuiltIn,
|
||||
FsmonitorOverride::Disabled,
|
||||
"the retained decision must avoid a second probe"
|
||||
);
|
||||
read_status(&config).await.expect("final status");
|
||||
@@ -513,30 +1042,24 @@ async fn fsmonitor_probe_is_base_only_and_the_sealed_decision_controls_final_ord
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
lines.len(),
|
||||
3,
|
||||
"one config probe, one feature probe, one status"
|
||||
);
|
||||
assert!(lines[0].ends_with("config --null --get core.fsmonitor"));
|
||||
assert!(!lines[0].contains("core.fsmonitor=false"));
|
||||
assert!(lines[1].ends_with("version --build-options"));
|
||||
assert!(!lines[1].contains("core.fsmonitor=false"));
|
||||
assert_eq!(lines.len(), 1, "synthetic context must not probe or start fsmonitor");
|
||||
let hooks = format!("core.hooksPath={}", crate::safe_git::DISABLED_HOOKS_PATH);
|
||||
let hooks_offset = lines[2].find(&hooks).expect("hooks override");
|
||||
let fsmonitor_offset = lines[2]
|
||||
.find("core.fsmonitor=true")
|
||||
.expect("typed fsmonitor override");
|
||||
let status_offset = lines[2].find("status --porcelain").expect("status command");
|
||||
let hooks_offset = lines[0].find(&hooks).expect("hooks override");
|
||||
let fsmonitor_offset = lines[0]
|
||||
.find("core.fsmonitor=false")
|
||||
.expect("disabled fsmonitor override");
|
||||
let status_offset = lines[0].find("status --porcelain").expect("status command");
|
||||
assert!(hooks_offset < fsmonitor_offset && fsmonitor_offset < status_offset);
|
||||
assert!(lines[2].ends_with("status --porcelain --ignore-submodules=dirty"));
|
||||
assert!(lines[0].ends_with(
|
||||
"status --porcelain --ignore-submodules=dirty --untracked-files=no"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zero_driver_status_skips_tracked_paths_attributes_and_overlay_writes() {
|
||||
async fn zero_driver_status_builds_the_same_frozen_context_without_an_overlay() {
|
||||
if std::env::var_os("CODEX_GIT_UTILS_STATUS_GUARD_ENV_CHILD").is_none() {
|
||||
run_isolated_config_test(
|
||||
"status_guard::tests::zero_driver_status_skips_tracked_paths_attributes_and_overlay_writes",
|
||||
"status_guard::tests::zero_driver_status_builds_the_same_frozen_context_without_an_overlay",
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -558,9 +1081,11 @@ async fn zero_driver_status_skips_tracked_paths_attributes_and_overlay_writes()
|
||||
.await
|
||||
.expect("zero-driver status capability");
|
||||
let lines = std::fs::read_to_string(log).expect("read wrapper log");
|
||||
assert!(!lines.contains(" ls-files -z --cached"), "{lines}");
|
||||
assert!(lines.contains(" ls-files -z --cached"), "{lines}");
|
||||
assert!(!lines.contains(" check-attr --stdin -z filter"), "{lines}");
|
||||
assert!(!lines.contains(" config --file "), "{lines}");
|
||||
assert!(!lines.contains(" check-attr --stdin -z"), "{lines}");
|
||||
assert!(lines.contains("config --file "), "{lines}");
|
||||
assert!(!lines.contains("include.path="), "{lines}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
Reference in New Issue
Block a user