From 4883b1dd5282fa6851e4316814537e3553741003 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Tue, 7 Jul 2026 10:36:22 -0400 Subject: [PATCH] Preserve EOF insertion after blank lines --- codex-rs/apply-patch/src/lib.rs | 18 ++++++++++++------ codex-rs/apply-patch/tests/suite/tool.rs | 12 ++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/codex-rs/apply-patch/src/lib.rs b/codex-rs/apply-patch/src/lib.rs index b1bf5a205a..5f7d5c5807 100644 --- a/codex-rs/apply-patch/src/lib.rs +++ b/codex-rs/apply-patch/src/lib.rs @@ -849,12 +849,18 @@ fn compute_replacements( } if chunk.old_lines.is_empty() { - // Pure addition (no old lines). We'll add them at the end or just - // before the final empty line if one exists. - let insertion_idx = if original_lines.last().is_some_and(String::is_empty) { - original_lines.len() - 1 - } else { - original_lines.len() + // Preserve the legacy split representation's handling of a final + // empty line. `SourceFile` only exposes real source lines, so its + // insertion point is always after the final line. + let insertion_idx = match update_file_mode { + ApplyPatchFileUpdateMode::NormalizeToLf => { + if original_lines.last().is_some_and(String::is_empty) { + original_lines.len() - 1 + } else { + original_lines.len() + } + } + ApplyPatchFileUpdateMode::PreserveLineEndings => original_lines.len(), }; replacements.push((insertion_idx, 0, chunk.new_lines.clone())); continue; diff --git a/codex-rs/apply-patch/tests/suite/tool.rs b/codex-rs/apply-patch/tests/suite/tool.rs index 192384285f..36d37efe1c 100644 --- a/codex-rs/apply-patch/tests/suite/tool.rs +++ b/codex-rs/apply-patch/tests/suite/tool.rs @@ -139,6 +139,18 @@ fn test_apply_patch_cli_preserves_crlf_from_target_file() -> anyhow::Result<()> ) } +#[test] +fn test_apply_patch_cli_appends_after_trailing_blank_crlf_line() -> anyhow::Result<()> { + let patch = "*** Begin Patch\n*** Update File: trailing_blank.txt\n@@\n+new\n*** End Patch"; + + assert_apply_patch_updates_file( + "trailing_blank.txt", + b"a\r\n\r\n", + patch, + b"a\r\n\r\nnew\r\n", + ) +} + #[test] fn test_apply_patch_cli_uses_legacy_line_handling_without_rollout_env() -> anyhow::Result<()> { let tmp = tempdir()?;