mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Harden internal Git patch operations
This commit is contained in:
Generated
+1
@@ -3137,6 +3137,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"pretty_assertions",
|
||||
"regex",
|
||||
"same-file",
|
||||
"schemars 0.8.22",
|
||||
"serde",
|
||||
"similar",
|
||||
|
||||
@@ -382,6 +382,7 @@ rustls = { version = "0.23", default-features = false, features = [
|
||||
rustls-native-certs = "0.8.3"
|
||||
rustls-pki-types = "1.14.0"
|
||||
schemars = "0.8.22"
|
||||
same-file = "1.0"
|
||||
seccompiler = "0.5.0"
|
||||
semver = "1.0"
|
||||
sentry = "0.46.0"
|
||||
|
||||
@@ -371,8 +371,8 @@ use codex_features::Stage;
|
||||
use codex_feedback::CodexFeedback;
|
||||
use codex_feedback::FeedbackAttachmentPath;
|
||||
use codex_feedback::FeedbackUploadOptions;
|
||||
use codex_git_utils::git_diff_to_remote;
|
||||
use codex_git_utils::resolve_root_git_project_for_trust;
|
||||
use codex_git_utils::try_git_diff_to_remote;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ServerOptions as LoginServerOptions;
|
||||
|
||||
@@ -21,16 +21,77 @@ impl GitRequestProcessor {
|
||||
&self,
|
||||
cwd: PathBuf,
|
||||
) -> Result<GitDiffToRemoteResponse, JSONRPCErrorError> {
|
||||
git_diff_to_remote(&cwd)
|
||||
try_git_diff_to_remote(&cwd)
|
||||
.await
|
||||
.map(|value| GitDiffToRemoteResponse {
|
||||
sha: value.sha,
|
||||
diff: value.diff,
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"failed to compute git diff to remote for cwd: {cwd:?}"
|
||||
))
|
||||
.map_err(|reason| {
|
||||
let mut error = invalid_request(format!(
|
||||
"failed to compute git diff to remote for cwd {cwd:?}: {reason}"
|
||||
));
|
||||
error.data = serde_json::to_value(&reason).ok();
|
||||
error
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn git(cwd: &std::path::Path, args: &[&str]) {
|
||||
let output = std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.expect("run Git");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selected_filter_failure_has_structured_json_rpc_data() {
|
||||
let repo = tempfile::tempdir().expect("repository");
|
||||
let root = repo.path();
|
||||
git(root, &["init"]);
|
||||
git(root, &["config", "user.email", "codex@example.com"]);
|
||||
git(root, &["config", "user.name", "Codex"]);
|
||||
std::fs::write(root.join(".gitattributes"), "file.txt filter=blocked\n")
|
||||
.expect("attributes");
|
||||
std::fs::write(root.join("file.txt"), "contents\n").expect("file");
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-m", "fixture"]);
|
||||
git(
|
||||
root,
|
||||
&[
|
||||
"config",
|
||||
"filter.blocked.clean",
|
||||
"git config codex.filterran true && git hash-object --stdin",
|
||||
],
|
||||
);
|
||||
|
||||
let error = GitRequestProcessor::new()
|
||||
.git_diff_to_origin(root.to_path_buf())
|
||||
.await
|
||||
.expect_err("selected filter must block diff");
|
||||
assert_eq!(
|
||||
error.data,
|
||||
Some(serde_json::json!({
|
||||
"reason": "selectedExecutableFilter",
|
||||
"driver": "blocked",
|
||||
"path": "file.txt",
|
||||
}))
|
||||
);
|
||||
let marker = std::process::Command::new("git")
|
||||
.args(["config", "--get", "codex.filterran"])
|
||||
.current_dir(root)
|
||||
.status()
|
||||
.expect("read marker");
|
||||
assert!(!marker.success(), "selected filter must not run");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +126,8 @@ pub(crate) struct TurnMetadataWorkspace {
|
||||
pub(crate) latest_git_commit_hash: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) has_changes: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) has_changes_unavailable_reason: Option<codex_git_utils::GitReadError>,
|
||||
}
|
||||
|
||||
/// Caller-owned snapshot of Codex metadata sent to ResponsesAPI.
|
||||
|
||||
@@ -18,8 +18,8 @@ use crate::responses_metadata::subagent_metadata_kind;
|
||||
use crate::sandbox_tags::permission_profile_sandbox_tag;
|
||||
use codex_git_utils::get_git_remote_urls_assume_git_repo;
|
||||
use codex_git_utils::get_git_repo_root;
|
||||
use codex_git_utils::get_has_changes;
|
||||
use codex_git_utils::get_head_commit_hash;
|
||||
use codex_git_utils::try_get_has_changes;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
@@ -43,6 +43,7 @@ struct WorkspaceGitMetadata {
|
||||
associated_remote_urls: Option<BTreeMap<String, String>>,
|
||||
latest_git_commit_hash: Option<String>,
|
||||
has_changes: Option<bool>,
|
||||
has_changes_unavailable_reason: Option<codex_git_utils::GitReadError>,
|
||||
}
|
||||
|
||||
impl WorkspaceGitMetadata {
|
||||
@@ -50,6 +51,7 @@ impl WorkspaceGitMetadata {
|
||||
self.associated_remote_urls.is_none()
|
||||
&& self.latest_git_commit_hash.is_none()
|
||||
&& self.has_changes.is_none()
|
||||
&& self.has_changes_unavailable_reason.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +61,7 @@ impl From<WorkspaceGitMetadata> for TurnMetadataWorkspace {
|
||||
associated_remote_urls: value.associated_remote_urls,
|
||||
latest_git_commit_hash: value.latest_git_commit_hash,
|
||||
has_changes: value.has_changes,
|
||||
has_changes_unavailable_reason: value.has_changes_unavailable_reason,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,32 +316,36 @@ impl TurnMetadataState {
|
||||
}
|
||||
|
||||
async fn fetch_workspace_git_metadata(&self) -> WorkspaceGitMetadata {
|
||||
let (head_commit_hash, associated_remote_urls, has_changes) = tokio::join!(
|
||||
let (head_commit_hash, associated_remote_urls, has_changes_result) = tokio::join!(
|
||||
get_head_commit_hash(&self.cwd),
|
||||
get_git_remote_urls_assume_git_repo(&self.cwd),
|
||||
get_has_changes(&self.cwd),
|
||||
try_get_has_changes(&self.cwd),
|
||||
);
|
||||
let latest_git_commit_hash = head_commit_hash.map(|sha| sha.0);
|
||||
let (has_changes, has_changes_unavailable_reason) = split_has_changes(has_changes_result);
|
||||
|
||||
WorkspaceGitMetadata {
|
||||
associated_remote_urls,
|
||||
latest_git_commit_hash,
|
||||
has_changes,
|
||||
has_changes_unavailable_reason,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn memory_workspaces(cwd: &AbsolutePathBuf) -> BTreeMap<String, TurnMetadataWorkspace> {
|
||||
let repo_root = get_git_repo_root(cwd).map(|root| root.to_string_lossy().into_owned());
|
||||
let (head_commit_hash, associated_remote_urls, has_changes) = tokio::join!(
|
||||
let (head_commit_hash, associated_remote_urls, has_changes_result) = tokio::join!(
|
||||
get_head_commit_hash(cwd),
|
||||
get_git_remote_urls_assume_git_repo(cwd),
|
||||
get_has_changes(cwd),
|
||||
try_get_has_changes(cwd),
|
||||
);
|
||||
let (has_changes, has_changes_unavailable_reason) = split_has_changes(has_changes_result);
|
||||
let workspace_git_metadata = WorkspaceGitMetadata {
|
||||
associated_remote_urls,
|
||||
latest_git_commit_hash: head_commit_hash.map(|sha| sha.0),
|
||||
has_changes,
|
||||
has_changes_unavailable_reason,
|
||||
};
|
||||
let mut workspaces = BTreeMap::new();
|
||||
if let Some(repo_root) = repo_root
|
||||
@@ -349,6 +356,15 @@ async fn memory_workspaces(cwd: &AbsolutePathBuf) -> BTreeMap<String, TurnMetada
|
||||
workspaces
|
||||
}
|
||||
|
||||
fn split_has_changes(
|
||||
result: Result<bool, codex_git_utils::GitReadError>,
|
||||
) -> (Option<bool>, Option<codex_git_utils::GitReadError>) {
|
||||
match result {
|
||||
Ok(has_changes) => (Some(has_changes), None),
|
||||
Err(reason) => (None, Some(reason)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "turn_metadata_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -31,6 +31,44 @@ fn test_mcp_turn_metadata_context() -> McpTurnMetadataContext<'static> {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_metadata_serializes_structured_has_changes_refusal() {
|
||||
let workspace = TurnMetadataWorkspace {
|
||||
associated_remote_urls: None,
|
||||
latest_git_commit_hash: None,
|
||||
has_changes: None,
|
||||
has_changes_unavailable_reason: Some(
|
||||
codex_git_utils::GitReadError::SelectedExecutableFilter {
|
||||
driver: "lfs".to_string(),
|
||||
path: "asset.bin".to_string(),
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(workspace).expect("serialize workspace"),
|
||||
serde_json::json!({
|
||||
"has_changes_unavailable_reason": {
|
||||
"reason": "selectedExecutableFilter",
|
||||
"driver": "lfs",
|
||||
"path": "asset.bin",
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(codex_git_utils::GitReadError::CommandFailed {
|
||||
operation: "status".to_string(),
|
||||
exit_code: Some(128),
|
||||
})
|
||||
.expect("serialize command failure"),
|
||||
serde_json::json!({
|
||||
"reason": "commandFailed",
|
||||
"operation": "status",
|
||||
"exitCode": 128,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fn test_responses_metadata_json(
|
||||
state: &TurnMetadataState,
|
||||
window_id: &str,
|
||||
|
||||
@@ -20,6 +20,7 @@ gix = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
regex = "1"
|
||||
schemars = { workspace = true }
|
||||
same-file = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
similar = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
@@ -12,12 +12,15 @@ use std::path::PathBuf;
|
||||
|
||||
use crate::FsmonitorOverride;
|
||||
use crate::apply_output::parse_git_apply_output;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::merge_driver::ensure_no_selected_merge_drivers;
|
||||
use crate::patch_paths::ensure_paths_do_not_enter_submodules;
|
||||
use crate::patch_paths::classify_patch_paths;
|
||||
use crate::patch_paths::extract_effective_paths_from_patch;
|
||||
use crate::patch_paths::stage_effective_paths;
|
||||
use crate::patch_paths::validate_gitlink_updates;
|
||||
use crate::safe_git::DISABLED_HOOKS_PATH;
|
||||
use crate::safe_git::ensure_no_selected_executable_git_filters;
|
||||
#[cfg(test)]
|
||||
use crate::safe_git::isolate_git_command_environment;
|
||||
|
||||
/// Parameters for invoking [`apply_git_patch`].
|
||||
@@ -46,16 +49,27 @@ pub struct ApplyGitResult {
|
||||
/// When [`ApplyGitRequest::preflight`] is `true`, this behaves like `git apply --check` and
|
||||
/// leaves the working tree untouched while still parsing the command output for diagnostics.
|
||||
pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
let git = GitRunner::for_cwd_io(&req.cwd)?;
|
||||
let mut cfg_parts = configured_git_config_parts();
|
||||
let git_root = resolve_git_root(&req.cwd, &cfg_parts)?;
|
||||
let git_root = resolve_git_root(&git, &req.cwd, &cfg_parts)?;
|
||||
|
||||
// Write unified diff into a temporary file
|
||||
let (tmpdir, patch_path) = write_temp_patch(&req.diff)?;
|
||||
// Keep tmpdir alive until function end to ensure the file exists
|
||||
let _guard = tmpdir;
|
||||
let patch_paths = extract_effective_paths_from_patch(&patch_path, req.revert)?;
|
||||
ensure_no_selected_executable_git_filters(&git_root, &patch_paths, &cfg_parts)?;
|
||||
ensure_paths_do_not_enter_submodules(&git_root, &patch_paths)?;
|
||||
let patch_paths = extract_effective_paths_from_patch(&git, &patch_path, req.revert)?;
|
||||
ensure_no_selected_executable_git_filters(&git, &git_root, &patch_paths, &cfg_parts)?;
|
||||
let guarded_paths = classify_patch_paths(&git, &git_root, &patch_paths)?;
|
||||
validate_gitlink_updates(
|
||||
&git,
|
||||
&git_root,
|
||||
&patch_paths,
|
||||
&patch_path,
|
||||
&req.diff,
|
||||
req.revert,
|
||||
&guarded_paths,
|
||||
)?;
|
||||
let index_only_gitlink_patch = guarded_paths.exact_gitlinks.len() == patch_paths.len();
|
||||
|
||||
cfg_parts.extend(safe_git_config_parts());
|
||||
let patch_arg = patch_path.to_string_lossy().to_string();
|
||||
@@ -63,12 +77,15 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
// Optional preflight: dry-run only; do not modify working tree
|
||||
if req.preflight {
|
||||
let mut check_args = vec!["apply".to_string(), "--check".to_string()];
|
||||
if index_only_gitlink_patch {
|
||||
check_args.push("--cached".to_string());
|
||||
}
|
||||
if req.revert {
|
||||
check_args.push("-R".to_string());
|
||||
}
|
||||
check_args.push(patch_arg);
|
||||
let rendered = render_command_for_log(&git_root, &cfg_parts, &check_args);
|
||||
let (c_code, c_out, c_err) = run_git(&git_root, &cfg_parts, &check_args)?;
|
||||
let (c_code, c_out, c_err) = run_git(&git, &git_root, &cfg_parts, &check_args)?;
|
||||
let (mut applied_paths, mut skipped_paths, mut conflicted_paths) =
|
||||
parse_git_apply_output(&c_out, &c_err);
|
||||
applied_paths.sort();
|
||||
@@ -90,27 +107,44 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
|
||||
// Avoid three-way machinery entirely when the patch applies cleanly.
|
||||
// A selected merge driver is relevant only to the three-way fallback.
|
||||
let mut plain_check_args = vec![
|
||||
"apply".to_string(),
|
||||
"--check".to_string(),
|
||||
"--index".to_string(),
|
||||
];
|
||||
let mut plain_check_args = vec!["apply".to_string(), "--check".to_string()];
|
||||
plain_check_args.push(
|
||||
if index_only_gitlink_patch {
|
||||
"--cached"
|
||||
} else {
|
||||
"--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_git(&git_root, &cfg_parts, &plain_check_args)?;
|
||||
let (plain_check_code, _, _) = run_git(&git, &git_root, &cfg_parts, &plain_check_args)?;
|
||||
|
||||
let mut args = vec!["apply".to_string()];
|
||||
if plain_check_code != 0 {
|
||||
ensure_no_selected_merge_drivers(&git_root, &patch_paths, &cfg_parts)?;
|
||||
ensure_no_selected_merge_drivers(&git, &git_root, &patch_paths, &cfg_parts)?;
|
||||
if req.revert {
|
||||
if !guarded_paths.exact_gitlinks.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"refusing to stage an exact gitlink for a reverse three-way apply",
|
||||
));
|
||||
}
|
||||
// Stage WT paths first to avoid index mismatch on three-way revert.
|
||||
stage_effective_paths(&git_root, &patch_paths)?;
|
||||
stage_effective_paths(&git, &git_root, &patch_paths)?;
|
||||
}
|
||||
args.push("--3way".to_string());
|
||||
} else {
|
||||
args.push("--index".to_string());
|
||||
args.push(
|
||||
if index_only_gitlink_patch {
|
||||
"--cached"
|
||||
} else {
|
||||
"--index"
|
||||
}
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if req.revert {
|
||||
args.push("-R".to_string());
|
||||
@@ -118,7 +152,7 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
args.push(patch_arg);
|
||||
|
||||
let cmd_for_log = render_command_for_log(&git_root, &cfg_parts, &args);
|
||||
let (code, stdout, stderr) = run_git(&git_root, &cfg_parts, &args)?;
|
||||
let (code, stdout, stderr) = run_git(&git, &git_root, &cfg_parts, &args)?;
|
||||
|
||||
let (mut applied_paths, mut skipped_paths, mut conflicted_paths) =
|
||||
parse_git_apply_output(&stdout, &stderr);
|
||||
@@ -140,16 +174,19 @@ pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_git_root(cwd: &Path, git_config_args: &[String]) -> io::Result<PathBuf> {
|
||||
fn resolve_git_root(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<PathBuf> {
|
||||
let requested_cwd = std::fs::canonicalize(cwd)?;
|
||||
let mut command = std::process::Command::new("git");
|
||||
isolate_git_command_environment(&mut command);
|
||||
let out = command
|
||||
let mut command = git.command();
|
||||
command
|
||||
.args(git_config_args)
|
||||
.arg("rev-parse")
|
||||
.arg("--show-toplevel")
|
||||
.current_dir(&requested_cwd)
|
||||
.output()?;
|
||||
.current_dir(&requested_cwd);
|
||||
let out = git.output(command)?;
|
||||
let code = out.status.code().unwrap_or(-1);
|
||||
if code != 0 {
|
||||
return Err(io::Error::other(format!(
|
||||
@@ -209,19 +246,20 @@ pub(crate) fn write_temp_patch(diff: &str) -> io::Result<(tempfile::TempDir, Pat
|
||||
}
|
||||
|
||||
pub(crate) fn run_git(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_cfg: &[String],
|
||||
args: &[String],
|
||||
) -> io::Result<(i32, String, String)> {
|
||||
let mut cmd = std::process::Command::new("git");
|
||||
isolate_git_command_environment(&mut cmd);
|
||||
let mut cmd = git.command();
|
||||
for p in git_cfg {
|
||||
cmd.arg(p);
|
||||
}
|
||||
for a in args {
|
||||
cmd.arg(a);
|
||||
}
|
||||
let out = cmd.current_dir(cwd).output()?;
|
||||
cmd.current_dir(cwd);
|
||||
let out = git.output(cmd)?;
|
||||
let code = out.status.code().unwrap_or(-1);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
|
||||
@@ -769,7 +807,9 @@ diff --git a/ghost.txt b/ghost.txt\n--- a/ghost.txt\n+++ b/ghost.txt\n@@ -1,1 +1
|
||||
"test.txt filter=codex-test\n",
|
||||
)
|
||||
.expect("attributes");
|
||||
let git = GitRunner::for_cwd_io(repo.path()).expect("trusted Git");
|
||||
let error = ensure_no_selected_executable_git_filters(
|
||||
&git,
|
||||
repo.path(),
|
||||
&["test.txt".to_string()],
|
||||
&config_args,
|
||||
@@ -796,7 +836,9 @@ diff --git a/ghost.txt b/ghost.txt\n--- a/ghost.txt\n+++ b/ghost.txt\n@@ -1,1 +1
|
||||
);
|
||||
assert_eq!(config_code, 0, "configure core.worktree: {config_err}");
|
||||
|
||||
let error = resolve_git_root(&attacker, &[]).expect_err("reject redirected worktree");
|
||||
let git = GitRunner::for_cwd_io(&attacker).expect("trusted Git");
|
||||
let error =
|
||||
resolve_git_root(&git, &attacker, &[]).expect_err("reject redirected worktree");
|
||||
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert!(error.to_string().contains("instead of expected worktree"));
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ use std::path::PathBuf;
|
||||
use std::process::ExitStatus;
|
||||
use std::string::FromUtf8Error;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
use walkdir::Error as WalkdirError;
|
||||
|
||||
@@ -33,3 +35,38 @@ pub enum GitToolingError {
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
/// Stable, caller-visible reasons that a read-only Git operation was refused
|
||||
/// or could not produce a complete result.
|
||||
#[derive(Clone, Debug, Deserialize, Error, PartialEq, Eq, Serialize)]
|
||||
#[serde(
|
||||
tag = "reason",
|
||||
rename_all = "camelCase",
|
||||
rename_all_fields = "camelCase"
|
||||
)]
|
||||
pub enum GitReadError {
|
||||
#[error("no trusted Git executable is available")]
|
||||
NoTrustedGit,
|
||||
#[error("{path:?} is not a Git repository")]
|
||||
NotRepository { path: PathBuf },
|
||||
#[error("Git resolved {reported_root:?} instead of expected root {expected_root:?}")]
|
||||
RepositoryRootMismatch {
|
||||
expected_root: PathBuf,
|
||||
reported_root: PathBuf,
|
||||
},
|
||||
#[error("no remote base commit is available")]
|
||||
NoRemoteBase,
|
||||
#[error("Git operation {operation:?} timed out")]
|
||||
CommandTimedOut { operation: String },
|
||||
#[error("Git operation {operation:?} failed with exit code {exit_code:?}")]
|
||||
CommandFailed {
|
||||
operation: String,
|
||||
exit_code: Option<i32>,
|
||||
},
|
||||
#[error("Git operation {operation:?} returned invalid output")]
|
||||
InvalidOutput { operation: String },
|
||||
#[error("executable filter {driver:?} is selected for {path:?}")]
|
||||
SelectedExecutableFilter { driver: String, path: String },
|
||||
#[error("untracked path {path:?} is an embedded repository or directory")]
|
||||
EmbeddedRepository { path: String },
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
use std::ffi::OsStr;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
use crate::GitReadError;
|
||||
use crate::git_config::path_is_within;
|
||||
use crate::safe_git::isolate_git_command_environment;
|
||||
use crate::safe_git::isolate_tokio_git_command_environment;
|
||||
|
||||
/// A Git executable resolved outside every repository-controlled root for one
|
||||
/// internal operation.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct GitRunner {
|
||||
executable: PathBuf,
|
||||
}
|
||||
|
||||
impl GitRunner {
|
||||
pub(crate) fn for_cwd(cwd: &Path) -> Result<Self, GitReadError> {
|
||||
let roots = untrusted_roots_for_cwd(cwd)?;
|
||||
let search_path = std::env::var_os("PATH").ok_or(GitReadError::NoTrustedGit)?;
|
||||
Self::from_search_path(&roots, &search_path)
|
||||
}
|
||||
|
||||
pub(crate) fn for_cwd_io(cwd: &Path) -> io::Result<Self> {
|
||||
Self::for_cwd(cwd).map_err(|error| io::Error::new(io::ErrorKind::NotFound, error))
|
||||
}
|
||||
|
||||
pub(crate) fn command(&self) -> Command {
|
||||
Command::new(&self.executable)
|
||||
}
|
||||
|
||||
pub(crate) fn tokio_command(&self) -> tokio::process::Command {
|
||||
tokio::process::Command::new(&self.executable)
|
||||
}
|
||||
|
||||
/// Spawn a configured synchronous command after applying the final
|
||||
/// repository-selector environment lock.
|
||||
///
|
||||
/// PR #29470 composes its one local-only transport policy at this final
|
||||
/// boundary so caller configuration cannot restore transport authority.
|
||||
pub(crate) fn output(&self, mut command: Command) -> io::Result<std::process::Output> {
|
||||
isolate_git_command_environment(&mut command);
|
||||
command.output()
|
||||
}
|
||||
|
||||
/// Like [`Self::output`], but restores one internally generated scratch
|
||||
/// index after inherited/caller-provided selectors have been removed.
|
||||
pub(crate) fn output_with_index_file(
|
||||
&self,
|
||||
mut command: Command,
|
||||
index_file: &Path,
|
||||
) -> io::Result<std::process::Output> {
|
||||
isolate_git_command_environment(&mut command);
|
||||
command.env("GIT_INDEX_FILE", index_file);
|
||||
command.output()
|
||||
}
|
||||
|
||||
/// Spawn a configured Tokio command after applying the final
|
||||
/// repository-selector environment lock.
|
||||
pub(crate) async fn output_tokio(
|
||||
&self,
|
||||
mut command: tokio::process::Command,
|
||||
) -> io::Result<std::process::Output> {
|
||||
isolate_tokio_git_command_environment(&mut command);
|
||||
command.output().await
|
||||
}
|
||||
|
||||
fn from_search_path(
|
||||
untrusted_roots: &[PathBuf],
|
||||
search_path: &OsStr,
|
||||
) -> Result<Self, GitReadError> {
|
||||
for directory in std::env::split_paths(search_path) {
|
||||
if !directory.is_absolute() {
|
||||
continue;
|
||||
}
|
||||
let candidate = directory.join(git_executable_name());
|
||||
if untrusted_roots
|
||||
.iter()
|
||||
.any(|root| path_is_within(&candidate, root))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Ok(canonical_parent) = std::fs::canonicalize(&directory) else {
|
||||
continue;
|
||||
};
|
||||
if untrusted_roots
|
||||
.iter()
|
||||
.any(|root| path_is_within(&canonical_parent, root))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Ok(canonical_candidate) = std::fs::canonicalize(&candidate) else {
|
||||
continue;
|
||||
};
|
||||
if untrusted_roots
|
||||
.iter()
|
||||
.any(|root| path_is_within(&canonical_candidate, root))
|
||||
|| !is_native_executable_file(&canonical_candidate)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Ok(Self {
|
||||
// Preserve the absolute PATH entry rather than replacing it
|
||||
// with the canonical target: Git may be installed through a
|
||||
// trusted multicall symlink whose argv[0] selects Git mode.
|
||||
executable: candidate,
|
||||
});
|
||||
}
|
||||
Err(GitReadError::NoTrustedGit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn executable(&self) -> &Path {
|
||||
&self.executable
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn from_executable_for_test(executable: PathBuf) -> Self {
|
||||
Self { executable }
|
||||
}
|
||||
}
|
||||
|
||||
fn untrusted_roots_for_cwd(cwd: &Path) -> Result<Vec<PathBuf>, GitReadError> {
|
||||
let canonical_cwd = std::fs::canonicalize(cwd).map_err(|_| GitReadError::NotRepository {
|
||||
path: cwd.to_path_buf(),
|
||||
})?;
|
||||
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 mut roots = vec![worktree_root.clone()];
|
||||
if let Some(main_root) = linked_main_worktree_root(&worktree_root)
|
||||
&& !roots.contains(&main_root)
|
||||
{
|
||||
roots.push(main_root);
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
fn linked_main_worktree_root(worktree_root: &Path) -> Option<PathBuf> {
|
||||
let dot_git = worktree_root.join(".git");
|
||||
if dot_git.is_dir() {
|
||||
return None;
|
||||
}
|
||||
let contents = std::fs::read_to_string(dot_git).ok()?;
|
||||
let git_dir = contents.trim().strip_prefix("gitdir:")?.trim();
|
||||
if git_dir.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let git_dir = PathBuf::from(git_dir);
|
||||
let git_dir = if git_dir.is_absolute() {
|
||||
git_dir
|
||||
} else {
|
||||
worktree_root.join(git_dir)
|
||||
};
|
||||
let git_dir = std::fs::canonicalize(git_dir).ok()?;
|
||||
let worktrees = git_dir.parent()?;
|
||||
if worktrees.file_name()? != OsStr::new("worktrees") {
|
||||
return None;
|
||||
}
|
||||
std::fs::canonicalize(worktrees.parent()?.parent()?).ok()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn git_executable_name() -> &'static str {
|
||||
"git.exe"
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn git_executable_name() -> &'static str {
|
||||
"git"
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn is_native_executable_file(path: &Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
std::fs::metadata(path)
|
||||
.is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_native_executable_file(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(OsStr::to_str)
|
||||
.is_some_and(|extension| extension.eq_ignore_ascii_case("exe"))
|
||||
&& std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file())
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn is_native_executable_file(path: &Path) -> bool {
|
||||
std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "git_command_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,132 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn write_executable(path: &Path, body: &str) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
std::fs::write(path, body).expect("write executable");
|
||||
let mut permissions = std::fs::metadata(path)
|
||||
.expect("executable metadata")
|
||||
.permissions();
|
||||
permissions.set_mode(0o755);
|
||||
std::fs::set_permissions(path, permissions).expect("set executable permissions");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn resolver_skips_repository_controlled_git_and_runs_external_candidate() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let repo = fixture.path().join("repo");
|
||||
let repo_bin = repo.join("bin");
|
||||
let trusted_bin = fixture.path().join("trusted-bin");
|
||||
std::fs::create_dir_all(&repo_bin).expect("repo bin");
|
||||
std::fs::create_dir_all(&trusted_bin).expect("trusted bin");
|
||||
let marker = repo.join("repository-git-ran");
|
||||
write_executable(
|
||||
&repo_bin.join("git"),
|
||||
&format!("#!/bin/sh\nprintf ran > '{}'\n", marker.display()),
|
||||
);
|
||||
write_executable(&trusted_bin.join("git"), "#!/bin/sh\nprintf 'trusted\\n'\n");
|
||||
|
||||
let path = std::env::join_paths([repo_bin, trusted_bin.clone()]).expect("PATH");
|
||||
let roots = vec![std::fs::canonicalize(&repo).expect("canonical repo")];
|
||||
let runner = GitRunner::from_search_path(&roots, &path).expect("trusted Git");
|
||||
assert_eq!(runner.executable(), trusted_bin.join("git"));
|
||||
let output = runner.output(runner.command()).expect("run trusted Git");
|
||||
assert_eq!(output.stdout, b"trusted\n");
|
||||
assert!(!marker.exists(), "repository-controlled Git must not run");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn resolver_rejects_repository_candidates_symlinks_and_relative_entries() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let repo = fixture.path().join("repo");
|
||||
let repo_bin = repo.join("bin");
|
||||
let outside = fixture.path().join("outside");
|
||||
std::fs::create_dir_all(&repo_bin).expect("repo bin");
|
||||
std::fs::create_dir_all(&outside).expect("outside");
|
||||
write_executable(&repo_bin.join("owned-git"), "#!/bin/sh\nexit 0\n");
|
||||
std::os::unix::fs::symlink(repo_bin.join("owned-git"), outside.join("git"))
|
||||
.expect("outside symlink into repository");
|
||||
|
||||
let roots = vec![std::fs::canonicalize(&repo).expect("canonical repo")];
|
||||
let path =
|
||||
std::env::join_paths([PathBuf::new(), PathBuf::from("relative"), outside]).expect("PATH");
|
||||
assert_eq!(
|
||||
GitRunner::from_search_path(&roots, &path).unwrap_err(),
|
||||
GitReadError::NoTrustedGit
|
||||
);
|
||||
|
||||
let trusted = fixture.path().join("trusted");
|
||||
std::fs::create_dir_all(&trusted).expect("trusted");
|
||||
write_executable(&trusted.join("git"), "#!/bin/sh\nexit 0\n");
|
||||
std::fs::remove_file(repo_bin.join("git")).ok();
|
||||
std::os::unix::fs::symlink(trusted.join("git"), repo_bin.join("git"))
|
||||
.expect("repository symlink out");
|
||||
let path = std::env::join_paths([repo_bin]).expect("PATH");
|
||||
assert_eq!(
|
||||
GitRunner::from_search_path(&roots, &path).unwrap_err(),
|
||||
GitReadError::NoTrustedGit
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn resolver_skips_non_executable_files() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let repo = fixture.path().join("repo");
|
||||
let bin = fixture.path().join("bin");
|
||||
std::fs::create_dir_all(&repo).expect("repo");
|
||||
std::fs::create_dir_all(&bin).expect("bin");
|
||||
std::fs::write(bin.join("git"), "not executable\n").expect("candidate");
|
||||
let roots = vec![std::fs::canonicalize(repo).expect("canonical repo")];
|
||||
let path = std::env::join_paths([bin]).expect("PATH");
|
||||
assert_eq!(
|
||||
GitRunner::from_search_path(&roots, &path).unwrap_err(),
|
||||
GitReadError::NoTrustedGit
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_worktree_marks_main_and_linked_roots_untrusted() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let main = fixture.path().join("main");
|
||||
let linked = fixture.path().join("linked");
|
||||
let git_dir = main.join(".git/worktrees/linked");
|
||||
std::fs::create_dir_all(&git_dir).expect("linked Git directory");
|
||||
std::fs::create_dir_all(&linked).expect("linked worktree");
|
||||
std::fs::write(
|
||||
linked.join(".git"),
|
||||
format!("gitdir: {}\n", git_dir.display()),
|
||||
)
|
||||
.expect("linked .git file");
|
||||
|
||||
let roots = untrusted_roots_for_cwd(&linked).expect("untrusted roots");
|
||||
assert_eq!(
|
||||
roots,
|
||||
vec![
|
||||
std::fs::canonicalize(&linked).expect("canonical linked root"),
|
||||
std::fs::canonicalize(&main).expect("canonical main root"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn resolver_selects_native_git_exe_only() {
|
||||
let fixture = tempfile::tempdir().expect("fixture");
|
||||
let repo = fixture.path().join("repo");
|
||||
let scripts = fixture.path().join("scripts");
|
||||
let native = fixture.path().join("native");
|
||||
std::fs::create_dir_all(&repo).expect("repo");
|
||||
std::fs::create_dir_all(&scripts).expect("scripts");
|
||||
std::fs::create_dir_all(&native).expect("native");
|
||||
std::fs::write(scripts.join("git.cmd"), "@exit /b 0\r\n").expect("script");
|
||||
std::fs::write(native.join("git.exe"), b"MZ").expect("native executable fixture");
|
||||
let roots = vec![std::fs::canonicalize(repo).expect("canonical repo")];
|
||||
let path = std::env::join_paths([scripts, native.clone()]).expect("PATH");
|
||||
let runner = GitRunner::from_search_path(&roots, &path).expect("native Git");
|
||||
assert_eq!(runner.executable(), native.join("git.exe"));
|
||||
}
|
||||
@@ -12,12 +12,6 @@ pub(crate) enum GitConfigScope {
|
||||
Command,
|
||||
}
|
||||
|
||||
impl GitConfigScope {
|
||||
pub(crate) fn is_system_or_global(self) -> bool {
|
||||
matches!(self, Self::System | Self::Global)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct GitConfigEntry {
|
||||
pub(crate) scope: GitConfigScope,
|
||||
@@ -67,6 +61,59 @@ pub(crate) fn parse_effective_config(
|
||||
Ok(effective)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub(crate) fn parse_effective_config_with_origins(
|
||||
output: &[u8],
|
||||
) -> io::Result<BTreeMap<String, GitConfigEntry>> {
|
||||
if output.is_empty() {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let Some(body) = output.strip_suffix(&[0]) else {
|
||||
return Err(invalid_config_output("unterminated Git config output"));
|
||||
};
|
||||
let fields = body.split(|byte| *byte == 0).collect::<Vec<_>>();
|
||||
if fields.len() % 2 != 0 {
|
||||
return Err(invalid_config_output("incomplete Git config record"));
|
||||
}
|
||||
|
||||
let mut effective = BTreeMap::new();
|
||||
for record in fields.chunks_exact(2) {
|
||||
let origin = parse_utf8_field(record[0], "config origin")?;
|
||||
if origin.is_empty() {
|
||||
return Err(invalid_config_output("empty Git config origin"));
|
||||
}
|
||||
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",
|
||||
));
|
||||
};
|
||||
if key.is_empty() {
|
||||
return Err(invalid_config_output("empty Git config key"));
|
||||
}
|
||||
let scope = if origin == "command line:" {
|
||||
GitConfigScope::Command
|
||||
} else {
|
||||
// Older Git does not expose the scope. Selection depends on the
|
||||
// emitted precedence order, not on this informational label.
|
||||
GitConfigScope::Local
|
||||
};
|
||||
effective.insert(
|
||||
key.to_string(),
|
||||
GitConfigEntry {
|
||||
scope,
|
||||
origin: origin.to_string(),
|
||||
key: key.to_string(),
|
||||
value: value.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(effective)
|
||||
}
|
||||
|
||||
pub(crate) fn path_is_within(path: &Path, root: &Path) -> bool {
|
||||
let mut path_components = path.components();
|
||||
for root_component in root.components() {
|
||||
|
||||
@@ -41,6 +41,32 @@ fn rejects_malformed_config_records() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_legacy_origin_records_in_effective_order() {
|
||||
let output = b"file:/tmp/global\0filter.demo.clean\nfirst\0\
|
||||
file:/repo/.git/config\0filter.demo.clean\n\0\
|
||||
command line:\0merge.Name.driver\nhelper %A %B\0";
|
||||
let entries = parse_effective_config_with_origins(output).expect("parse legacy config");
|
||||
assert_eq!(
|
||||
entries.get("filter.demo.clean"),
|
||||
Some(&GitConfigEntry {
|
||||
scope: GitConfigScope::Local,
|
||||
origin: "file:/repo/.git/config".to_string(),
|
||||
key: "filter.demo.clean".to_string(),
|
||||
value: String::new(),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
entries.get("merge.Name.driver"),
|
||||
Some(&GitConfigEntry {
|
||||
scope: GitConfigScope::Command,
|
||||
origin: "command line:".to_string(),
|
||||
key: "merge.Name.driver".to_string(),
|
||||
value: "helper %A %B".to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_containment_uses_component_boundaries() {
|
||||
let root = Path::new("/repo/root");
|
||||
|
||||
+130
-61
@@ -13,16 +13,16 @@ use futures::future::join_all;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use ts_rs::TS;
|
||||
|
||||
use crate::GitReadError;
|
||||
use crate::GitSha;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::safe_git::DISABLED_HOOKS_PATH;
|
||||
use crate::safe_git::GIT_COMMAND_TIMEOUT;
|
||||
use crate::safe_git::has_selected_executable_filters_from;
|
||||
use crate::safe_git::isolate_tokio_git_command_environment;
|
||||
use crate::safe_git::safe_untracked_paths_for_diff;
|
||||
use crate::safe_git::safe_untracked_paths_for_diff_checked;
|
||||
use crate::safe_git::selected_executable_filter_from;
|
||||
|
||||
/// Return `true` if the project folder specified by the `Config` is inside a
|
||||
/// Git repository.
|
||||
@@ -82,7 +82,7 @@ pub struct GitInfo {
|
||||
pub repository_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct GitDiffToRemote {
|
||||
pub sha: GitSha,
|
||||
pub diff: String,
|
||||
@@ -289,23 +289,34 @@ fn trim_git_suffix(value: &str) -> &str {
|
||||
}
|
||||
|
||||
pub async fn get_has_changes(cwd: &Path) -> Option<bool> {
|
||||
let git = Path::new("git");
|
||||
if has_selected_executable_filters_from(git, cwd).await? {
|
||||
return None;
|
||||
try_get_has_changes(cwd).await.ok()
|
||||
}
|
||||
|
||||
pub async fn try_get_has_changes(cwd: &Path) -> Result<bool, GitReadError> {
|
||||
let git = GitRunner::for_cwd(cwd)?;
|
||||
if let Some((driver, path)) = selected_executable_filter_from(&git, cwd).await? {
|
||||
return Err(GitReadError::SelectedExecutableFilter {
|
||||
driver,
|
||||
path: String::from_utf8_lossy(&path).into_owned(),
|
||||
});
|
||||
}
|
||||
let fsmonitor = detect_local_fsmonitor_override(git, cwd).await;
|
||||
let output = run_git_command_with_timeout_from(
|
||||
git,
|
||||
let fsmonitor = detect_local_fsmonitor_override(&git, cwd).await;
|
||||
let output = try_run_git_command_with_timeout_from(
|
||||
&git,
|
||||
&["status", "--porcelain", "--ignore-submodules=dirty"],
|
||||
cwd,
|
||||
fsmonitor,
|
||||
"status",
|
||||
)
|
||||
.await?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
return Err(GitReadError::CommandFailed {
|
||||
operation: "status".to_string(),
|
||||
exit_code: output.status.code(),
|
||||
});
|
||||
}
|
||||
|
||||
Some(!output.stdout.is_empty())
|
||||
Ok(!output.stdout.is_empty())
|
||||
}
|
||||
|
||||
fn parse_git_remote_urls(stdout: &str) -> Option<BTreeMap<String, String>> {
|
||||
@@ -396,14 +407,31 @@ pub async fn recent_commits(cwd: &Path, limit: usize) -> Vec<CommitLogEntry> {
|
||||
|
||||
/// Returns the closest git sha to HEAD that is on a remote as well as the diff to that sha.
|
||||
pub async fn git_diff_to_remote(cwd: &Path) -> Option<GitDiffToRemote> {
|
||||
get_git_repo_root(cwd)?;
|
||||
try_git_diff_to_remote(cwd).await.ok()
|
||||
}
|
||||
|
||||
let remotes = get_git_remotes(cwd).await?;
|
||||
let branches = branch_ancestry(cwd).await?;
|
||||
let base_sha = find_closest_sha(cwd, &branches, &remotes).await?;
|
||||
let diff = diff_against_sha(cwd, &base_sha).await?;
|
||||
pub async fn try_git_diff_to_remote(cwd: &Path) -> Result<GitDiffToRemote, GitReadError> {
|
||||
let canonical_cwd = std::fs::canonicalize(cwd).map_err(|_| GitReadError::NotRepository {
|
||||
path: cwd.to_path_buf(),
|
||||
})?;
|
||||
get_git_repo_root(&canonical_cwd).ok_or_else(|| GitReadError::NotRepository {
|
||||
path: canonical_cwd.clone(),
|
||||
})?;
|
||||
let git = GitRunner::for_cwd(&canonical_cwd)?;
|
||||
let untracked = safe_untracked_paths_for_diff_checked(&git, &canonical_cwd).await?;
|
||||
|
||||
Some(GitDiffToRemote {
|
||||
let remotes = get_git_remotes(&canonical_cwd)
|
||||
.await
|
||||
.ok_or(GitReadError::NoRemoteBase)?;
|
||||
let branches = branch_ancestry(&canonical_cwd)
|
||||
.await
|
||||
.ok_or(GitReadError::NoRemoteBase)?;
|
||||
let base_sha = find_closest_sha(&canonical_cwd, &branches, &remotes)
|
||||
.await
|
||||
.ok_or(GitReadError::NoRemoteBase)?;
|
||||
let diff = try_diff_against_sha(&git, &canonical_cwd, &base_sha, untracked).await?;
|
||||
|
||||
Ok(GitDiffToRemote {
|
||||
sha: base_sha,
|
||||
diff,
|
||||
})
|
||||
@@ -413,17 +441,12 @@ pub async fn git_diff_to_remote(cwd: &Path) -> Option<GitDiffToRemote> {
|
||||
async fn run_git_command_with_timeout(args: &[&str], cwd: &Path) -> Option<std::process::Output> {
|
||||
// These callers only inspect repository metadata. Worktree workflows probe
|
||||
// once and pass their override directly to the lower-level runner.
|
||||
run_git_command_with_timeout_from(
|
||||
Path::new("git"),
|
||||
args,
|
||||
cwd,
|
||||
crate::FsmonitorOverride::Disabled,
|
||||
)
|
||||
.await
|
||||
let git = GitRunner::for_cwd(cwd).ok()?;
|
||||
run_git_command_with_timeout_from(&git, args, cwd, crate::FsmonitorOverride::Disabled).await
|
||||
}
|
||||
|
||||
struct LocalFsmonitorProbeRunner<'a> {
|
||||
git: &'a Path,
|
||||
git: &'a GitRunner,
|
||||
cwd: &'a Path,
|
||||
}
|
||||
|
||||
@@ -431,30 +454,40 @@ impl crate::FsmonitorProbeRunner for LocalFsmonitorProbeRunner<'_> {
|
||||
async fn run_probe(&mut self, args: &[&str]) -> Option<Vec<u8>> {
|
||||
// Both probes are fast, bounded metadata queries that do not inspect the
|
||||
// worktree or index, so do not reduce the requested command's timeout.
|
||||
let mut command = Command::new(self.git);
|
||||
isolate_tokio_git_command_environment(&mut command);
|
||||
let mut command = self.git.tokio_command();
|
||||
command.args(args).current_dir(self.cwd).kill_on_drop(true);
|
||||
match timeout(GIT_COMMAND_TIMEOUT, command.output()).await {
|
||||
match timeout(GIT_COMMAND_TIMEOUT, self.git.output_tokio(command)).await {
|
||||
Ok(Ok(output)) if output.status.success() => Some(output.stdout),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn detect_local_fsmonitor_override(git: &Path, cwd: &Path) -> crate::FsmonitorOverride {
|
||||
async fn detect_local_fsmonitor_override(git: &GitRunner, cwd: &Path) -> crate::FsmonitorOverride {
|
||||
let mut runner = LocalFsmonitorProbeRunner { git, cwd };
|
||||
crate::detect_fsmonitor_override(&mut runner).await
|
||||
}
|
||||
|
||||
async fn run_git_command_with_timeout_from(
|
||||
git: &Path,
|
||||
git: &GitRunner,
|
||||
args: &[&str],
|
||||
cwd: &Path,
|
||||
fsmonitor: crate::FsmonitorOverride,
|
||||
) -> Option<std::process::Output> {
|
||||
try_run_git_command_with_timeout_from(git, args, cwd, fsmonitor, "gitMetadata")
|
||||
.await
|
||||
.ok()
|
||||
}
|
||||
|
||||
async fn try_run_git_command_with_timeout_from(
|
||||
git: &GitRunner,
|
||||
args: &[&str],
|
||||
cwd: &Path,
|
||||
fsmonitor: crate::FsmonitorOverride,
|
||||
operation: &str,
|
||||
) -> Result<std::process::Output, GitReadError> {
|
||||
let disabled_hooks = format!("core.hooksPath={DISABLED_HOOKS_PATH}");
|
||||
let mut command = Command::new(git);
|
||||
isolate_tokio_git_command_environment(&mut command);
|
||||
let mut command = git.tokio_command();
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
// Keep internal Git commands independent of repository-selected hooks
|
||||
@@ -464,11 +497,18 @@ async fn run_git_command_with_timeout_from(
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.kill_on_drop(true);
|
||||
let result = timeout(GIT_COMMAND_TIMEOUT, command.output()).await;
|
||||
|
||||
match result {
|
||||
Ok(Ok(output)) => Some(output),
|
||||
_ => None, // Timeout or error
|
||||
match timeout(GIT_COMMAND_TIMEOUT, git.output_tokio(command)).await {
|
||||
Err(_) => Err(GitReadError::CommandTimedOut {
|
||||
operation: operation.to_string(),
|
||||
}),
|
||||
Ok(Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
Err(GitReadError::NoTrustedGit)
|
||||
}
|
||||
Ok(Err(_)) => Err(GitReadError::CommandFailed {
|
||||
operation: operation.to_string(),
|
||||
exit_code: None,
|
||||
}),
|
||||
Ok(Ok(output)) => Ok(output),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -748,11 +788,14 @@ async fn find_closest_sha(cwd: &Path, branches: &[String], remotes: &[String]) -
|
||||
closest_sha.map(|(sha, _)| sha)
|
||||
}
|
||||
|
||||
async fn diff_against_sha(cwd: &Path, sha: &GitSha) -> Option<String> {
|
||||
let git = Path::new("git");
|
||||
let untracked = safe_untracked_paths_for_diff(git, cwd).await?;
|
||||
async fn try_diff_against_sha(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
sha: &GitSha,
|
||||
untracked: Vec<Vec<u8>>,
|
||||
) -> Result<String, GitReadError> {
|
||||
let fsmonitor = detect_local_fsmonitor_override(git, cwd).await;
|
||||
let output = run_git_command_with_timeout_from(
|
||||
let output = try_run_git_command_with_timeout_from(
|
||||
git,
|
||||
&[
|
||||
"diff",
|
||||
@@ -764,35 +807,51 @@ async fn diff_against_sha(cwd: &Path, sha: &GitSha) -> Option<String> {
|
||||
],
|
||||
cwd,
|
||||
fsmonitor,
|
||||
"diffToRemote",
|
||||
)
|
||||
.await?;
|
||||
// 0 is success and no diff.
|
||||
// 1 is success but there is a diff.
|
||||
let exit_ok = output.status.code().is_some_and(|c| c == 0 || c == 1);
|
||||
if !exit_ok {
|
||||
return None;
|
||||
return Err(GitReadError::CommandFailed {
|
||||
operation: "diffToRemote".to_string(),
|
||||
exit_code: output.status.code(),
|
||||
});
|
||||
}
|
||||
let mut diff = String::from_utf8(output.stdout).ok()?;
|
||||
let mut diff = String::from_utf8(output.stdout).map_err(|_| GitReadError::InvalidOutput {
|
||||
operation: "diffToRemote".to_string(),
|
||||
})?;
|
||||
|
||||
if !untracked.is_empty() {
|
||||
let untracked = untracked
|
||||
.into_iter()
|
||||
.map(git_path_bytes_to_os_string)
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.ok_or_else(|| GitReadError::InvalidOutput {
|
||||
operation: "untrackedPaths".to_string(),
|
||||
})?;
|
||||
let futures_iter = untracked.into_iter().map(|file| async move {
|
||||
run_git_no_index_diff_from(git, cwd, fsmonitor, &file).await
|
||||
try_run_git_no_index_diff_from(git, cwd, fsmonitor, &file).await
|
||||
});
|
||||
let results = join_all(futures_iter).await;
|
||||
for extra in results.into_iter().flatten() {
|
||||
if extra.status.code().is_some_and(|c| c == 0 || c == 1)
|
||||
&& let Ok(s) = String::from_utf8(extra.stdout)
|
||||
{
|
||||
diff.push_str(&s);
|
||||
for result in results {
|
||||
let extra = result?;
|
||||
if !extra.status.code().is_some_and(|c| c == 0 || c == 1) {
|
||||
return Err(GitReadError::CommandFailed {
|
||||
operation: "untrackedDiff".to_string(),
|
||||
exit_code: extra.status.code(),
|
||||
});
|
||||
}
|
||||
let extra =
|
||||
String::from_utf8(extra.stdout).map_err(|_| GitReadError::InvalidOutput {
|
||||
operation: "untrackedDiff".to_string(),
|
||||
})?;
|
||||
diff.push_str(&extra);
|
||||
}
|
||||
}
|
||||
|
||||
Some(diff)
|
||||
Ok(diff)
|
||||
}
|
||||
|
||||
fn git_path_bytes_to_os_string(path: Vec<u8>) -> Option<std::ffi::OsString> {
|
||||
@@ -807,16 +866,15 @@ fn git_path_bytes_to_os_string(path: Vec<u8>) -> Option<std::ffi::OsString> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_git_no_index_diff_from(
|
||||
git: &Path,
|
||||
async fn try_run_git_no_index_diff_from(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
fsmonitor: crate::FsmonitorOverride,
|
||||
path: &OsStr,
|
||||
) -> Option<std::process::Output> {
|
||||
) -> Result<std::process::Output, GitReadError> {
|
||||
let disabled_hooks = format!("core.hooksPath={DISABLED_HOOKS_PATH}");
|
||||
let null_device = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
||||
let mut command = Command::new(git);
|
||||
isolate_tokio_git_command_environment(&mut command);
|
||||
let mut command = git.tokio_command();
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.args(["-c", &disabled_hooks])
|
||||
@@ -833,9 +891,18 @@ async fn run_git_no_index_diff_from(
|
||||
.arg(path)
|
||||
.current_dir(cwd)
|
||||
.kill_on_drop(true);
|
||||
match timeout(GIT_COMMAND_TIMEOUT, command.output()).await {
|
||||
Ok(Ok(output)) => Some(output),
|
||||
_ => None,
|
||||
match timeout(GIT_COMMAND_TIMEOUT, git.output_tokio(command)).await {
|
||||
Err(_) => Err(GitReadError::CommandTimedOut {
|
||||
operation: "untrackedDiff".to_string(),
|
||||
}),
|
||||
Ok(Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
Err(GitReadError::NoTrustedGit)
|
||||
}
|
||||
Ok(Err(_)) => Err(GitReadError::CommandFailed {
|
||||
operation: "untrackedDiff".to_string(),
|
||||
exit_code: None,
|
||||
}),
|
||||
Ok(Ok(output)) => Ok(output),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1006,6 +1073,7 @@ mod tests {
|
||||
// The config response mirrors:
|
||||
// git -c core.fsmonitor=/tmp/fsmonitor-helper \
|
||||
// config --null --get core.fsmonitor
|
||||
let git = GitRunner::from_executable_for_test(git);
|
||||
let fsmonitor = detect_local_fsmonitor_override(&git, temp_dir.path()).await;
|
||||
let output = run_git_command_with_timeout_from(
|
||||
&git,
|
||||
@@ -1097,6 +1165,7 @@ mod tests {
|
||||
"write local built-in fsmonitor config"
|
||||
);
|
||||
|
||||
let git = GitRunner::from_executable_for_test(git);
|
||||
let fsmonitor = detect_local_fsmonitor_override(&git, repo.as_path()).await;
|
||||
let output = run_git_command_with_timeout_from(
|
||||
&git,
|
||||
|
||||
@@ -4,6 +4,7 @@ mod baseline;
|
||||
mod branch;
|
||||
mod errors;
|
||||
mod fsmonitor;
|
||||
mod git_command;
|
||||
mod git_config;
|
||||
mod info;
|
||||
mod merge_driver;
|
||||
@@ -24,6 +25,7 @@ pub use baseline::ensure_git_baseline_repository;
|
||||
pub use baseline::reset_git_repository;
|
||||
pub use branch::merge_base_with_head;
|
||||
pub use codex_protocol::protocol::GitSha;
|
||||
pub use errors::GitReadError;
|
||||
pub use errors::GitToolingError;
|
||||
pub use fsmonitor::FsmonitorOverride;
|
||||
pub use fsmonitor::FsmonitorProbeRunner;
|
||||
@@ -45,6 +47,8 @@ pub use info::git_diff_to_remote;
|
||||
pub use info::local_git_branches;
|
||||
pub use info::recent_commits;
|
||||
pub use info::resolve_root_git_project_for_trust;
|
||||
pub use info::try_get_has_changes;
|
||||
pub use info::try_git_diff_to_remote;
|
||||
pub use patch_paths::extract_paths_from_patch;
|
||||
pub use patch_paths::stage_paths;
|
||||
pub use platform::create_symlink;
|
||||
|
||||
@@ -4,22 +4,24 @@ use std::io;
|
||||
use std::io::Seek;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::git_config::GitConfigEntry;
|
||||
use crate::git_config::parse_effective_config;
|
||||
#[cfg(test)]
|
||||
use crate::safe_git::isolate_git_command_environment;
|
||||
use crate::safe_git::read_effective_config_with_fallback;
|
||||
|
||||
const MERGE_CONFIG_PATTERN: &str = r"^(merge\.default|merge\..*\.driver)$";
|
||||
|
||||
pub(crate) fn ensure_no_selected_merge_drivers(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
paths: &[String],
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<()> {
|
||||
let entries = read_merge_config(cwd, git_config_args)?;
|
||||
let attributes = read_merge_attributes(cwd, paths, git_config_args)?;
|
||||
let entries = read_merge_config(git, cwd, git_config_args)?;
|
||||
let attributes = read_merge_attributes(git, cwd, paths, git_config_args)?;
|
||||
if let Some((driver, path)) = untrusted_driver_selection(&entries, &attributes)? {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
@@ -32,40 +34,15 @@ pub(crate) fn ensure_no_selected_merge_drivers(
|
||||
}
|
||||
|
||||
fn read_merge_config(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<BTreeMap<String, GitConfigEntry>> {
|
||||
let mut command = Command::new("git");
|
||||
isolate_git_command_environment(&mut command);
|
||||
let output = command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.args(git_config_args)
|
||||
.args([
|
||||
"config",
|
||||
"--null",
|
||||
"--show-scope",
|
||||
"--show-origin",
|
||||
"--includes",
|
||||
"--get-regexp",
|
||||
MERGE_CONFIG_PATTERN,
|
||||
])
|
||||
.current_dir(cwd)
|
||||
.output()?;
|
||||
if !output
|
||||
.status
|
||||
.code()
|
||||
.is_some_and(|code| code == 0 || code == 1)
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"git merge config probe failed with status {}: {}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
)));
|
||||
}
|
||||
parse_effective_config(&output.stdout)
|
||||
read_effective_config_with_fallback(git, cwd, git_config_args, MERGE_CONFIG_PATTERN, "merge")
|
||||
}
|
||||
|
||||
fn read_merge_attributes(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
paths: &[String],
|
||||
git_config_args: &[String],
|
||||
@@ -83,15 +60,14 @@ fn read_merge_attributes(
|
||||
}
|
||||
input.rewind()?;
|
||||
|
||||
let mut command = Command::new("git");
|
||||
isolate_git_command_environment(&mut command);
|
||||
let output = command
|
||||
let mut command = git.command();
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.args(git_config_args)
|
||||
.args(["check-attr", "--stdin", "-z", "merge"])
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::from(input))
|
||||
.output()?;
|
||||
.stdin(Stdio::from(input));
|
||||
let output = git.output(command)?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"git merge attribute probe failed with status {}: {}",
|
||||
@@ -164,9 +140,6 @@ fn untrusted_driver_selection(
|
||||
.and_then(|key| key.strip_suffix(".driver"))
|
||||
.filter(|name| !name.is_empty())
|
||||
.ok_or_else(|| invalid_config_entry("malformed merge driver key"))?;
|
||||
if !entry.value.is_empty() && !entry.scope.is_system_or_global() {
|
||||
return Ok(Some((name.to_string(), "<Git config>".to_string())));
|
||||
}
|
||||
drivers.insert(name.to_string(), entry.value.as_str());
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,56 @@ fn apply_allows_unused_global_merge_driver() {
|
||||
assert_ne!(marker_code, 0, "unused merge driver must not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_way_apply_allows_unrelated_local_merge_driver() {
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("file.txt"), "base\n").expect("write base");
|
||||
let (add_code, _, add_err) = run(root, &["git", "add", "file.txt"]);
|
||||
assert_eq!(add_code, 0, "add base: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "base"]);
|
||||
assert_eq!(commit_code, 0, "commit base: {commit_err}");
|
||||
|
||||
std::fs::write(root.join("file.txt"), "base\npatched\n").expect("write patch side");
|
||||
let (diff_code, diff, diff_err) = run(root, &["git", "diff", "--full-index", "--", "file.txt"]);
|
||||
assert_eq!(diff_code, 0, "create patch: {diff_err}");
|
||||
let (restore_code, _, restore_err) = run(root, &["git", "checkout", "--", "file.txt"]);
|
||||
assert_eq!(restore_code, 0, "restore base: {restore_err}");
|
||||
|
||||
std::fs::write(root.join("file.txt"), "current\nbase\n").expect("write current side");
|
||||
let (stage_code, _, stage_err) = run(root, &["git", "add", "file.txt"]);
|
||||
assert_eq!(stage_code, 0, "stage current side: {stage_err}");
|
||||
let (config_code, _, config_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"config",
|
||||
"merge.unused.driver",
|
||||
"git config codex.mergeran true && false",
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
config_code, 0,
|
||||
"configure unused local driver: {config_err}"
|
||||
);
|
||||
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff,
|
||||
revert: false,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("allow unrelated local merge driver during three-way fallback");
|
||||
assert_eq!(result.exit_code, 0, "three-way apply: {}", result.stderr);
|
||||
assert!(result.cmd_for_log.contains("--3way"));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("file.txt")).expect("read merged file"),
|
||||
"current\nbase\npatched\n"
|
||||
);
|
||||
let (marker_code, _, _) = run(root, &["git", "config", "--get", "codex.mergeran"]);
|
||||
assert_ne!(marker_code, 0, "unused merge driver must not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_allows_clean_patch_with_selected_merge_driver() {
|
||||
let repo = init_repo();
|
||||
@@ -248,17 +298,32 @@ fn selected_driver_policy_handles_default_and_sentinel_ambiguity() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_driver_policy_rejects_untrusted_scope_even_when_unused() {
|
||||
let mut entries = config_entries([("merge.local.driver", "helper")]);
|
||||
entries
|
||||
.get_mut("merge.local.driver")
|
||||
.expect("local driver")
|
||||
.scope = GitConfigScope::Local;
|
||||
let attributes = BTreeMap::from([("file.txt".to_string(), "other".to_string())]);
|
||||
assert_eq!(
|
||||
untrusted_driver_selection(&entries, &attributes).expect("local driver"),
|
||||
Some(("local".to_string(), "<Git config>".to_string()))
|
||||
);
|
||||
fn selected_driver_policy_ignores_scope_until_driver_is_selected() {
|
||||
for scope in [
|
||||
GitConfigScope::System,
|
||||
GitConfigScope::Global,
|
||||
GitConfigScope::Local,
|
||||
GitConfigScope::Worktree,
|
||||
GitConfigScope::Command,
|
||||
] {
|
||||
let mut entries = config_entries([("merge.scoped.driver", "helper")]);
|
||||
entries
|
||||
.get_mut("merge.scoped.driver")
|
||||
.expect("scoped driver")
|
||||
.scope = scope;
|
||||
let attributes = BTreeMap::from([("file.txt".to_string(), "other".to_string())]);
|
||||
assert_eq!(
|
||||
untrusted_driver_selection(&entries, &attributes).expect("unused scoped driver"),
|
||||
None,
|
||||
"{scope:?}"
|
||||
);
|
||||
let attributes = BTreeMap::from([("file.txt".to_string(), "scoped".to_string())]);
|
||||
assert_eq!(
|
||||
untrusted_driver_selection(&entries, &attributes).expect("selected scoped driver"),
|
||||
Some(("scoped".to_string(), "file.txt".to_string())),
|
||||
"{scope:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,10 +2,13 @@ use std::ffi::OsStr;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
#[cfg(test)]
|
||||
use std::process::Command;
|
||||
|
||||
use crate::GitToolingError;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::safe_git::DISABLED_HOOKS_PATH;
|
||||
#[cfg(test)]
|
||||
use crate::safe_git::isolate_git_command_environment;
|
||||
|
||||
pub(crate) fn ensure_git_repository(path: &Path) -> Result<(), GitToolingError> {
|
||||
@@ -110,16 +113,16 @@ where
|
||||
args_vec.push(OsString::from(arg.as_ref()));
|
||||
}
|
||||
let command_string = build_command_string(&args_vec);
|
||||
let mut command = Command::new("git");
|
||||
let git = GitRunner::for_cwd_io(dir)?;
|
||||
let mut command = git.command();
|
||||
command.current_dir(dir);
|
||||
if let Some(envs) = env {
|
||||
for (key, value) in envs {
|
||||
command.env(key, value);
|
||||
}
|
||||
}
|
||||
isolate_git_command_environment(&mut command);
|
||||
command.args(&args_vec);
|
||||
let output = command.output()?;
|
||||
let output = git.output(command)?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(GitToolingError::GitCommand {
|
||||
|
||||
@@ -1,24 +1,27 @@
|
||||
//! Effective patch-path discovery and safe staging guards.
|
||||
|
||||
use std::io;
|
||||
use std::io::Seek;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::apply::run_git;
|
||||
use crate::apply::safe_git_config_parts;
|
||||
use crate::apply::write_temp_patch;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::git_config::path_is_within;
|
||||
use crate::safe_git::ensure_no_selected_executable_git_filters;
|
||||
use crate::safe_git::isolate_git_command_environment;
|
||||
|
||||
pub(crate) fn extract_effective_paths_from_patch(
|
||||
git: &GitRunner,
|
||||
patch_path: &Path,
|
||||
revert: bool,
|
||||
) -> io::Result<Vec<String>> {
|
||||
let forward_paths = git_apply_numstat_paths(patch_path, revert)?;
|
||||
let forward_paths = git_apply_numstat_paths(git, patch_path, revert)?;
|
||||
// `git apply --numstat` reports only the destination of a rename. Parse the
|
||||
// opposite orientation too so the submodule guard covers both endpoints.
|
||||
let reverse_paths = git_apply_numstat_paths(patch_path, !revert)?;
|
||||
let reverse_paths = git_apply_numstat_paths(git, patch_path, !revert)?;
|
||||
if forward_paths.len() != reverse_paths.len() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
@@ -47,24 +50,31 @@ pub fn extract_paths_from_patch(diff_text: &str) -> Vec<String> {
|
||||
let Ok((tmpdir, patch_path)) = write_temp_patch(diff_text) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let paths =
|
||||
extract_effective_paths_from_patch(&patch_path, /*revert*/ false).unwrap_or_default();
|
||||
let paths = std::env::current_dir()
|
||||
.ok()
|
||||
.and_then(|cwd| GitRunner::for_cwd(&cwd).ok())
|
||||
.and_then(|git| {
|
||||
extract_effective_paths_from_patch(&git, &patch_path, /*revert*/ false).ok()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
drop(tmpdir);
|
||||
paths
|
||||
}
|
||||
|
||||
fn git_apply_numstat_paths(patch_path: &Path, revert: bool) -> io::Result<Vec<String>> {
|
||||
let mut cmd = std::process::Command::new("git");
|
||||
isolate_git_command_environment(&mut cmd);
|
||||
fn git_apply_numstat_paths(
|
||||
git: &GitRunner,
|
||||
patch_path: &Path,
|
||||
revert: bool,
|
||||
) -> io::Result<Vec<String>> {
|
||||
let mut cmd = git.command();
|
||||
cmd.args(["apply", "--numstat", "-z"]);
|
||||
if revert {
|
||||
cmd.arg("-R");
|
||||
}
|
||||
let out = cmd
|
||||
.arg("--")
|
||||
cmd.arg("--")
|
||||
.arg(patch_path)
|
||||
.current_dir(patch_path.parent().unwrap_or_else(|| Path::new(".")))
|
||||
.output()?;
|
||||
.current_dir(patch_path.parent().unwrap_or_else(|| Path::new(".")));
|
||||
let out = git.output(cmd)?;
|
||||
if !out.status.success() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
@@ -152,8 +162,7 @@ fn insert_numstat_path(paths: &mut Vec<String>, path: &[u8]) -> io::Result<()> {
|
||||
fn validate_patch_path(path: String) -> io::Result<String> {
|
||||
if path.starts_with('/')
|
||||
|| path.ends_with('/')
|
||||
|| path.contains('\\')
|
||||
|| path.as_bytes().get(1) == Some(&b':')
|
||||
|| invalid_platform_patch_path(&path)
|
||||
|| path
|
||||
.split('/')
|
||||
.any(|component| component.is_empty() || component == "." || component == "..")
|
||||
@@ -166,16 +175,38 @@ fn validate_patch_path(path: String) -> io::Result<String> {
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// 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 (tmpdir, patch_path) = write_temp_patch(diff)?;
|
||||
let paths = extract_effective_paths_from_patch(&patch_path, /*revert*/ true)?;
|
||||
let _guard = tmpdir;
|
||||
stage_effective_paths(git_root, &paths)
|
||||
#[cfg(windows)]
|
||||
fn invalid_platform_patch_path(path: &str) -> bool {
|
||||
path.contains('\\') || path.as_bytes().get(1) == Some(&b':')
|
||||
}
|
||||
|
||||
pub(crate) fn stage_effective_paths(git_root: &Path, paths: &[String]) -> io::Result<()> {
|
||||
ensure_no_selected_executable_git_filters(git_root, paths, &[])?;
|
||||
#[cfg(not(windows))]
|
||||
fn invalid_platform_patch_path(_path: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
let (tmpdir, patch_path) = write_temp_patch(diff)?;
|
||||
let paths = extract_effective_paths_from_patch(&git, &patch_path, /*revert*/ true)?;
|
||||
let _guard = tmpdir;
|
||||
stage_effective_paths(&git, git_root, &paths)
|
||||
}
|
||||
|
||||
pub(crate) fn stage_effective_paths(
|
||||
git: &GitRunner,
|
||||
git_root: &Path,
|
||||
paths: &[String],
|
||||
) -> io::Result<()> {
|
||||
ensure_no_selected_executable_git_filters(git, git_root, paths, &[])?;
|
||||
let guarded = classify_patch_paths(git, git_root, paths)?;
|
||||
if !guarded.exact_gitlinks.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"refusing to stage an exact submodule entry with git add",
|
||||
));
|
||||
}
|
||||
let mut existing: Vec<String> = Vec::new();
|
||||
for p in paths {
|
||||
let joined = git_root.join(p);
|
||||
@@ -186,7 +217,6 @@ pub(crate) fn stage_effective_paths(git_root: &Path, paths: &[String]) -> io::Re
|
||||
if existing.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
ensure_paths_do_not_enter_submodules(git_root, &existing)?;
|
||||
let mut args = vec![
|
||||
"--literal-pathspecs".to_string(),
|
||||
"add".to_string(),
|
||||
@@ -194,30 +224,55 @@ pub(crate) fn stage_effective_paths(git_root: &Path, paths: &[String]) -> io::Re
|
||||
];
|
||||
args.extend(existing);
|
||||
let config_parts = safe_git_config_parts();
|
||||
let (_code, _, _) = run_git(git_root, &config_parts, &args)?;
|
||||
let (_code, _, _) = run_git(git, git_root, &config_parts, &args)?;
|
||||
// We do not hard fail staging; best-effort is OK. Return Ok even on non-zero.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn ensure_paths_do_not_enter_submodules(
|
||||
git_root: &Path,
|
||||
paths: &[String],
|
||||
) -> io::Result<()> {
|
||||
let git = GitRunner::for_cwd_io(git_root)?;
|
||||
classify_patch_paths(&git, git_root, paths).map(|_| ())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct GuardedPatchPaths {
|
||||
pub(crate) exact_gitlinks: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct IndexStageRecord {
|
||||
mode: String,
|
||||
oid: String,
|
||||
stage: u8,
|
||||
path: String,
|
||||
}
|
||||
|
||||
pub(crate) fn classify_patch_paths(
|
||||
git: &GitRunner,
|
||||
git_root: &Path,
|
||||
paths: &[String],
|
||||
) -> io::Result<GuardedPatchPaths> {
|
||||
if paths.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"refusing to inspect an empty patch path set",
|
||||
));
|
||||
}
|
||||
let mut candidates = std::collections::BTreeSet::new();
|
||||
let exact_leaves = paths
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
let mut traversed_ancestors = std::collections::BTreeSet::new();
|
||||
for path in paths {
|
||||
insert_path_prefixes(path, &mut candidates, /*include_leaf*/ true);
|
||||
insert_path_prefixes(path, &mut traversed_ancestors, /*include_leaf*/ false);
|
||||
}
|
||||
|
||||
let canonical_root = std::fs::canonicalize(git_root)?;
|
||||
let git_metadata_dirs = canonical_git_metadata_dirs(&canonical_root)?;
|
||||
let git_metadata_dirs = canonical_git_metadata_dirs(git, &canonical_root)?;
|
||||
let mut canonical_candidates = std::collections::BTreeSet::new();
|
||||
for candidate in &traversed_ancestors {
|
||||
match std::fs::canonicalize(git_root.join(candidate)) {
|
||||
@@ -259,41 +314,375 @@ pub(crate) fn ensure_paths_do_not_enter_submodules(
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
candidates.extend(canonical_candidates);
|
||||
let mut exact_candidates = exact_leaves.clone();
|
||||
exact_candidates.extend(traversed_ancestors.iter().cloned());
|
||||
exact_candidates.extend(canonical_candidates.iter().cloned());
|
||||
let records = read_index_stage_records(git, git_root, &exact_candidates, false, None)?;
|
||||
let mut exact_gitlinks = std::collections::BTreeMap::new();
|
||||
for record in records {
|
||||
if !exact_candidates.contains(&record.path) {
|
||||
continue;
|
||||
}
|
||||
if record.stage != 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"refusing to apply a patch across an unmerged index entry",
|
||||
));
|
||||
}
|
||||
if record.mode != "160000" {
|
||||
continue;
|
||||
}
|
||||
if traversed_ancestors.contains(&record.path) || canonical_candidates.contains(&record.path)
|
||||
{
|
||||
return Err(submodule_descendant_error());
|
||||
}
|
||||
if exact_leaves.contains(&record.path) {
|
||||
exact_gitlinks.insert(record.path, record.oid);
|
||||
}
|
||||
}
|
||||
|
||||
// `:(icase)` is discovery only. Confirm a differently-cased candidate by
|
||||
// filesystem identity so case-sensitive siblings remain independent.
|
||||
if !traversed_ancestors.is_empty() {
|
||||
let icase_records =
|
||||
read_index_stage_records(git, git_root, &traversed_ancestors, true, None)?;
|
||||
for record in icase_records {
|
||||
if record.mode != "160000" || traversed_ancestors.contains(&record.path) {
|
||||
continue;
|
||||
}
|
||||
let indexed = std::fs::canonicalize(git_root.join(&record.path));
|
||||
for candidate in &traversed_ancestors {
|
||||
if !candidate.eq_ignore_ascii_case(&record.path) {
|
||||
continue;
|
||||
}
|
||||
let requested = std::fs::canonicalize(git_root.join(candidate));
|
||||
match (&requested, &indexed) {
|
||||
(Ok(requested), Ok(indexed))
|
||||
if same_file::is_same_file(requested, indexed).unwrap_or(false) =>
|
||||
{
|
||||
return Err(submodule_descendant_error());
|
||||
}
|
||||
(Ok(_), Ok(_)) => {}
|
||||
_ if filesystem_is_case_sensitive(git_root) == Some(true) => {}
|
||||
// If either object is absent and the containing filesystem
|
||||
// does not prove case-sensitive lookup, fail closed.
|
||||
_ => return Err(submodule_descendant_error()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(GuardedPatchPaths { exact_gitlinks })
|
||||
}
|
||||
|
||||
pub(crate) fn validate_gitlink_updates(
|
||||
git: &GitRunner,
|
||||
git_root: &Path,
|
||||
paths: &[String],
|
||||
patch_path: &Path,
|
||||
patch_text: &str,
|
||||
revert: bool,
|
||||
guarded: &GuardedPatchPaths,
|
||||
) -> io::Result<()> {
|
||||
let mentions_gitlink = patch_header_mentions_gitlink_mode(patch_text);
|
||||
if guarded.exact_gitlinks.is_empty() && !mentions_gitlink {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let config_parts = safe_git_config_parts();
|
||||
let (code, index_path, stderr) = run_git(
|
||||
git,
|
||||
git_root,
|
||||
&config_parts,
|
||||
&[
|
||||
"rev-parse".to_string(),
|
||||
"--git-path".to_string(),
|
||||
"index".to_string(),
|
||||
],
|
||||
)?;
|
||||
if code != 0 {
|
||||
return Err(io::Error::other(format!(
|
||||
"failed to resolve parent Git index (exit {code}): {}",
|
||||
stderr.trim()
|
||||
)));
|
||||
}
|
||||
let index_path = PathBuf::from(index_path.trim_end_matches(['\r', '\n']));
|
||||
let index_path = if index_path.is_absolute() {
|
||||
index_path
|
||||
} else {
|
||||
git_root.join(index_path)
|
||||
};
|
||||
let index_parent = index_path.parent().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git index has no parent directory",
|
||||
)
|
||||
})?;
|
||||
let mut scratch = tempfile::NamedTempFile::new_in(index_parent)?;
|
||||
let index_exists = index_path.exists();
|
||||
if index_exists {
|
||||
let mut source = std::fs::File::open(&index_path)?;
|
||||
io::copy(&mut source, scratch.as_file_mut())?;
|
||||
scratch.as_file_mut().flush()?;
|
||||
scratch.as_file_mut().rewind()?;
|
||||
}
|
||||
let scratch_guard = scratch.into_temp_path();
|
||||
let scratch_path = scratch_guard.to_path_buf();
|
||||
if !index_exists {
|
||||
std::fs::remove_file(&scratch_path)?;
|
||||
}
|
||||
let mut args = vec!["apply".to_string(), "--cached".to_string()];
|
||||
if revert {
|
||||
args.push("-R".to_string());
|
||||
}
|
||||
args.push("--".to_string());
|
||||
args.push(patch_path.to_string_lossy().into_owned());
|
||||
let output = run_git_bytes(git, git_root, &config_parts, &args, Some(&scratch_path))?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
format!(
|
||||
"refusing a gitlink patch that cannot be validated in an isolated parent index: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let candidates = paths
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
let records = read_index_stage_records(git, git_root, &candidates, false, Some(&scratch_path))?;
|
||||
let mut resulting_gitlinks = std::collections::BTreeMap::new();
|
||||
for record in records {
|
||||
if !candidates.contains(&record.path) {
|
||||
continue;
|
||||
}
|
||||
if record.stage != 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"refusing a gitlink patch that produces an unmerged index entry",
|
||||
));
|
||||
}
|
||||
if record.mode == "160000" {
|
||||
resulting_gitlinks.insert(record.path, record.oid);
|
||||
}
|
||||
}
|
||||
if resulting_gitlinks.keys().ne(guarded.exact_gitlinks.keys())
|
||||
|| guarded.exact_gitlinks.iter().any(|(path, oid)| {
|
||||
resulting_gitlinks
|
||||
.get(path)
|
||||
.is_some_and(|resulting_oid| resulting_oid == oid)
|
||||
})
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"only object-ID updates to existing exact gitlink paths are supported",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_index_stage_records(
|
||||
git: &GitRunner,
|
||||
git_root: &Path,
|
||||
candidates: &std::collections::BTreeSet<String>,
|
||||
ignore_case: bool,
|
||||
index_file: Option<&Path>,
|
||||
) -> io::Result<Vec<IndexStageRecord>> {
|
||||
if candidates.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut args = vec![
|
||||
"ls-files".to_string(),
|
||||
"--stage".to_string(),
|
||||
"-z".to_string(),
|
||||
"--".to_string(),
|
||||
];
|
||||
let magic = if ignore_case {
|
||||
":(icase,literal)"
|
||||
} else {
|
||||
":(literal)"
|
||||
};
|
||||
args.extend(
|
||||
candidates
|
||||
.into_iter()
|
||||
.map(|candidate| format!(":(icase,literal){candidate}")),
|
||||
.iter()
|
||||
.map(|candidate| format!("{magic}{candidate}")),
|
||||
);
|
||||
let config_parts = safe_git_config_parts();
|
||||
let (code, stdout, stderr) = run_git(git_root, &config_parts, &args)?;
|
||||
if code != 0 {
|
||||
let output = run_git_bytes(git, git_root, &config_parts, &args, index_file)?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"failed to inspect patch paths for submodules (exit {code}): {}",
|
||||
stderr.trim()
|
||||
"failed to inspect patch paths in the parent index (status {}): {}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
)));
|
||||
}
|
||||
if stdout
|
||||
.split('\0')
|
||||
.filter(|record| !record.is_empty())
|
||||
.any(|record| record.starts_with("160000 "))
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"refusing to stage a patch path that is a submodule or enters a submodule",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
parse_index_stage_records(&output.stdout)
|
||||
}
|
||||
|
||||
fn canonical_git_metadata_dirs(git_root: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
fn run_git_bytes(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_cfg: &[String],
|
||||
args: &[String],
|
||||
index_file: Option<&Path>,
|
||||
) -> io::Result<std::process::Output> {
|
||||
// Keep this constructor centralized so #29470 can add its local-only
|
||||
// transport environment here during the later semantic rebase.
|
||||
let mut command = git.command();
|
||||
command.args(git_cfg).args(args).current_dir(cwd);
|
||||
match index_file {
|
||||
Some(index_file) => git.output_with_index_file(command, index_file),
|
||||
None => git.output(command),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_index_stage_records(output: &[u8]) -> io::Result<Vec<IndexStageRecord>> {
|
||||
if !output.is_empty() && !output.ends_with(&[0]) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git returned an unterminated index record",
|
||||
));
|
||||
}
|
||||
let mut records = Vec::new();
|
||||
for raw in output
|
||||
.split(|byte| *byte == 0)
|
||||
.filter(|record| !record.is_empty())
|
||||
{
|
||||
let tab = raw.iter().position(|byte| *byte == b'\t').ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git returned an index record without a path",
|
||||
)
|
||||
})?;
|
||||
let metadata = std::str::from_utf8(&raw[..tab]).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git returned non-UTF-8 index metadata",
|
||||
)
|
||||
})?;
|
||||
let path = std::str::from_utf8(&raw[tab + 1..]).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git returned a non-UTF-8 index path",
|
||||
)
|
||||
})?;
|
||||
let fields = metadata.split_whitespace().collect::<Vec<_>>();
|
||||
let [mode, oid, stage] = fields.as_slice() else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git returned malformed index metadata",
|
||||
));
|
||||
};
|
||||
if mode.len() != 6 || !mode.bytes().all(|byte| matches!(byte, b'0'..=b'7')) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git returned an invalid index mode",
|
||||
));
|
||||
}
|
||||
if oid.is_empty() || !oid.bytes().all(|byte| byte.is_ascii_hexdigit()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git returned an invalid object ID",
|
||||
));
|
||||
}
|
||||
let stage = stage
|
||||
.parse::<u8>()
|
||||
.ok()
|
||||
.filter(|stage| *stage <= 3)
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Git returned an invalid index stage",
|
||||
)
|
||||
})?;
|
||||
records.push(IndexStageRecord {
|
||||
mode: (*mode).to_string(),
|
||||
oid: (*oid).to_string(),
|
||||
stage,
|
||||
path: path.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
fn patch_header_mentions_gitlink_mode(patch: &str) -> bool {
|
||||
let mut in_header = false;
|
||||
for line in patch.lines() {
|
||||
if line.starts_with("diff --git ") {
|
||||
in_header = true;
|
||||
continue;
|
||||
}
|
||||
if !in_header {
|
||||
continue;
|
||||
}
|
||||
if line.starts_with("@@") || line == "GIT binary patch" {
|
||||
in_header = false;
|
||||
continue;
|
||||
}
|
||||
if matches!(
|
||||
line,
|
||||
"new file mode 160000"
|
||||
| "deleted file mode 160000"
|
||||
| "old mode 160000"
|
||||
| "new mode 160000"
|
||||
) || line
|
||||
.strip_prefix("index ")
|
||||
.is_some_and(|index| index.ends_with(" 160000"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn submodule_descendant_error() -> io::Error {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"refusing to apply a patch path that enters a submodule",
|
||||
)
|
||||
}
|
||||
|
||||
fn filesystem_is_case_sensitive(path: &Path) -> Option<bool> {
|
||||
if let Some(result) = case_sensitivity_from_existing_entry(&path.join(".git")) {
|
||||
return Some(result);
|
||||
}
|
||||
for existing in path.ancestors() {
|
||||
if let Some(result) = case_sensitivity_from_existing_entry(existing) {
|
||||
return Some(result);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn case_sensitivity_from_existing_entry(existing: &Path) -> Option<bool> {
|
||||
if !existing.exists() {
|
||||
return None;
|
||||
}
|
||||
let name = existing.file_name()?.to_str()?;
|
||||
let mut alternate = name.to_string();
|
||||
let (index, replacement) = alternate.char_indices().find_map(|(index, character)| {
|
||||
if character.is_ascii_lowercase() {
|
||||
Some((index, character.to_ascii_uppercase()))
|
||||
} else if character.is_ascii_uppercase() {
|
||||
Some((index, character.to_ascii_lowercase()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})?;
|
||||
alternate.replace_range(index..index + 1, &replacement.to_string());
|
||||
let alternate_path = existing.parent()?.join(alternate);
|
||||
match std::fs::canonicalize(&alternate_path) {
|
||||
Ok(_) => same_file::is_same_file(existing, &alternate_path)
|
||||
.ok()
|
||||
.map(|same| !same),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Some(true),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_git_metadata_dirs(git: &GitRunner, git_root: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let config_parts = safe_git_config_parts();
|
||||
let queries = [
|
||||
vec!["rev-parse".to_string(), "--absolute-git-dir".to_string()],
|
||||
@@ -301,7 +690,7 @@ fn canonical_git_metadata_dirs(git_root: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
];
|
||||
let mut metadata_dirs = std::collections::BTreeSet::new();
|
||||
for args in queries {
|
||||
let (code, stdout, stderr) = run_git(git_root, &config_parts, &args)?;
|
||||
let (code, stdout, stderr) = run_git(git, git_root, &config_parts, &args)?;
|
||||
if code != 0 {
|
||||
return Err(io::Error::other(format!(
|
||||
"failed to resolve Git repository metadata (exit {code}): {}",
|
||||
|
||||
@@ -67,7 +67,9 @@ fn read_file_normalized(path: &Path) -> String {
|
||||
|
||||
fn effective_paths(diff: &str, revert: bool) -> io::Result<Vec<String>> {
|
||||
let (tmpdir, patch_path) = write_temp_patch(diff)?;
|
||||
let paths = extract_effective_paths_from_patch(&patch_path, revert)?;
|
||||
let cwd = std::env::current_dir()?;
|
||||
let git = GitRunner::for_cwd_io(&cwd)?;
|
||||
let paths = extract_effective_paths_from_patch(&git, &patch_path, revert)?;
|
||||
drop(tmpdir);
|
||||
Ok(paths)
|
||||
}
|
||||
@@ -213,11 +215,122 @@ fn effective_paths_follow_git_for_mismatched_headers() {
|
||||
fn effective_paths_reject_platform_ambiguous_paths() {
|
||||
let error = effective_paths("", /*revert*/ false).expect_err("reject empty patch paths");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
|
||||
let error = validate_patch_path("..\\nested\\file.txt".to_string())
|
||||
.expect_err("reject Windows path separators");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
|
||||
let error = validate_patch_path("C:/outside.txt".to_string()).expect_err("reject drive prefix");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let error = validate_patch_path("..\\nested\\file.txt".to_string())
|
||||
.expect_err("reject Windows path separators");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
|
||||
let error =
|
||||
validate_patch_path("C:/outside.txt".to_string()).expect_err("reject drive prefix");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
assert_eq!(
|
||||
validate_patch_path("back\\slash.txt".to_string()).expect("valid Unix filename"),
|
||||
"back\\slash.txt"
|
||||
);
|
||||
assert_eq!(
|
||||
validate_patch_path("a:file.txt".to_string()).expect("valid Unix filename"),
|
||||
"a:file.txt"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn patch_applies_valid_unix_colon_and_backslash_paths() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
for (path, contents) in [
|
||||
("a:file.txt", "old colon\n"),
|
||||
("back\\slash.txt", "old slash\n"),
|
||||
] {
|
||||
std::fs::write(root.join(path), contents).expect("write fixture");
|
||||
}
|
||||
let (add_code, _, add_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"--literal-pathspecs",
|
||||
"add",
|
||||
"--",
|
||||
"a:file.txt",
|
||||
"back\\slash.txt",
|
||||
],
|
||||
);
|
||||
assert_eq!(add_code, 0, "add fixture: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "fixture"]);
|
||||
assert_eq!(commit_code, 0, "commit fixture: {commit_err}");
|
||||
|
||||
std::fs::write(root.join("a:file.txt"), "new colon\n").expect("modify colon path");
|
||||
std::fs::write(root.join("back\\slash.txt"), "new slash\n").expect("modify backslash path");
|
||||
let (diff_code, diff, diff_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"--literal-pathspecs",
|
||||
"diff",
|
||||
"--full-index",
|
||||
"--binary",
|
||||
"--",
|
||||
"a:file.txt",
|
||||
"back\\slash.txt",
|
||||
],
|
||||
);
|
||||
assert_eq!(diff_code, 0, "create patch: {diff_err}");
|
||||
assert!(!diff.is_empty(), "fixture patch must not be empty");
|
||||
let (restore_code, _, restore_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"--literal-pathspecs",
|
||||
"checkout",
|
||||
"--",
|
||||
"a:file.txt",
|
||||
"back\\slash.txt",
|
||||
],
|
||||
);
|
||||
assert_eq!(restore_code, 0, "restore fixture: {restore_err}");
|
||||
|
||||
for preflight in [true, false] {
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.clone(),
|
||||
revert: false,
|
||||
preflight,
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("forward preflight={preflight}: {error}"));
|
||||
assert_eq!(result.exit_code, 0, "forward preflight={preflight}");
|
||||
}
|
||||
assert_eq!(
|
||||
read_file_normalized(&root.join("a:file.txt")),
|
||||
"new colon\n"
|
||||
);
|
||||
assert_eq!(
|
||||
read_file_normalized(&root.join("back\\slash.txt")),
|
||||
"new slash\n"
|
||||
);
|
||||
|
||||
for preflight in [true, false] {
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.clone(),
|
||||
revert: true,
|
||||
preflight,
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("reverse preflight={preflight}: {error}"));
|
||||
assert_eq!(result.exit_code, 0, "reverse preflight={preflight}");
|
||||
}
|
||||
assert_eq!(
|
||||
read_file_normalized(&root.join("a:file.txt")),
|
||||
"old colon\n"
|
||||
);
|
||||
assert_eq!(
|
||||
read_file_normalized(&root.join("back\\slash.txt")),
|
||||
"old slash\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -257,6 +370,437 @@ fn stage_paths_rejects_gitlink_before_entering_submodule() {
|
||||
assert!(!configured_filter_ran(&root.join("nested")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patch_allows_exact_gitlink_updates_without_entering_submodule() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
init_submodule_with_clean_filter(root);
|
||||
let nested = root.join("nested");
|
||||
|
||||
let (old_code, old_sha, old_err) = run(root, &["git", "rev-parse", "HEAD:nested"]);
|
||||
assert_eq!(old_code, 0, "read old gitlink: {old_err}");
|
||||
let old_sha = old_sha.trim().to_string();
|
||||
let _ = run(
|
||||
&nested,
|
||||
&["git", "config", "user.email", "codex@example.com"],
|
||||
);
|
||||
let _ = run(&nested, &["git", "config", "user.name", "Codex"]);
|
||||
std::fs::write(nested.join("second.txt"), "second\n").expect("write child commit");
|
||||
let (add_code, _, add_err) = run(&nested, &["git", "add", "second.txt"]);
|
||||
assert_eq!(add_code, 0, "add child commit: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(&nested, &["git", "commit", "-m", "second"]);
|
||||
assert_eq!(commit_code, 0, "commit child: {commit_err}");
|
||||
let (new_code, new_sha, new_err) = run(&nested, &["git", "rev-parse", "HEAD"]);
|
||||
assert_eq!(new_code, 0, "read new child commit: {new_err}");
|
||||
let new_sha = new_sha.trim().to_string();
|
||||
|
||||
let (update_code, _, update_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"update-index",
|
||||
"--cacheinfo",
|
||||
"160000",
|
||||
&new_sha,
|
||||
"nested",
|
||||
],
|
||||
);
|
||||
assert_eq!(update_code, 0, "update parent gitlink: {update_err}");
|
||||
let (diff_code, diff, diff_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"diff",
|
||||
"--cached",
|
||||
"--full-index",
|
||||
"--binary",
|
||||
"--",
|
||||
"nested",
|
||||
],
|
||||
);
|
||||
assert_eq!(diff_code, 0, "create gitlink patch: {diff_err}");
|
||||
assert!(!diff.is_empty(), "gitlink patch must not be empty");
|
||||
let (restore_code, _, restore_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"update-index",
|
||||
"--cacheinfo",
|
||||
"160000",
|
||||
&old_sha,
|
||||
"nested",
|
||||
],
|
||||
);
|
||||
assert_eq!(restore_code, 0, "restore parent gitlink: {restore_err}");
|
||||
let (reset_code, _, reset_err) = run(&nested, &["git", "reset", "--soft", &old_sha]);
|
||||
assert_eq!(reset_code, 0, "restore child HEAD: {reset_err}");
|
||||
let _ = run(&nested, &["git", "config", "--unset", "codex.filterran"]);
|
||||
assert!(!configured_filter_ran(&nested));
|
||||
|
||||
for preflight in [true, false] {
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.clone(),
|
||||
revert: false,
|
||||
preflight,
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("forward gitlink preflight={preflight}: {error}"));
|
||||
assert_eq!(result.exit_code, 0, "forward preflight={preflight}");
|
||||
assert!(!configured_filter_ran(&nested));
|
||||
}
|
||||
let (staged_code, staged, staged_err) = run(root, &["git", "ls-files", "--stage", "nested"]);
|
||||
assert_eq!(staged_code, 0, "read updated gitlink: {staged_err}");
|
||||
assert!(
|
||||
staged.contains(&new_sha),
|
||||
"expected new gitlink, got {staged:?}"
|
||||
);
|
||||
|
||||
let (reset_code, _, reset_err) = run(&nested, &["git", "reset", "--soft", &new_sha]);
|
||||
assert_eq!(reset_code, 0, "advance child HEAD: {reset_err}");
|
||||
for preflight in [true, false] {
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.clone(),
|
||||
revert: true,
|
||||
preflight,
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("reverse gitlink preflight={preflight}: {error}"));
|
||||
assert_eq!(result.exit_code, 0, "reverse preflight={preflight}");
|
||||
assert!(!configured_filter_ran(&nested));
|
||||
}
|
||||
let (staged_code, staged, staged_err) = run(root, &["git", "ls-files", "--stage", "nested"]);
|
||||
assert_eq!(staged_code, 0, "read restored gitlink: {staged_err}");
|
||||
assert!(
|
||||
staged.contains(&old_sha),
|
||||
"expected old gitlink, got {staged:?}"
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(&nested).expect("remove initialized child checkout");
|
||||
for (revert, expected_sha) in [(false, &new_sha), (true, &old_sha)] {
|
||||
let preflight = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.clone(),
|
||||
revert,
|
||||
preflight: true,
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("uninitialized preflight revert={revert}: {error}"));
|
||||
assert_eq!(
|
||||
preflight.exit_code, 0,
|
||||
"uninitialized preflight revert={revert}"
|
||||
);
|
||||
let applied = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.clone(),
|
||||
revert,
|
||||
preflight: false,
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("uninitialized apply revert={revert}: {error}"));
|
||||
assert_eq!(applied.exit_code, 0, "uninitialized apply revert={revert}");
|
||||
let (stage_code, stage, stage_err) = run(root, &["git", "ls-files", "--stage", "nested"]);
|
||||
assert_eq!(stage_code, 0, "read uninitialized gitlink: {stage_err}");
|
||||
assert!(
|
||||
stage.contains(expected_sha.as_str()),
|
||||
"unexpected gitlink: {stage:?}"
|
||||
);
|
||||
assert!(
|
||||
!nested.exists(),
|
||||
"Codex must not initialize the child worktree"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patch_rejects_gitlink_add_delete_rename_and_mode_shapes_without_mutation() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
init_submodule_with_clean_filter(root);
|
||||
let nested = root.join("nested");
|
||||
std::fs::write(root.join("ordinary.txt"), "ordinary\n").expect("ordinary file");
|
||||
let (ordinary_add_code, _, ordinary_add_err) = run(root, &["git", "add", "ordinary.txt"]);
|
||||
assert_eq!(
|
||||
ordinary_add_code, 0,
|
||||
"add ordinary file: {ordinary_add_err}"
|
||||
);
|
||||
let (ordinary_commit_code, _, ordinary_commit_err) =
|
||||
run(root, &["git", "commit", "-m", "ordinary file"]);
|
||||
assert_eq!(
|
||||
ordinary_commit_code, 0,
|
||||
"commit ordinary file: {ordinary_commit_err}"
|
||||
);
|
||||
let (sha_code, gitlink_sha, sha_err) = run(root, &["git", "rev-parse", "HEAD:nested"]);
|
||||
assert_eq!(sha_code, 0, "read gitlink: {sha_err}");
|
||||
let gitlink_sha = gitlink_sha.trim().to_string();
|
||||
let (blob_code, ordinary_blob, blob_err) =
|
||||
run(root, &["git", "rev-parse", "HEAD:ordinary.txt"]);
|
||||
assert_eq!(blob_code, 0, "read ordinary blob: {blob_err}");
|
||||
let ordinary_blob = ordinary_blob.trim().to_string();
|
||||
let (before_code, before_index, before_err) = run(root, &["git", "ls-files", "--stage"]);
|
||||
assert_eq!(before_code, 0, "snapshot index: {before_err}");
|
||||
|
||||
let (remove_code, _, remove_err) =
|
||||
run(root, &["git", "update-index", "--force-remove", "nested"]);
|
||||
assert_eq!(remove_code, 0, "prepare deletion: {remove_err}");
|
||||
let (delete_code, delete_patch, delete_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"diff",
|
||||
"--cached",
|
||||
"--full-index",
|
||||
"--binary",
|
||||
"--",
|
||||
"nested",
|
||||
],
|
||||
);
|
||||
assert_eq!(delete_code, 0, "create deletion patch: {delete_err}");
|
||||
let (restore_code, _, restore_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"update-index",
|
||||
"--add",
|
||||
"--cacheinfo",
|
||||
"160000",
|
||||
&gitlink_sha,
|
||||
"nested",
|
||||
],
|
||||
);
|
||||
assert_eq!(restore_code, 0, "restore after deletion: {restore_err}");
|
||||
|
||||
let _ = run(root, &["git", "update-index", "--force-remove", "nested"]);
|
||||
let (rename_add_code, _, rename_add_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"update-index",
|
||||
"--add",
|
||||
"--cacheinfo",
|
||||
"160000",
|
||||
&gitlink_sha,
|
||||
"renamed-module",
|
||||
],
|
||||
);
|
||||
assert_eq!(rename_add_code, 0, "prepare rename: {rename_add_err}");
|
||||
let (rename_code, rename_patch, rename_err) = run(
|
||||
root,
|
||||
&["git", "diff", "--cached", "-M", "--full-index", "--binary"],
|
||||
);
|
||||
assert_eq!(rename_code, 0, "create rename patch: {rename_err}");
|
||||
let _ = run(
|
||||
root,
|
||||
&["git", "update-index", "--force-remove", "renamed-module"],
|
||||
);
|
||||
let _ = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"update-index",
|
||||
"--add",
|
||||
"--cacheinfo",
|
||||
"160000",
|
||||
&gitlink_sha,
|
||||
"nested",
|
||||
],
|
||||
);
|
||||
|
||||
let (add_code, _, add_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"update-index",
|
||||
"--add",
|
||||
"--cacheinfo",
|
||||
"160000",
|
||||
&gitlink_sha,
|
||||
"second-module",
|
||||
],
|
||||
);
|
||||
assert_eq!(add_code, 0, "prepare addition: {add_err}");
|
||||
let (new_code, new_patch, new_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"diff",
|
||||
"--cached",
|
||||
"--full-index",
|
||||
"--binary",
|
||||
"--",
|
||||
"second-module",
|
||||
],
|
||||
);
|
||||
assert_eq!(new_code, 0, "create addition patch: {new_err}");
|
||||
let _ = run(
|
||||
root,
|
||||
&["git", "update-index", "--force-remove", "second-module"],
|
||||
);
|
||||
|
||||
let (mode_code, _, mode_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"update-index",
|
||||
"--cacheinfo",
|
||||
"160000",
|
||||
&gitlink_sha,
|
||||
"ordinary.txt",
|
||||
],
|
||||
);
|
||||
assert_eq!(mode_code, 0, "prepare mode transition: {mode_err}");
|
||||
let (mode_diff_code, mode_patch, mode_diff_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"diff",
|
||||
"--cached",
|
||||
"--full-index",
|
||||
"--binary",
|
||||
"--",
|
||||
"ordinary.txt",
|
||||
],
|
||||
);
|
||||
assert_eq!(mode_diff_code, 0, "create mode patch: {mode_diff_err}");
|
||||
let (mode_restore_code, _, mode_restore_err) = run(
|
||||
root,
|
||||
&[
|
||||
"git",
|
||||
"update-index",
|
||||
"--cacheinfo",
|
||||
"100644",
|
||||
&ordinary_blob,
|
||||
"ordinary.txt",
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
mode_restore_code, 0,
|
||||
"restore ordinary mode: {mode_restore_err}"
|
||||
);
|
||||
let _ = run(&nested, &["git", "config", "--unset", "codex.filterran"]);
|
||||
|
||||
for (name, diff) in [
|
||||
("delete", delete_patch),
|
||||
("rename", rename_patch),
|
||||
("add", new_patch),
|
||||
("mode transition", mode_patch),
|
||||
] {
|
||||
assert!(!diff.is_empty(), "{name} patch must not be empty");
|
||||
let error = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff,
|
||||
revert: false,
|
||||
preflight: false,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Unsupported, "{name}");
|
||||
let (after_code, after_index, after_err) = run(root, &["git", "ls-files", "--stage"]);
|
||||
assert_eq!(after_code, 0, "read index after {name}: {after_err}");
|
||||
assert_eq!(after_index, before_index, "{name} changed parent index");
|
||||
assert!(!configured_filter_ran(&nested), "{name} entered child");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_stage_parser_preserves_paths_and_rejects_ambiguous_records() {
|
||||
let parsed = parse_index_stage_records(
|
||||
b"160000 0123456789abcdef0123456789abcdef01234567 0\tnested module\0\
|
||||
100644 abcdefabcdefabcdefabcdefabcdefabcdefabcd 2\tname\twith-tab\0",
|
||||
)
|
||||
.expect("parse records");
|
||||
assert_eq!(parsed.len(), 2);
|
||||
assert_eq!(parsed[0].mode, "160000");
|
||||
assert_eq!(parsed[0].oid, "0123456789abcdef0123456789abcdef01234567");
|
||||
assert_eq!(parsed[0].stage, 0);
|
||||
assert_eq!(parsed[0].path, "nested module");
|
||||
assert_eq!(parsed[1].path, "name\twith-tab");
|
||||
|
||||
for malformed in [
|
||||
b"160000 abc 0\tnested".as_slice(),
|
||||
b"160000 not-an-oid 0\tnested\0".as_slice(),
|
||||
b"160000 abc 4\tnested\0".as_slice(),
|
||||
b"160000 abc 0 nested\0".as_slice(),
|
||||
] {
|
||||
assert!(
|
||||
parse_index_stage_records(malformed).is_err(),
|
||||
"{malformed:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn case_sensitive_sibling_of_gitlink_is_not_treated_as_descendant() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
init_submodule_with_clean_filter(root);
|
||||
let sibling = root.join("NESTED");
|
||||
std::fs::create_dir_all(&sibling).expect("create case-distinct sibling");
|
||||
if std::fs::canonicalize(&sibling).expect("canonical sibling")
|
||||
== std::fs::canonicalize(root.join("nested")).expect("canonical gitlink")
|
||||
{
|
||||
return;
|
||||
}
|
||||
std::fs::write(sibling.join("file.txt"), "old\n").expect("write sibling file");
|
||||
let (add_code, _, add_err) = run(root, &["git", "add", "NESTED/file.txt"]);
|
||||
assert_eq!(add_code, 0, "add sibling: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "case sibling"]);
|
||||
assert_eq!(commit_code, 0, "commit sibling: {commit_err}");
|
||||
std::fs::write(sibling.join("file.txt"), "new\n").expect("modify sibling");
|
||||
let (diff_code, diff, diff_err) = run(
|
||||
root,
|
||||
&["git", "diff", "--full-index", "--", "NESTED/file.txt"],
|
||||
);
|
||||
assert_eq!(diff_code, 0, "create sibling patch: {diff_err}");
|
||||
let (restore_code, _, restore_err) = run(root, &["git", "checkout", "--", "NESTED/file.txt"]);
|
||||
assert_eq!(restore_code, 0, "restore sibling: {restore_err}");
|
||||
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff,
|
||||
revert: false,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("allow case-distinct sibling");
|
||||
assert_eq!(result.exit_code, 0);
|
||||
assert_eq!(read_file_normalized(&sibling.join("file.txt")), "new\n");
|
||||
assert!(!configured_filter_ran(&root.join("nested")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_case_distinct_sibling_is_allowed_on_case_sensitive_filesystem() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
init_submodule_with_clean_filter(root);
|
||||
let probe = root.join("NESTED");
|
||||
match std::fs::create_dir(&probe) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return,
|
||||
Err(error) => panic!("probe case-distinct name: {error}"),
|
||||
}
|
||||
if std::fs::canonicalize(&probe).expect("canonical probe")
|
||||
== std::fs::canonicalize(root.join("nested")).expect("canonical gitlink")
|
||||
{
|
||||
return;
|
||||
}
|
||||
std::fs::remove_dir(&probe).expect("remove probe");
|
||||
|
||||
let diff = "diff --git a/NESTED/new.txt b/NESTED/new.txt\nnew file mode 100644\n--- /dev/null\n+++ b/NESTED/new.txt\n@@ -0,0 +1 @@\n+case-sensitive sibling\n";
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
})
|
||||
.expect("allow absent case-distinct sibling");
|
||||
assert_eq!(result.exit_code, 0, "apply sibling: {}", result.stderr);
|
||||
assert_eq!(
|
||||
read_file_normalized(&root.join("NESTED/new.txt")),
|
||||
"case-sensitive sibling\n"
|
||||
);
|
||||
assert!(!configured_filter_ran(&root.join("nested")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gitlink_guard_ignores_inherited_git_selection_environment() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
@@ -303,6 +847,81 @@ fn gitlink_guard_ignores_inherited_git_selection_environment() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn public_apply_skips_repository_controlled_primary_git() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
if std::env::var_os("CODEX_GIT_UTILS_PATH_ENV_CHILD").is_some() {
|
||||
let root = PathBuf::from(
|
||||
std::env::var_os("CODEX_GIT_UTILS_TARGET_REPO").expect("target repository"),
|
||||
);
|
||||
let result = apply_git_patch(&ApplyGitRequest {
|
||||
cwd: root.clone(),
|
||||
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 trusted external Git");
|
||||
assert_eq!(result.exit_code, 0, "apply patch: {}", result.stderr);
|
||||
assert_eq!(read_file_normalized(&root.join("file.txt")), "new\n");
|
||||
return;
|
||||
}
|
||||
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
std::fs::write(root.join("file.txt"), "old\n").expect("fixture file");
|
||||
let (add_code, _, add_err) = run(root, &["git", "add", "file.txt"]);
|
||||
assert_eq!(add_code, 0, "add fixture: {add_err}");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-m", "fixture"]);
|
||||
assert_eq!(commit_code, 0, "commit fixture: {commit_err}");
|
||||
let (config_code, _, config_err) = run(root, &["git", "config", "filter.unused.clean", "cat"]);
|
||||
assert_eq!(config_code, 0, "configure unused filter: {config_err}");
|
||||
|
||||
let repo_bin = root.join("bin");
|
||||
std::fs::create_dir(&repo_bin).expect("repository bin");
|
||||
let marker = root.join("repository-primary-git-ran");
|
||||
let fake_git = repo_bin.join("git");
|
||||
std::fs::write(
|
||||
&fake_git,
|
||||
"#!/bin/sh\nprintf ran > \"$CODEX_GIT_UTILS_PRIMARY_GIT_MARKER\"\nexec \"$CODEX_GIT_UTILS_REAL_GIT\" \"$@\"\n",
|
||||
)
|
||||
.expect("repository Git");
|
||||
let mut permissions = std::fs::metadata(&fake_git)
|
||||
.expect("repository Git metadata")
|
||||
.permissions();
|
||||
permissions.set_mode(0o755);
|
||||
std::fs::set_permissions(&fake_git, permissions).expect("repository Git executable");
|
||||
|
||||
let output = std::process::Command::new("/bin/sh")
|
||||
.args(["-c", "command -v git"])
|
||||
.output()
|
||||
.expect("resolve fixture Git");
|
||||
assert!(output.status.success(), "resolve fixture Git");
|
||||
let real_git = PathBuf::from(
|
||||
String::from_utf8(output.stdout)
|
||||
.expect("Git path UTF-8")
|
||||
.trim(),
|
||||
);
|
||||
let search_path = std::env::join_paths([
|
||||
repo_bin.as_path(),
|
||||
real_git.parent().expect("Git executable directory"),
|
||||
])
|
||||
.expect("controlled PATH");
|
||||
run_isolated_test(
|
||||
"patch_paths::tests::public_apply_skips_repository_controlled_primary_git",
|
||||
&[
|
||||
("CODEX_GIT_UTILS_TARGET_REPO", root.as_os_str()),
|
||||
("CODEX_GIT_UTILS_PRIMARY_GIT_MARKER", marker.as_os_str()),
|
||||
("CODEX_GIT_UTILS_REAL_GIT", real_git.as_os_str()),
|
||||
("PATH", search_path.as_os_str()),
|
||||
],
|
||||
);
|
||||
assert!(!marker.exists(), "repository-controlled primary Git ran");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn staging_rejects_global_lfs_filter_without_running_it() {
|
||||
@@ -311,7 +930,8 @@ fn staging_rejects_global_lfs_filter_without_running_it() {
|
||||
let root = PathBuf::from(
|
||||
std::env::var_os("CODEX_GIT_UTILS_TARGET_REPO").expect("target repository"),
|
||||
);
|
||||
let error = stage_effective_paths(&root, &["file.txt".to_string()])
|
||||
let git = GitRunner::for_cwd_io(&root).expect("trusted Git");
|
||||
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;
|
||||
|
||||
+203
-105
@@ -11,8 +11,11 @@ use tokio::process::Command as TokioCommand;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::GitReadError;
|
||||
use crate::git_command::GitRunner;
|
||||
use crate::git_config::GitConfigEntry;
|
||||
use crate::git_config::parse_effective_config;
|
||||
use crate::git_config::parse_effective_config_with_origins;
|
||||
|
||||
pub(crate) const DISABLED_HOOKS_PATH: &str = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
||||
pub(crate) const EXECUTABLE_FILTER_CONFIG_PATTERN: &str = r"^filter\..*\.(clean|smudge|process)$";
|
||||
@@ -52,24 +55,30 @@ pub(crate) fn isolate_tokio_git_command_environment(command: &mut tokio::process
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn has_selected_executable_filters_from(git: &Path, cwd: &Path) -> Option<bool> {
|
||||
pub(crate) async fn selected_executable_filter_from(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
) -> Result<Option<(String, Vec<u8>)>, GitReadError> {
|
||||
let git_root = resolve_git_root_async(git, cwd).await?;
|
||||
let entries = read_filter_config_async(git, &git_root).await?;
|
||||
if !entries.values().any(|entry| !entry.value.is_empty()) {
|
||||
return Some(false);
|
||||
return Ok(None);
|
||||
}
|
||||
let paths = read_paths_async(git, &git_root, PathSelection::Tracked).await?;
|
||||
let attributes = read_filter_attributes_async(git, &git_root, &paths).await?;
|
||||
selected_executable_filter(&entries, &attributes)
|
||||
.ok()
|
||||
.map(|selected| selected.is_some())
|
||||
selected_executable_filter(&entries, &attributes).map_err(|_| invalid_output("filterSelection"))
|
||||
}
|
||||
|
||||
/// Validate every tracked path plus the exact untracked paths that the caller
|
||||
/// will later feed to `git diff --no-index`. The returned raw paths must be
|
||||
/// reused rather than reconstructed from Git's quoted line-oriented output.
|
||||
pub(crate) async fn safe_untracked_paths_for_diff(git: &Path, cwd: &Path) -> Option<Vec<Vec<u8>>> {
|
||||
let requested_cwd = std::fs::canonicalize(cwd).ok()?;
|
||||
pub(crate) async fn safe_untracked_paths_for_diff_checked(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
) -> Result<Vec<Vec<u8>>, GitReadError> {
|
||||
let requested_cwd = std::fs::canonicalize(cwd).map_err(|_| GitReadError::NotRepository {
|
||||
path: cwd.to_path_buf(),
|
||||
})?;
|
||||
let git_root = resolve_git_root_async(git, &requested_cwd).await?;
|
||||
let untracked = read_paths_async(git, &requested_cwd, PathSelection::Untracked).await?;
|
||||
// An embedded untracked repository is reported by `ls-files` as a single
|
||||
@@ -78,37 +87,37 @@ pub(crate) async fn safe_untracked_paths_for_diff(git: &Path, cwd: &Path) -> Opt
|
||||
// child path that was never returned by the path probe. Fail closed rather
|
||||
// than let the sink operate on a different path vector than we validated.
|
||||
for path in &untracked {
|
||||
let path = git_path_bytes_to_path_buf(path)?;
|
||||
let display_path = String::from_utf8_lossy(path).into_owned();
|
||||
let path =
|
||||
git_path_bytes_to_path_buf(path).ok_or_else(|| invalid_output("untrackedPaths"))?;
|
||||
if std::fs::symlink_metadata(requested_cwd.join(path))
|
||||
.ok()?
|
||||
.map_err(|_| command_failed("pathMetadata", None))?
|
||||
.file_type()
|
||||
.is_dir()
|
||||
{
|
||||
return None;
|
||||
return Err(GitReadError::EmbeddedRepository { path: display_path });
|
||||
}
|
||||
}
|
||||
let entries = read_filter_config_async(git, &git_root).await?;
|
||||
if !entries.values().any(|entry| !entry.value.is_empty()) {
|
||||
return Some(untracked);
|
||||
return Ok(untracked);
|
||||
}
|
||||
|
||||
let tracked = read_paths_async(git, &git_root, PathSelection::Tracked).await?;
|
||||
let tracked_attributes = read_filter_attributes_async(git, &git_root, &tracked).await?;
|
||||
if selected_executable_filter(&entries, &tracked_attributes)
|
||||
.ok()?
|
||||
.is_some()
|
||||
if let Some((driver, path)) = selected_executable_filter(&entries, &tracked_attributes)
|
||||
.map_err(|_| invalid_output("trackedFilterSelection"))?
|
||||
{
|
||||
return None;
|
||||
return Err(selected_filter_error(driver, path));
|
||||
}
|
||||
let untracked_attributes =
|
||||
read_filter_attributes_async(git, &requested_cwd, &untracked).await?;
|
||||
if selected_executable_filter(&entries, &untracked_attributes)
|
||||
.ok()?
|
||||
.is_some()
|
||||
if let Some((driver, path)) = selected_executable_filter(&entries, &untracked_attributes)
|
||||
.map_err(|_| invalid_output("untrackedFilterSelection"))?
|
||||
{
|
||||
return None;
|
||||
return Err(selected_filter_error(driver, path));
|
||||
}
|
||||
Some(untracked)
|
||||
Ok(untracked)
|
||||
}
|
||||
|
||||
fn git_path_bytes_to_path_buf(path: &[u8]) -> Option<PathBuf> {
|
||||
@@ -125,10 +134,11 @@ fn git_path_bytes_to_path_buf(path: &[u8]) -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_git_root_async(git: &Path, cwd: &Path) -> Option<PathBuf> {
|
||||
let requested_cwd = std::fs::canonicalize(cwd).ok()?;
|
||||
let mut command = TokioCommand::new(git);
|
||||
isolate_tokio_git_command_environment(&mut command);
|
||||
async fn resolve_git_root_async(git: &GitRunner, cwd: &Path) -> Result<PathBuf, GitReadError> {
|
||||
let requested_cwd = std::fs::canonicalize(cwd).map_err(|_| GitReadError::NotRepository {
|
||||
path: cwd.to_path_buf(),
|
||||
})?;
|
||||
let mut command = git.tokio_command();
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.args([
|
||||
@@ -141,33 +151,40 @@ async fn resolve_git_root_async(git: &Path, cwd: &Path) -> Option<PathBuf> {
|
||||
])
|
||||
.current_dir(&requested_cwd)
|
||||
.kill_on_drop(true);
|
||||
let output = match timeout(GIT_COMMAND_TIMEOUT, command.output()).await {
|
||||
Ok(Ok(output)) => output,
|
||||
_ => return None,
|
||||
};
|
||||
let output = command_output(git, command, "resolveGitRoot").await?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
return Err(GitReadError::NotRepository {
|
||||
path: requested_cwd,
|
||||
});
|
||||
}
|
||||
let path = String::from_utf8(output.stdout).ok()?;
|
||||
let path = String::from_utf8(output.stdout).map_err(|_| invalid_output("resolveGitRoot"))?;
|
||||
let path = path.trim_end_matches(['\r', '\n']);
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
return Err(invalid_output("resolveGitRoot"));
|
||||
}
|
||||
let reported_root = std::fs::canonicalize(PathBuf::from(path)).ok()?;
|
||||
let reported_root =
|
||||
std::fs::canonicalize(PathBuf::from(path)).map_err(|_| invalid_output("resolveGitRoot"))?;
|
||||
let expected_root = crate::get_git_repo_root(&requested_cwd)
|
||||
.and_then(|root| std::fs::canonicalize(root).ok())?;
|
||||
.and_then(|root| std::fs::canonicalize(root).ok())
|
||||
.ok_or_else(|| GitReadError::NotRepository {
|
||||
path: requested_cwd.clone(),
|
||||
})?;
|
||||
if reported_root != expected_root {
|
||||
return None;
|
||||
return Err(GitReadError::RepositoryRootMismatch {
|
||||
expected_root,
|
||||
reported_root,
|
||||
});
|
||||
}
|
||||
Some(reported_root)
|
||||
Ok(reported_root)
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_no_selected_executable_git_filters(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
paths: &[String],
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<()> {
|
||||
let entries = read_filter_config(cwd, git_config_args)?;
|
||||
let entries = read_filter_config(git, cwd, git_config_args)?;
|
||||
if !entries.values().any(|entry| !entry.value.is_empty()) {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -175,7 +192,7 @@ pub(crate) fn ensure_no_selected_executable_git_filters(
|
||||
.iter()
|
||||
.map(|path| path.as_bytes().to_vec())
|
||||
.collect::<Vec<_>>();
|
||||
let attributes = read_filter_attributes(cwd, &paths, git_config_args)?;
|
||||
let attributes = read_filter_attributes(git, cwd, &paths, git_config_args)?;
|
||||
if let Some((driver, path)) = selected_executable_filter(&entries, &attributes)? {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
@@ -189,50 +206,107 @@ pub(crate) fn ensure_no_selected_executable_git_filters(
|
||||
}
|
||||
|
||||
fn read_filter_config(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
) -> io::Result<BTreeMap<String, GitConfigEntry>> {
|
||||
let mut command = Command::new("git");
|
||||
isolate_git_command_environment(&mut command);
|
||||
let output = command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.args(git_config_args)
|
||||
.args([
|
||||
"config",
|
||||
"--null",
|
||||
"--show-scope",
|
||||
"--show-origin",
|
||||
"--includes",
|
||||
"--get-regexp",
|
||||
EXECUTABLE_FILTER_CONFIG_PATTERN,
|
||||
])
|
||||
.current_dir(cwd)
|
||||
.output()?;
|
||||
if !output
|
||||
read_effective_config_with_fallback(
|
||||
git,
|
||||
cwd,
|
||||
git_config_args,
|
||||
EXECUTABLE_FILTER_CONFIG_PATTERN,
|
||||
"filter",
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn read_effective_config_with_fallback(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
pattern: &str,
|
||||
probe: &str,
|
||||
) -> io::Result<BTreeMap<String, GitConfigEntry>> {
|
||||
let scoped = run_effective_config_query(git, cwd, git_config_args, pattern, true)?;
|
||||
if scoped
|
||||
.status
|
||||
.code()
|
||||
.is_some_and(|code| code == 0 || code == 1)
|
||||
{
|
||||
return parse_effective_config(&scoped.stdout);
|
||||
}
|
||||
|
||||
let legacy = run_effective_config_query(git, cwd, git_config_args, pattern, false)?;
|
||||
if !legacy
|
||||
.status
|
||||
.code()
|
||||
.is_some_and(|code| code == 0 || code == 1)
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"git config probe failed with status {}: {}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
"git {probe} config probe failed with status {}: {}",
|
||||
legacy.status,
|
||||
String::from_utf8_lossy(&legacy.stderr).trim()
|
||||
)));
|
||||
}
|
||||
parse_effective_config(&output.stdout)
|
||||
parse_effective_config_with_origins(&legacy.stdout)
|
||||
}
|
||||
|
||||
fn run_effective_config_query(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
git_config_args: &[String],
|
||||
pattern: &str,
|
||||
show_scope: bool,
|
||||
) -> io::Result<std::process::Output> {
|
||||
let mut command = git.command();
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.args(git_config_args)
|
||||
.args(["config", "--null"]);
|
||||
if show_scope {
|
||||
command.arg("--show-scope");
|
||||
}
|
||||
command
|
||||
.args(["--show-origin", "--includes", "--get-regexp", pattern])
|
||||
.current_dir(cwd);
|
||||
git.output(command)
|
||||
}
|
||||
|
||||
async fn read_filter_config_async(
|
||||
git: &Path,
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
) -> Option<BTreeMap<String, GitConfigEntry>> {
|
||||
let mut command = TokioCommand::new(git);
|
||||
isolate_tokio_git_command_environment(&mut command);
|
||||
) -> Result<BTreeMap<String, GitConfigEntry>, GitReadError> {
|
||||
let scoped = run_filter_config_query_async(git, cwd, true).await?;
|
||||
if scoped
|
||||
.status
|
||||
.code()
|
||||
.is_some_and(|code| code == 0 || code == 1)
|
||||
{
|
||||
return parse_effective_config(&scoped.stdout).map_err(|_| invalid_output("filterConfig"));
|
||||
}
|
||||
|
||||
let legacy = run_filter_config_query_async(git, cwd, false).await?;
|
||||
if !legacy
|
||||
.status
|
||||
.code()
|
||||
.is_some_and(|code| code == 0 || code == 1)
|
||||
{
|
||||
return Err(command_failed("filterConfig", legacy.status.code()));
|
||||
}
|
||||
parse_effective_config_with_origins(&legacy.stdout).map_err(|_| invalid_output("filterConfig"))
|
||||
}
|
||||
|
||||
async fn run_filter_config_query_async(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
show_scope: bool,
|
||||
) -> Result<std::process::Output, GitReadError> {
|
||||
let mut command = git.tokio_command();
|
||||
command.args(["config", "--null"]);
|
||||
if show_scope {
|
||||
command.arg("--show-scope");
|
||||
}
|
||||
command
|
||||
.args([
|
||||
"config",
|
||||
"--null",
|
||||
"--show-scope",
|
||||
"--show-origin",
|
||||
"--includes",
|
||||
"--get-regexp",
|
||||
@@ -240,18 +314,7 @@ async fn read_filter_config_async(
|
||||
])
|
||||
.current_dir(cwd)
|
||||
.kill_on_drop(true);
|
||||
let output = match timeout(GIT_COMMAND_TIMEOUT, command.output()).await {
|
||||
Ok(Ok(output)) => output,
|
||||
_ => return None,
|
||||
};
|
||||
if !output
|
||||
.status
|
||||
.code()
|
||||
.is_some_and(|code| code == 0 || code == 1)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
parse_effective_config(&output.stdout).ok()
|
||||
command_output(git, command, "filterConfig").await
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -261,12 +324,11 @@ enum PathSelection {
|
||||
}
|
||||
|
||||
async fn read_paths_async(
|
||||
git: &Path,
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
selection: PathSelection,
|
||||
) -> Option<Vec<Vec<u8>>> {
|
||||
let mut command = TokioCommand::new(git);
|
||||
isolate_tokio_git_command_environment(&mut command);
|
||||
) -> Result<Vec<Vec<u8>>, GitReadError> {
|
||||
let mut command = git.tokio_command();
|
||||
let hooks_config = format!("core.hooksPath={DISABLED_HOOKS_PATH}");
|
||||
let mut args = vec![
|
||||
"-c",
|
||||
@@ -285,30 +347,32 @@ async fn read_paths_async(
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.kill_on_drop(true);
|
||||
let output = match timeout(GIT_COMMAND_TIMEOUT, command.output()).await {
|
||||
Ok(Ok(output)) => output,
|
||||
_ => return None,
|
||||
let operation = match selection {
|
||||
PathSelection::Tracked => "trackedPaths",
|
||||
PathSelection::Untracked => "untrackedPaths",
|
||||
};
|
||||
let output = command_output(git, command, operation).await?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
return Err(command_failed(operation, output.status.code()));
|
||||
}
|
||||
parse_nul_paths(&output.stdout).ok()
|
||||
parse_nul_paths(&output.stdout).map_err(|_| invalid_output(operation))
|
||||
}
|
||||
|
||||
async fn read_filter_attributes_async(
|
||||
git: &Path,
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
paths: &[Vec<u8>],
|
||||
) -> Option<BTreeMap<Vec<u8>, String>> {
|
||||
) -> Result<BTreeMap<Vec<u8>, String>, GitReadError> {
|
||||
if paths.is_empty() {
|
||||
return Some(BTreeMap::new());
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let mut input = tempfile::tempfile().ok()?;
|
||||
write_nul_paths(&mut input, paths).ok()?;
|
||||
input.rewind().ok()?;
|
||||
let mut input = tempfile::tempfile().map_err(|_| command_failed("filterAttributes", None))?;
|
||||
write_nul_paths(&mut input, paths).map_err(|_| invalid_output("filterAttributes"))?;
|
||||
input
|
||||
.rewind()
|
||||
.map_err(|_| command_failed("filterAttributes", None))?;
|
||||
|
||||
let mut command = TokioCommand::new(git);
|
||||
isolate_tokio_git_command_environment(&mut command);
|
||||
let mut command = git.tokio_command();
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.args([
|
||||
@@ -324,17 +388,52 @@ async fn read_filter_attributes_async(
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::from(input))
|
||||
.kill_on_drop(true);
|
||||
let output = match timeout(GIT_COMMAND_TIMEOUT, command.output()).await {
|
||||
Ok(Ok(output)) => output,
|
||||
_ => return None,
|
||||
};
|
||||
let output = command_output(git, command, "filterAttributes").await?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
return Err(command_failed("filterAttributes", output.status.code()));
|
||||
}
|
||||
parse_filter_attributes(&output.stdout, paths).map_err(|_| invalid_output("filterAttributes"))
|
||||
}
|
||||
|
||||
async fn command_output(
|
||||
git: &GitRunner,
|
||||
command: TokioCommand,
|
||||
operation: &str,
|
||||
) -> Result<std::process::Output, GitReadError> {
|
||||
match timeout(GIT_COMMAND_TIMEOUT, git.output_tokio(command)).await {
|
||||
Err(_) => Err(GitReadError::CommandTimedOut {
|
||||
operation: operation.to_string(),
|
||||
}),
|
||||
Ok(Err(error)) if error.kind() == io::ErrorKind::NotFound => {
|
||||
Err(GitReadError::NoTrustedGit)
|
||||
}
|
||||
Ok(Err(_)) => Err(command_failed(operation, None)),
|
||||
Ok(Ok(output)) => Ok(output),
|
||||
}
|
||||
}
|
||||
|
||||
fn command_failed(operation: &str, exit_code: Option<i32>) -> GitReadError {
|
||||
GitReadError::CommandFailed {
|
||||
operation: operation.to_string(),
|
||||
exit_code,
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_output(operation: &str) -> GitReadError {
|
||||
GitReadError::InvalidOutput {
|
||||
operation: operation.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_filter_error(driver: String, path: Vec<u8>) -> GitReadError {
|
||||
GitReadError::SelectedExecutableFilter {
|
||||
driver,
|
||||
path: String::from_utf8_lossy(&path).into_owned(),
|
||||
}
|
||||
parse_filter_attributes(&output.stdout, paths).ok()
|
||||
}
|
||||
|
||||
fn read_filter_attributes(
|
||||
git: &GitRunner,
|
||||
cwd: &Path,
|
||||
paths: &[Vec<u8>],
|
||||
git_config_args: &[String],
|
||||
@@ -346,9 +445,8 @@ fn read_filter_attributes(
|
||||
write_nul_paths(&mut input, paths)?;
|
||||
input.rewind()?;
|
||||
|
||||
let mut command = Command::new("git");
|
||||
isolate_git_command_environment(&mut command);
|
||||
let output = command
|
||||
let mut command = git.command();
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.args(git_config_args)
|
||||
.args([
|
||||
@@ -362,8 +460,8 @@ fn read_filter_attributes(
|
||||
"filter",
|
||||
])
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::from(input))
|
||||
.output()?;
|
||||
.stdin(Stdio::from(input));
|
||||
let output = git.output(command)?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"git filter attribute probe failed with status {}: {}",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::GitReadError;
|
||||
use crate::apply::ApplyGitRequest;
|
||||
use crate::apply::apply_git_patch;
|
||||
use crate::get_has_changes;
|
||||
@@ -6,6 +7,8 @@ use crate::git_config::GitConfigScope;
|
||||
use crate::git_diff_to_remote;
|
||||
#[cfg(unix)]
|
||||
use crate::patch_paths::stage_paths;
|
||||
use crate::try_get_has_changes;
|
||||
use crate::try_git_diff_to_remote;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
#[cfg(unix)]
|
||||
@@ -313,9 +316,75 @@ async fn get_has_changes_rejects_configured_clean_filter_without_running_it() {
|
||||
configure_clean_filter(&repo_path, "test.txt").await;
|
||||
|
||||
assert_eq!(get_has_changes(&repo_path).await, None);
|
||||
assert_eq!(
|
||||
try_get_has_changes(&repo_path).await,
|
||||
Err(GitReadError::SelectedExecutableFilter {
|
||||
driver: "x=y".to_string(),
|
||||
path: "test.txt".to_string(),
|
||||
})
|
||||
);
|
||||
assert!(!configured_filter_ran(&repo_path).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checked_has_changes_distinguishes_non_repository() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
assert_eq!(
|
||||
try_get_has_changes(temp_dir.path()).await,
|
||||
Err(GitReadError::NotRepository {
|
||||
path: std::fs::canonicalize(temp_dir.path()).expect("canonical temp dir"),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn legacy_git_without_show_scope_uses_origin_fallback() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo_path = create_test_git_repo(&temp_dir).await;
|
||||
std::fs::write(repo_path.join(".gitattributes"), "test.txt filter=legacy\n")
|
||||
.expect("attributes");
|
||||
run_git(&repo_path, &["add", ".gitattributes"]).await;
|
||||
run_git(&repo_path, &["commit", "-m", "attributes"]).await;
|
||||
run_git(
|
||||
&repo_path,
|
||||
&["config", "filter.legacy.clean", "git hash-object --stdin"],
|
||||
)
|
||||
.await;
|
||||
|
||||
let output = std::process::Command::new("/bin/sh")
|
||||
.args(["-c", "command -v git"])
|
||||
.output()
|
||||
.expect("resolve fixture Git");
|
||||
assert!(output.status.success(), "resolve fixture Git");
|
||||
let real_git = String::from_utf8(output.stdout)
|
||||
.expect("Git path UTF-8")
|
||||
.trim()
|
||||
.to_string();
|
||||
let wrapper = temp_dir.path().join("legacy-git");
|
||||
std::fs::write(
|
||||
&wrapper,
|
||||
format!(
|
||||
"#!/bin/sh\nfor arg in \"$@\"; do\n if [ \"$arg\" = --show-scope ]; then\n exit 129\n fi\ndone\nexec '{}' \"$@\"\n",
|
||||
real_git.replace('\'', "'\\''")
|
||||
),
|
||||
)
|
||||
.expect("legacy Git wrapper");
|
||||
let mut permissions = std::fs::metadata(&wrapper)
|
||||
.expect("legacy Git metadata")
|
||||
.permissions();
|
||||
permissions.set_mode(0o755);
|
||||
std::fs::set_permissions(&wrapper, permissions).expect("legacy Git executable");
|
||||
|
||||
let git = GitRunner::from_executable_for_test(wrapper);
|
||||
assert_eq!(
|
||||
selected_executable_filter_from(&git, &repo_path).await,
|
||||
Ok(Some(("legacy".to_string(), b"test.txt".to_vec())))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_has_changes_rejects_core_worktree_redirection_before_running_filter() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
@@ -512,6 +581,12 @@ async fn untracked_diff_rejects_embedded_repo_before_derived_filter_path() {
|
||||
std::fs::write(nested.join("null"), "embedded contents\n").expect("write embedded file");
|
||||
|
||||
assert!(git_diff_to_remote(&repo_path).await.is_none());
|
||||
assert_eq!(
|
||||
try_git_diff_to_remote(&repo_path).await,
|
||||
Err(GitReadError::EmbeddedRepository {
|
||||
path: "nested/".to_string(),
|
||||
})
|
||||
);
|
||||
assert!(!configured_filter_ran(&repo_path).await);
|
||||
}
|
||||
|
||||
@@ -549,9 +624,26 @@ async fn git_diff_to_remote_rejects_configured_clean_filter_without_running_it()
|
||||
run_git(&repo_path, &["push", "origin", &branch]).await;
|
||||
|
||||
assert!(git_diff_to_remote(&repo_path).await.is_none());
|
||||
assert_eq!(
|
||||
try_git_diff_to_remote(&repo_path).await,
|
||||
Err(GitReadError::SelectedExecutableFilter {
|
||||
driver: "x=y".to_string(),
|
||||
path: "test.txt".to_string(),
|
||||
})
|
||||
);
|
||||
assert!(!configured_filter_ran(&repo_path).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checked_diff_distinguishes_missing_remote_base() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let repo_path = create_test_git_repo(&temp_dir).await;
|
||||
assert_eq!(
|
||||
try_git_diff_to_remote(&repo_path).await,
|
||||
Err(GitReadError::NoRemoteBase)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn apply_and_stage_reject_global_relative_filter_without_running_it() {
|
||||
@@ -655,6 +747,7 @@ async fn nested_cwd_rejects_global_lfs_filter_without_running_it() {
|
||||
.expect("write global config");
|
||||
std::fs::write(&system_config, "").expect("write system config");
|
||||
let marker = config_dir.path().join("repo-lfs-ran");
|
||||
let primary_git_marker = config_dir.path().join("repo-primary-git-ran");
|
||||
let repo_git_lfs = repo_bin.join("git-lfs");
|
||||
std::fs::write(
|
||||
&repo_git_lfs,
|
||||
@@ -678,6 +771,17 @@ async fn nested_cwd_rejects_global_lfs_filter_without_running_it() {
|
||||
.expect("Git path UTF-8")
|
||||
.trim(),
|
||||
);
|
||||
let repo_git = repo_bin.join("git");
|
||||
std::fs::write(
|
||||
&repo_git,
|
||||
"#!/bin/sh\nprintf ran > \"$CODEX_GIT_UTILS_PRIMARY_GIT_MARKER\"\nexec \"$CODEX_GIT_UTILS_REAL_GIT\" \"$@\"\n",
|
||||
)
|
||||
.expect("repository Git");
|
||||
let mut permissions = std::fs::metadata(&repo_git)
|
||||
.expect("repository Git metadata")
|
||||
.permissions();
|
||||
permissions.set_mode(0o755);
|
||||
std::fs::set_permissions(&repo_git, permissions).expect("make repository Git executable");
|
||||
let search_path = std::env::join_paths([
|
||||
repo_bin.as_path(),
|
||||
git_path.parent().expect("Git executable directory"),
|
||||
@@ -688,12 +792,21 @@ async fn nested_cwd_rejects_global_lfs_filter_without_running_it() {
|
||||
&[
|
||||
("CODEX_GIT_UTILS_TARGET_REPO", repo_path.as_os_str()),
|
||||
("CODEX_GIT_UTILS_UNSAFE_LFS_MARKER", marker.as_os_str()),
|
||||
(
|
||||
"CODEX_GIT_UTILS_PRIMARY_GIT_MARKER",
|
||||
primary_git_marker.as_os_str(),
|
||||
),
|
||||
("CODEX_GIT_UTILS_REAL_GIT", git_path.as_os_str()),
|
||||
("GIT_CONFIG_GLOBAL", global_config.as_os_str()),
|
||||
("GIT_CONFIG_SYSTEM", system_config.as_os_str()),
|
||||
("PATH", search_path.as_os_str()),
|
||||
],
|
||||
);
|
||||
assert!(!marker.exists(), "repository git-lfs must not run");
|
||||
assert!(
|
||||
!primary_git_marker.exists(),
|
||||
"repository-controlled primary Git must not run"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user