Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions codex-rs/apply-patch/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,11 @@ async fn derive_new_contents_from_chunks(
})
})?;

let mut original_lines: Vec<String> = original_contents.split('\n').map(String::from).collect();
let line_separator = detect_line_separator(&original_contents);
let mut original_lines: Vec<String> = original_contents
.split('\n')
.map(|line| line.strip_suffix('\r').unwrap_or(line).to_string())
.collect();

// Drop the trailing empty element that results from the final newline so
// that line counts match the behaviour of standard `diff`.
Expand All @@ -678,13 +682,28 @@ async fn derive_new_contents_from_chunks(
if !new_lines.last().is_some_and(String::is_empty) {
new_lines.push(String::new());
}
let new_contents = new_lines.join("\n");
let new_contents = new_lines.join(line_separator);
Ok(AppliedPatch {
original_contents,
new_contents,
})
}

fn detect_line_separator(contents: &str) -> &'static str {
let lf_count = contents
.as_bytes()
.iter()
.filter(|byte| **byte == b'\n')
.count();
let crlf_count = contents.match_indices("\r\n").count();

if lf_count > 0 && lf_count == crlf_count {
"\r\n"
} else {
"\n"
}
}

/// Compute a list of replacements needed to transform `original_lines` into the
/// new lines, given the patch `chunks`. Each replacement is returned as
/// `(start_index, old_len, new_lines)`.
Expand Down
2 changes: 2 additions & 0 deletions codex-rs/apply-patch/tests/fixtures/scenarios/.gitattributes
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
** text eol=lf
023_update_preserves_crlf/input/lines.txt text eol=crlf
023_update_preserves_crlf/expected/lines.txt text eol=crlf
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
alpha
BETA
gamma
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
alpha
beta
gamma
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
*** Begin Patch
*** Update File: lines.txt
@@
-alpha
-beta
-gamma
+alpha
+BETA
+gamma
*** End Patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
alpha
BETA
gamma
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
alpha
beta
gamma
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
*** Begin Patch
*** Update File: lines.txt
@@
-alpha
-beta
-gamma
+alpha
+BETA
+gamma
*** End Patch