diff --git a/codex-rs/apply-patch/src/invocation.rs b/codex-rs/apply-patch/src/invocation.rs index 8ac2084e4f..b1731d081f 100644 --- a/codex-rs/apply-patch/src/invocation.rs +++ b/codex-rs/apply-patch/src/invocation.rs @@ -13,12 +13,13 @@ use crate::ApplyPatchArgs; use crate::ApplyPatchError; use crate::ApplyPatchFileChange; use crate::ApplyPatchFileUpdate; +use crate::ApplyPatchFileUpdateMode; use crate::IoError; use crate::MaybeApplyPatchVerified; use crate::parser::Hunk; use crate::parser::ParseError; use crate::parser::parse_patch; -use crate::unified_diff_from_chunks; +use crate::unified_diff_from_chunks_with_mode; use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; use std::str::Utf8Error; @@ -143,6 +144,25 @@ pub async fn maybe_parse_apply_patch_verified( cwd: &PathUri, fs: &dyn ExecutorFileSystem, sandbox: Option<&codex_exec_server::FileSystemSandboxContext>, +) -> MaybeApplyPatchVerified { + maybe_parse_apply_patch_verified_with_mode( + argv, + cwd, + ApplyPatchFileUpdateMode::default(), + fs, + sandbox, + ) + .await +} + +/// Parses and verifies an `apply_patch` invocation using the selected +/// file-update mode. +pub async fn maybe_parse_apply_patch_verified_with_mode( + argv: &[String], + cwd: &PathUri, + update_file_mode: ApplyPatchFileUpdateMode, + fs: &dyn ExecutorFileSystem, + sandbox: Option<&codex_exec_server::FileSystemSandboxContext>, ) -> MaybeApplyPatchVerified { // Detect a raw patch body passed directly as the command or as the body of a shell // script. In these cases, report an explicit error rather than applying the patch. @@ -158,7 +178,9 @@ pub async fn maybe_parse_apply_patch_verified( } match maybe_parse_apply_patch(argv, cwd) { - MaybeApplyPatch::Body(args) => verify_apply_patch_args(args, cwd, fs, sandbox).await, + MaybeApplyPatch::Body(args) => { + verify_apply_patch_args_with_mode(args, cwd, update_file_mode, fs, sandbox).await + } MaybeApplyPatch::ShellParseError(e) => MaybeApplyPatchVerified::ShellParseError(e), MaybeApplyPatch::PatchParseError(e) => MaybeApplyPatchVerified::CorrectnessError(e.into()), MaybeApplyPatch::NotApplyPatch => MaybeApplyPatchVerified::NotApplyPatch, @@ -171,7 +193,19 @@ pub async fn verify_apply_patch_args( fs: &dyn ExecutorFileSystem, sandbox: Option<&codex_exec_server::FileSystemSandboxContext>, ) -> MaybeApplyPatchVerified { - match try_verify_apply_patch_args(args, cwd, fs, sandbox).await { + verify_apply_patch_args_with_mode(args, cwd, ApplyPatchFileUpdateMode::default(), fs, sandbox) + .await +} + +/// Verifies parsed patch arguments using the selected file-update mode. +pub async fn verify_apply_patch_args_with_mode( + args: ApplyPatchArgs, + cwd: &PathUri, + update_file_mode: ApplyPatchFileUpdateMode, + fs: &dyn ExecutorFileSystem, + sandbox: Option<&codex_exec_server::FileSystemSandboxContext>, +) -> MaybeApplyPatchVerified { + match try_verify_apply_patch_args(args, cwd, update_file_mode, fs, sandbox).await { Ok(action) => MaybeApplyPatchVerified::Body(action), Err(err) => MaybeApplyPatchVerified::CorrectnessError(err), } @@ -180,6 +214,7 @@ pub async fn verify_apply_patch_args( async fn try_verify_apply_patch_args( args: ApplyPatchArgs, cwd: &PathUri, + update_file_mode: ApplyPatchFileUpdateMode, fs: &dyn ExecutorFileSystem, sandbox: Option<&codex_exec_server::FileSystemSandboxContext>, ) -> Result { @@ -217,7 +252,14 @@ async fn try_verify_apply_patch_args( unified_diff, content: contents, .. - } = unified_diff_from_chunks(&path, &chunks, fs, sandbox).await?; + } = unified_diff_from_chunks_with_mode( + &path, + &chunks, + update_file_mode, + fs, + sandbox, + ) + .await?; changes.insert( path, ApplyPatchFileChange::Update { @@ -233,6 +275,7 @@ async fn try_verify_apply_patch_args( } Ok(ApplyPatchAction { changes, + update_file_mode, patch, cwd: effective_cwd, }) @@ -856,6 +899,7 @@ PATCH"#, new_content: "updated session directory content\n".to_string(), }, )]), + update_file_mode: ApplyPatchFileUpdateMode::default(), patch: argv[1].clone(), cwd: PathUri::from_host_native_path(session_dir.path()) .expect("absolute test path"), diff --git a/codex-rs/apply-patch/src/lib.rs b/codex-rs/apply-patch/src/lib.rs index 1957ddae04..0271938c54 100644 --- a/codex-rs/apply-patch/src/lib.rs +++ b/codex-rs/apply-patch/src/lib.rs @@ -29,7 +29,9 @@ use text_file::SourceFile; use thiserror::Error; pub use invocation::maybe_parse_apply_patch_verified; +pub use invocation::maybe_parse_apply_patch_verified_with_mode; pub use invocation::verify_apply_patch_args; +pub use invocation::verify_apply_patch_args_with_mode; pub use standalone_executable::main; use crate::invocation::ExtractHeredocError; @@ -43,6 +45,30 @@ use crate::invocation::ExtractHeredocError; /// surface. pub const CODEX_CORE_APPLY_PATCH_ARG1: &str = "--codex-run-as-apply-patch"; +/// Internal environment variable used to carry the selected update mode +/// through the arg0-dispatched standalone executable. +pub const CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR: &str = + "CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS"; + +/// Controls how updates reconstruct the target file after matching a patch. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum ApplyPatchFileUpdateMode { + /// Preserve the historical behavior of normalizing updated files to LF. + #[default] + NormalizeToLf, + /// Preserve existing line endings and use the file's preferred ending for new lines. + PreserveLineEndings, +} + +/// Reads the update mode selected for an arg0-dispatched `apply_patch` process. +#[doc(hidden)] +pub fn apply_patch_file_update_mode_from_env() -> ApplyPatchFileUpdateMode { + match std::env::var(CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR).as_deref() { + Ok("1") => ApplyPatchFileUpdateMode::PreserveLineEndings, + _ => ApplyPatchFileUpdateMode::NormalizeToLf, + } +} + #[derive(Debug, Error, PartialEq)] pub enum ApplyPatchError { #[error(transparent)] @@ -141,6 +167,8 @@ pub enum MaybeApplyPatchVerified { pub struct ApplyPatchAction { changes: HashMap, + update_file_mode: ApplyPatchFileUpdateMode, + /// The raw patch argument that can be used to apply the patch. i.e., if the /// original arg was parsed in "lenient" mode with a /// heredoc, this should be the value without the heredoc wrapper. @@ -160,6 +188,11 @@ impl ApplyPatchAction { &self.changes } + /// Returns the update mode selected while the patch was verified. + pub fn update_file_mode(&self) -> ApplyPatchFileUpdateMode { + self.update_file_mode + } + /// Should be used exclusively for testing. (Not worth the overhead of /// creating a feature flag for this.) pub fn new_add_for_test(path: &PathUri, content: String) -> Self { @@ -176,6 +209,7 @@ impl ApplyPatchAction { #[expect(clippy::expect_used)] Self { changes, + update_file_mode: ApplyPatchFileUpdateMode::default(), cwd: path.parent().expect("path should have parent"), patch, } @@ -283,6 +317,29 @@ pub async fn apply_patch( stderr: &mut impl std::io::Write, fs: &dyn ExecutorFileSystem, sandbox: Option<&FileSystemSandboxContext>, +) -> Result { + apply_patch_with_mode( + patch, + ApplyPatchFileUpdateMode::default(), + cwd, + stdout, + stderr, + fs, + sandbox, + ) + .await +} + +/// Applies the patch using the selected file-update mode and prints the result +/// to stdout/stderr. +pub async fn apply_patch_with_mode( + patch: &str, + update_file_mode: ApplyPatchFileUpdateMode, + cwd: &PathUri, + stdout: &mut impl std::io::Write, + stderr: &mut impl std::io::Write, + fs: &dyn ExecutorFileSystem, + sandbox: Option<&FileSystemSandboxContext>, ) -> Result { let hunks = match parse_patch(patch) { Ok(source) => source.hunks, @@ -311,7 +368,7 @@ pub async fn apply_patch( } }; - apply_hunks(&hunks, cwd, stdout, stderr, fs, sandbox).await + apply_hunks_with_mode(&hunks, update_file_mode, cwd, stdout, stderr, fs, sandbox).await } /// Applies hunks and continues to update stdout/stderr @@ -322,9 +379,32 @@ pub async fn apply_hunks( stderr: &mut impl std::io::Write, fs: &dyn ExecutorFileSystem, sandbox: Option<&FileSystemSandboxContext>, +) -> Result { + apply_hunks_with_mode( + hunks, + ApplyPatchFileUpdateMode::default(), + cwd, + stdout, + stderr, + fs, + sandbox, + ) + .await +} + +/// Applies hunks using the selected file-update mode and continues to update +/// stdout/stderr. +async fn apply_hunks_with_mode( + hunks: &[Hunk], + update_file_mode: ApplyPatchFileUpdateMode, + cwd: &PathUri, + stdout: &mut impl std::io::Write, + stderr: &mut impl std::io::Write, + fs: &dyn ExecutorFileSystem, + sandbox: Option<&FileSystemSandboxContext>, ) -> Result { let mut delta = AppliedPatchDelta::empty(); - match apply_hunks_to_files(hunks, cwd, fs, sandbox, &mut delta).await { + match apply_hunks_to_files(hunks, update_file_mode, cwd, fs, sandbox, &mut delta).await { Ok(affected_paths) => { print_summary(&affected_paths, stdout).map_err(|error| { ApplyPatchFailure::new(ApplyPatchError::from(error), delta.clone()) @@ -363,6 +443,7 @@ pub struct AffectedPaths { /// Returns an error if the patch could not be applied. async fn apply_hunks_to_files( hunks: &[Hunk], + update_file_mode: ApplyPatchFileUpdateMode, cwd: &PathUri, fs: &dyn ExecutorFileSystem, sandbox: Option<&FileSystemSandboxContext>, @@ -472,7 +553,14 @@ async fn apply_hunks_to_files( let AppliedPatch { original_contents, new_contents, - } = derive_new_contents_from_chunks(&path_uri, chunks, fs, sandbox).await?; + } = derive_new_contents_from_chunks( + &path_uri, + chunks, + update_file_mode, + fs, + sandbox, + ) + .await?; if let Some(dest) = move_path { let dest_uri = cwd.join(&dest.to_string_lossy())?; let overwritten_move_content = @@ -678,6 +766,7 @@ struct AppliedPatch { async fn derive_new_contents_from_chunks( path: &PathUri, chunks: &[UpdateFileChunk], + update_file_mode: ApplyPatchFileUpdateMode, fs: &dyn ExecutorFileSystem, sandbox: Option<&FileSystemSandboxContext>, ) -> std::result::Result { @@ -691,13 +780,37 @@ async fn derive_new_contents_from_chunks( }) })?; - let mut source_file = SourceFile::parse(&original_contents); - let original_lines = source_file.line_texts(); - let path_text = path.inferred_native_path_string(); - let replacements = compute_replacements(&original_lines, &path_text, chunks)?; - source_file.apply_replacements(&replacements); - let new_contents = source_file.into_contents(); + let new_contents = match update_file_mode { + ApplyPatchFileUpdateMode::NormalizeToLf => { + let mut original_lines = original_contents + .split('\n') + .map(String::from) + .collect::>(); + + // Drop the trailing empty element that results from the final newline so + // that line counts match the behaviour of standard `diff`. + if original_lines.last().is_some_and(String::is_empty) { + original_lines.pop(); + } + + let replacements = + compute_replacements(&original_lines, &path_text, chunks, update_file_mode)?; + let mut new_lines = apply_replacements(original_lines, &replacements); + if !new_lines.last().is_some_and(String::is_empty) { + new_lines.push(String::new()); + } + new_lines.join("\n") + } + ApplyPatchFileUpdateMode::PreserveLineEndings => { + let mut source_file = SourceFile::parse(&original_contents); + let original_lines = source_file.line_texts(); + let replacements = + compute_replacements(&original_lines, &path_text, chunks, update_file_mode)?; + source_file.apply_replacements(&replacements); + source_file.into_contents() + } + }; Ok(AppliedPatch { original_contents, new_contents, @@ -711,6 +824,7 @@ fn compute_replacements( original_lines: &[String], path: &str, chunks: &[UpdateFileChunk], + update_file_mode: ApplyPatchFileUpdateMode, ) -> std::result::Result, ApplyPatchError> { let mut replacements: Vec = Vec::new(); let mut line_index: usize = 0; @@ -779,33 +893,40 @@ fn compute_replacements( } if let Some(start_idx) = found { - // Context lines occur in both sides of a patch chunk. Keep those - // original lines in place so their exact contents and terminators - // survive, especially when the file has mixed line endings. - let mut old_start = 0; - let mut new_start = 0; - for &(old_context, new_context) in &chunk.context_line_indices { - // A trailing empty context line can be removed from `pattern` - // and `new_slice` above when it represents the final newline. - if old_context >= pattern.len() || new_context >= new_slice.len() { - break; + match update_file_mode { + ApplyPatchFileUpdateMode::NormalizeToLf => { + replacements.push((start_idx, pattern.len(), new_slice.to_vec())); } - if old_start != old_context || new_start != new_context { - replacements.push(( - start_idx + old_start, - old_context - old_start, - new_slice[new_start..new_context].to_vec(), - )); + ApplyPatchFileUpdateMode::PreserveLineEndings => { + // Context lines occur in both sides of a patch chunk. Keep those + // original lines in place so their exact contents and terminators + // survive, especially when the file has mixed line endings. + let mut old_start = 0; + let mut new_start = 0; + for &(old_context, new_context) in &chunk.context_line_indices { + // A trailing empty context line can be removed from `pattern` + // and `new_slice` above when it represents the final newline. + if old_context >= pattern.len() || new_context >= new_slice.len() { + break; + } + if old_start != old_context || new_start != new_context { + replacements.push(( + start_idx + old_start, + old_context - old_start, + new_slice[new_start..new_context].to_vec(), + )); + } + old_start = old_context + 1; + new_start = new_context + 1; + } + if old_start != pattern.len() || new_start != new_slice.len() { + replacements.push(( + start_idx + old_start, + pattern.len() - old_start, + new_slice[new_start..].to_vec(), + )); + } } - old_start = old_context + 1; - new_start = new_context + 1; - } - if old_start != pattern.len() || new_start != new_slice.len() { - replacements.push(( - start_idx + old_start, - pattern.len() - old_start, - new_slice[new_start..].to_vec(), - )); } line_index = start_idx + pattern.len(); } else { @@ -822,6 +943,31 @@ fn compute_replacements( Ok(replacements) } +/// Apply the `(start_index, old_len, new_lines)` replacements to `original_lines`, +/// returning the modified file contents as a vector of lines. +fn apply_replacements(mut lines: Vec, replacements: &[Replacement]) -> Vec { + // We must apply replacements in descending order so that earlier replacements + // don't shift the positions of later ones. + for (start_idx, old_len, new_segment) in replacements.iter().rev() { + let start_idx = *start_idx; + let old_len = *old_len; + + // Remove old lines. + for _ in 0..old_len { + if start_idx < lines.len() { + lines.remove(start_idx); + } + } + + // Insert new lines. + for (offset, new_line) in new_segment.iter().enumerate() { + lines.insert(start_idx + offset, new_line.clone()); + } + } + + lines +} + /// Intended result of a file update for apply_patch. #[derive(Debug, Eq, PartialEq)] pub struct ApplyPatchFileUpdate { @@ -836,7 +982,32 @@ pub async fn unified_diff_from_chunks( fs: &dyn ExecutorFileSystem, sandbox: Option<&FileSystemSandboxContext>, ) -> std::result::Result { - unified_diff_from_chunks_with_context(path, chunks, /*context*/ 1, fs, sandbox).await + unified_diff_from_chunks_with_mode( + path, + chunks, + ApplyPatchFileUpdateMode::default(), + fs, + sandbox, + ) + .await +} + +pub(crate) async fn unified_diff_from_chunks_with_mode( + path: &PathUri, + chunks: &[UpdateFileChunk], + update_file_mode: ApplyPatchFileUpdateMode, + fs: &dyn ExecutorFileSystem, + sandbox: Option<&FileSystemSandboxContext>, +) -> std::result::Result { + unified_diff_from_chunks_with_context_and_mode( + path, + chunks, + /*context*/ 1, + update_file_mode, + fs, + sandbox, + ) + .await } pub async fn unified_diff_from_chunks_with_context( @@ -845,11 +1016,30 @@ pub async fn unified_diff_from_chunks_with_context( context: usize, fs: &dyn ExecutorFileSystem, sandbox: Option<&FileSystemSandboxContext>, +) -> std::result::Result { + unified_diff_from_chunks_with_context_and_mode( + path, + chunks, + context, + ApplyPatchFileUpdateMode::default(), + fs, + sandbox, + ) + .await +} + +async fn unified_diff_from_chunks_with_context_and_mode( + path: &PathUri, + chunks: &[UpdateFileChunk], + context: usize, + update_file_mode: ApplyPatchFileUpdateMode, + fs: &dyn ExecutorFileSystem, + sandbox: Option<&FileSystemSandboxContext>, ) -> std::result::Result { let AppliedPatch { original_contents, new_contents, - } = derive_new_contents_from_chunks(path, chunks, fs, sandbox).await?; + } = derive_new_contents_from_chunks(path, chunks, update_file_mode, fs, sandbox).await?; let text_diff = TextDiff::from_lines(&original_contents, &new_contents); let unified_diff = text_diff.unified_diff().context_radius(context).to_string(); Ok(ApplyPatchFileUpdate { diff --git a/codex-rs/apply-patch/src/standalone_executable.rs b/codex-rs/apply-patch/src/standalone_executable.rs index 384b2ecee2..c977fb74c2 100644 --- a/codex-rs/apply-patch/src/standalone_executable.rs +++ b/codex-rs/apply-patch/src/standalone_executable.rs @@ -67,8 +67,10 @@ pub fn run_main() -> i32 { }; // TODO(anp): Discover the standalone executable cwd as PathUri directly. let cwd = codex_utils_path_uri::PathUri::from_abs_path(&cwd); - match runtime.block_on(crate::apply_patch( + let update_file_mode = crate::apply_patch_file_update_mode_from_env(); + match runtime.block_on(crate::apply_patch_with_mode( &patch_arg, + update_file_mode, &cwd, &mut stdout, &mut stderr, diff --git a/codex-rs/apply-patch/tests/fixtures/scenarios/.gitattributes b/codex-rs/apply-patch/tests/fixtures/scenarios/.gitattributes index a42a20ddc5..bc6ff1725c 100644 --- a/codex-rs/apply-patch/tests/fixtures/scenarios/.gitattributes +++ b/codex-rs/apply-patch/tests/fixtures/scenarios/.gitattributes @@ -1 +1,3 @@ ** text eol=lf +023_preserves_crlf_line_endings/input/*.txt -diff -text +023_preserves_crlf_line_endings/expected/*.txt -diff -text diff --git a/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/expected/lines.txt b/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/expected/lines.txt new file mode 100644 index 0000000000..43321636e6 --- /dev/null +++ b/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/expected/lines.txt @@ -0,0 +1,4 @@ +ONE +two +between +three diff --git a/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/input/lines.txt b/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/input/lines.txt new file mode 100644 index 0000000000..e1587ff9ea --- /dev/null +++ b/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/input/lines.txt @@ -0,0 +1,3 @@ +one +two +three diff --git a/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/patch.txt b/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/patch.txt new file mode 100644 index 0000000000..6df72a09cf --- /dev/null +++ b/codex-rs/apply-patch/tests/fixtures/scenarios/023_preserves_crlf_line_endings/patch.txt @@ -0,0 +1,9 @@ +*** Begin Patch +*** Update File: lines.txt +@@ +-one ++ONE + two ++between + three +*** End Patch diff --git a/codex-rs/apply-patch/tests/suite/scenarios.rs b/codex-rs/apply-patch/tests/suite/scenarios.rs index 3beb7d652d..451240e01a 100644 --- a/codex-rs/apply-patch/tests/suite/scenarios.rs +++ b/codex-rs/apply-patch/tests/suite/scenarios.rs @@ -1,4 +1,6 @@ -use codex_utils_cargo_bin::repo_root; +use anyhow::Context; +use codex_apply_patch::CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR; +use codex_utils_cargo_bin::find_resource; use pretty_assertions::assert_eq; use std::collections::BTreeMap; use std::fs; @@ -9,17 +11,15 @@ use tempfile::tempdir; #[test] fn test_apply_patch_scenarios() -> anyhow::Result<()> { - let scenarios_dir = repo_root()? - .join("codex-rs") - .join("apply-patch") - .join("tests") - .join("fixtures") - .join("scenarios"); - for scenario in fs::read_dir(scenarios_dir)? { + let scenarios_dir = find_resource!("tests/fixtures/scenarios")?; + for scenario in fs::read_dir(&scenarios_dir) + .with_context(|| format!("failed to read {}", scenarios_dir.display()))? + { let scenario = scenario?; let path = scenario.path(); if path.is_dir() { - run_apply_patch_scenario(&path)?; + run_apply_patch_scenario(&path) + .with_context(|| format!("failed to run scenario {}", path.display()))?; } } Ok(()) @@ -37,15 +37,19 @@ fn run_apply_patch_scenario(dir: &Path) -> anyhow::Result<()> { } // Read the patch.txt file - let patch = fs::read_to_string(dir.join("patch.txt"))?; + let patch_path = dir.join("patch.txt"); + let patch = fs::read_to_string(&patch_path) + .with_context(|| format!("failed to read {}", patch_path.display()))?; // Run apply_patch in the temporary directory. We intentionally do not assert // on the exit status here; the scenarios are specified purely in terms of // final filesystem state, which we compare below. Command::new(codex_utils_cargo_bin::cargo_bin("apply_patch")?) .arg(patch) + .env(CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR, "1") .current_dir(tmp.path()) - .output()?; + .output() + .with_context(|| format!("failed to run scenario {}", dir.display()))?; // Assert that the final state matches the expected state exactly let expected_dir = dir.join("expected"); diff --git a/codex-rs/apply-patch/tests/suite/tool.rs b/codex-rs/apply-patch/tests/suite/tool.rs index 30661624f4..b285098102 100644 --- a/codex-rs/apply-patch/tests/suite/tool.rs +++ b/codex-rs/apply-patch/tests/suite/tool.rs @@ -1,4 +1,5 @@ use assert_cmd::Command; +use codex_apply_patch::CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR; use pretty_assertions::assert_eq; use std::fs; use std::path::Path; @@ -7,6 +8,7 @@ use tempfile::tempdir; fn run_apply_patch_in_dir(dir: &Path, patch: &str) -> anyhow::Result { let mut cmd = Command::new(codex_utils_cargo_bin::cargo_bin("apply_patch")?); + cmd.env(CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR, "1"); cmd.current_dir(dir); Ok(cmd.arg(patch).assert()) } @@ -33,6 +35,7 @@ fn assert_apply_patch_updates_file( fn apply_patch_command(dir: &Path) -> anyhow::Result { let mut cmd = Command::new(codex_utils_cargo_bin::cargo_bin("apply_patch")?); + cmd.env(CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR, "1"); cmd.current_dir(dir); Ok(cmd) } @@ -116,6 +119,24 @@ fn test_apply_patch_cli_preserves_crlf_from_target_file() -> anyhow::Result<()> ) } +#[test] +fn test_apply_patch_cli_uses_legacy_line_handling_without_rollout_env() -> anyhow::Result<()> { + let tmp = tempdir()?; + let target_path = tmp.path().join("crlf.txt"); + fs::write(&target_path, b"one\r\n")?; + let patch = "*** Begin Patch\n*** Update File: crlf.txt\n@@\n-one\n+uno\n*** End Patch"; + + Command::new(codex_utils_cargo_bin::cargo_bin("apply_patch")?) + .env_remove(CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR) + .arg(patch) + .current_dir(tmp.path()) + .assert() + .success(); + + assert_eq!(fs::read(target_path)?, b"uno\n"); + Ok(()) +} + #[test] fn test_apply_patch_cli_preserves_cr_from_target_file() -> anyhow::Result<()> { let patch = "*** Begin Patch\n*** Update File: cr.txt\n@@\n-one\n+uno\n@@\n two\n+\n+between\n three\n*** End Patch"; diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs index 1c28f81d8c..584850294a 100644 --- a/codex-rs/arg0/src/lib.rs +++ b/codex-rs/arg0/src/lib.rs @@ -123,8 +123,10 @@ pub fn arg0_dispatch() -> Option { Err(_) => std::process::exit(1), }; let cwd = cwd.into(); - match runtime.block_on(codex_apply_patch::apply_patch( + let update_file_mode = codex_apply_patch::apply_patch_file_update_mode_from_env(); + match runtime.block_on(codex_apply_patch::apply_patch_with_mode( &patch_arg, + update_file_mode, &cwd, &mut stdout, &mut stderr, diff --git a/codex-rs/core/src/exec_env.rs b/codex-rs/core/src/exec_env.rs index f33061698b..0065c2ffb6 100644 --- a/codex-rs/core/src/exec_env.rs +++ b/codex-rs/core/src/exec_env.rs @@ -1,3 +1,6 @@ +use codex_apply_patch::CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR; +use codex_features::Feature; +use codex_features::Features; use codex_protocol::ThreadId; #[cfg(test)] use codex_protocol::config_types::EnvironmentVariablePattern; @@ -51,6 +54,18 @@ pub(crate) fn inject_permission_profile_env( } } +/// Carries the apply_patch line-ending rollout state into arg0-dispatched +/// helper processes. The in-process apply_patch path reads the feature directly. +pub(crate) fn inject_apply_patch_env(env: &mut HashMap, features: &Features) { + env.retain(|key, _| !key.eq_ignore_ascii_case(CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR)); + if features.enabled(Feature::ApplyPatchPreserveLineEndings) { + env.insert( + CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_string(), + "1".to_string(), + ); + } +} + #[cfg(all(test, target_os = "windows"))] fn create_env_from_vars( vars: I, diff --git a/codex-rs/core/src/exec_env_tests.rs b/codex-rs/core/src/exec_env_tests.rs index 73c0944c14..b585232522 100644 --- a/codex-rs/core/src/exec_env_tests.rs +++ b/codex-rs/core/src/exec_env_tests.rs @@ -41,6 +41,28 @@ fn inject_permission_profile_env_removes_stale_value_without_active_profile() { assert_eq!(env.get(CODEX_PERMISSION_PROFILE_ENV_VAR), None); } +#[test] +fn inject_apply_patch_env_follows_preserve_line_endings_feature() { + let mut env = HashMap::from([( + CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_ascii_lowercase(), + "stale".to_string(), + )]); + let mut features = Features::with_defaults(); + + inject_apply_patch_env(&mut env, &features); + assert_eq!(env, HashMap::new()); + + features.enable(Feature::ApplyPatchPreserveLineEndings); + inject_apply_patch_env(&mut env, &features); + assert_eq!( + env, + HashMap::from([( + CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS_ENV_VAR.to_string(), + "1".to_string(), + )]) + ); +} + #[cfg(target_os = "windows")] #[test] fn inject_permission_profile_env_replaces_differently_cased_windows_key() { diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 6326dbc1ad..7c70721008 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -37,6 +37,7 @@ use crate::tools::runtimes::apply_patch::ApplyPatchRuntime; use crate::tools::sandboxing::ToolCtx; use codex_apply_patch::ApplyPatchAction; use codex_apply_patch::ApplyPatchFileChange; +use codex_apply_patch::ApplyPatchFileUpdateMode; use codex_apply_patch::Hunk; use codex_apply_patch::StreamingPatchParser; use codex_exec_server::ExecutorFileSystem; @@ -55,6 +56,19 @@ use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; const APPLY_PATCH_ARGUMENT_DIFF_BUFFER_INTERVAL: Duration = Duration::from_millis(500); + +fn apply_patch_file_update_mode(turn: &TurnContext) -> ApplyPatchFileUpdateMode { + if turn + .config + .features + .enabled(Feature::ApplyPatchPreserveLineEndings) + { + ApplyPatchFileUpdateMode::PreserveLineEndings + } else { + ApplyPatchFileUpdateMode::NormalizeToLf + } +} + /// Handles freeform `apply_patch` requests and routes verified patches to the /// selected environment filesystem. #[derive(Default)] @@ -387,9 +401,10 @@ impl ApplyPatchHandler { /*additional_permissions*/ None, turn_environment.cwd(), ); - match codex_apply_patch::verify_apply_patch_args( + match codex_apply_patch::verify_apply_patch_args_with_mode( args, turn_environment.cwd(), + apply_patch_file_update_mode(&turn), fs.as_ref(), Some(&sandbox), ) @@ -555,8 +570,14 @@ pub(crate) async fn intercept_apply_patch( tool_name: &str, ) -> Result, FunctionCallError> { let sandbox = turn.file_system_sandbox_context(/*additional_permissions*/ None, cwd); - match codex_apply_patch::maybe_parse_apply_patch_verified(command, cwd, fs, Some(&sandbox)) - .await + match codex_apply_patch::maybe_parse_apply_patch_verified_with_mode( + command, + cwd, + apply_patch_file_update_mode(&turn), + fs, + Some(&sandbox), + ) + .await { codex_apply_patch::MaybeApplyPatchVerified::Body(changes) => { let (approval_keys, effective_additional_permissions, file_system_sandbox_policy) = diff --git a/codex-rs/core/src/tools/handlers/apply_patch_tests.rs b/codex-rs/core/src/tools/handlers/apply_patch_tests.rs index f346b3d143..e182ce1885 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch_tests.rs @@ -44,6 +44,24 @@ async fn invocation_for_payload(payload: ToolPayload) -> ToolInvocation { } } +#[tokio::test] +async fn file_update_mode_follows_preserve_line_endings_feature() { + let (_, mut turn) = make_session_and_context().await; + assert_eq!( + apply_patch_file_update_mode(&turn), + codex_apply_patch::ApplyPatchFileUpdateMode::NormalizeToLf + ); + + Arc::make_mut(&mut turn.config) + .features + .enable(codex_features::Feature::ApplyPatchPreserveLineEndings) + .expect("feature should be enabled"); + assert_eq!( + apply_patch_file_update_mode(&turn), + codex_apply_patch::ApplyPatchFileUpdateMode::PreserveLineEndings + ); +} + #[tokio::test] async fn pre_tool_use_payload_uses_freeform_patch_input() { let patch = sample_patch(); diff --git a/codex-rs/core/src/tools/handlers/shell/shell_command.rs b/codex-rs/core/src/tools/handlers/shell/shell_command.rs index 62bcee8bdf..99edb918b4 100644 --- a/codex-rs/core/src/tools/handlers/shell/shell_command.rs +++ b/codex-rs/core/src/tools/handlers/shell/shell_command.rs @@ -6,6 +6,7 @@ use codex_utils_absolute_path::AbsolutePathBuf; use crate::exec::ExecCapturePolicy; use crate::exec::ExecParams; use crate::exec_env::create_env; +use crate::exec_env::inject_apply_patch_env; use crate::exec_env::inject_permission_profile_env; use crate::function_tool::FunctionCallError; use crate::maybe_emit_implicit_skill_invocation; @@ -104,6 +105,7 @@ impl ShellCommandHandler { &turn_context.config.permissions.shell_environment_policy, Some(session.thread_id), ); + inject_apply_patch_env(&mut env, &turn_context.config.features); let active_permission_profile = turn_context.config.permissions.active_permission_profile(); inject_permission_profile_env(&mut env, active_permission_profile.as_ref()); diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index b839b05c44..6c82a6202c 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -240,8 +240,9 @@ impl ToolRuntime for ApplyPatchRunti let sandbox = Self::file_system_sandbox_context_for_attempt(req, attempt); let mut stdout = Vec::new(); let mut stderr = Vec::new(); - let result = codex_apply_patch::apply_patch( + let result = codex_apply_patch::apply_patch_with_mode( &req.action.patch, + req.action.update_file_mode(), &req.action.cwd, &mut stdout, &mut stderr, diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index fe3ec45759..d8c12229e6 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -16,6 +16,7 @@ use crate::codex_thread::BackgroundTerminalInfo; use crate::exec_env::CODEX_PERMISSION_PROFILE_ENV_VAR; use crate::exec_env::CODEX_THREAD_ID_ENV_VAR; use crate::exec_env::create_env; +use crate::exec_env::inject_apply_patch_env; use crate::exec_env::inject_permission_profile_env; use crate::exec_policy::ExecApprovalRequest; use crate::sandboxing::ExecOptions; @@ -1114,6 +1115,7 @@ impl UnifiedExecProcessManager { CODEX_THREAD_ID_ENV_VAR.to_string(), context.session.thread_id.to_string(), ); + inject_apply_patch_env(&mut env, &context.turn.config.features); let active_permission_profile = context.turn.config.permissions.active_permission_profile(); inject_permission_profile_env(&mut env, active_permission_profile.as_ref()); let env = apply_unified_exec_env(env); diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index ce5ca459b4..f1657eb479 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -112,6 +112,8 @@ pub enum Feature { TerminalVisualizationInstructions, /// Stream structured progress while apply_patch input is being generated. ApplyPatchStreamingEvents, + /// Preserve existing line endings when apply_patch updates files. + ApplyPatchPreserveLineEndings, /// Allow exec tools to request additional permissions while staying sandboxed. ExecPermissionApprovals, /// Expose the built-in request_permissions tool. @@ -954,6 +956,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::ApplyPatchPreserveLineEndings, + key: "apply_patch_preserve_line_endings", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::ExecPermissionApprovals, key: "exec_permission_approvals",