Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid unnecessary line break at end of files; EOL type detection #50

Open
wants to merge 1 commit into
base: senpai
Choose a base branch
from
Open
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
26 changes: 22 additions & 4 deletions src/udiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,19 @@ impl Patchable for Diffs {
}

fn patch(&self, ranges: &HashSet<DiffRange>, before: &str) -> String {
// str::lines() only support LF and CRLF
let eol = if before.contains('\r') {
"\r\n".to_owned()
} else {
// when the original file hasn't got any line break,
// it doesn't matter if this is wrong
"\n".to_owned()
};
let eof = before
.chars()
.last()
.map(|c| c == '\n')
.unwrap_or_else(|| false);
let before = before.lines().collect::<Vec<_>>();
let mut ret = String::new();
let mut prev = 0;
Expand All @@ -112,20 +125,20 @@ impl Patchable for Diffs {
.get(i)
.map(|b| ret.push_str(b))
.expect("algo failure");
ret.push('\n');
ret.push_str(&eol);
}
if ranges.contains(&diff.range) {
for line in diff.new_lines.iter() {
ret.push_str(line);
ret.push('\n')
ret.push_str(&eol)
}
} else {
for i in before_start..before_end {
before
.get(i)
.map(|b| ret.push_str(b))
.expect("algo failure");
ret.push('\n')
ret.push_str(&eol)
}
}
prev = before_end;
Expand All @@ -135,7 +148,12 @@ impl Patchable for Diffs {
.get(i)
.map(|b| ret.push_str(b))
.expect("algo failure");
ret.push('\n')
ret.push_str(&eol)
}
if !eof {
for _ in 0..eol.len() {
ret.pop();
}
}
ret
}
Expand Down