use similar::{Algorithm, ChangeTag, TextDiff};
pub(super) struct Line<'a> {
pub tag: ChangeTag,
pub text: &'a str,
}
fn split(value: &str, strip_trailing_cr: bool) -> Vec<&str> {
value
.split('\n')
.map(|line| {
if strip_trailing_cr {
line.strip_suffix('\r').unwrap_or(line)
} else {
line
}
})
.collect()
}
pub(super) fn diff_lines<'a>(
before: &'a str,
after: &'a str,
strip_trailing_cr: bool,
) -> Vec<Line<'a>> {
let before = split(before, strip_trailing_cr);
let after = split(after, strip_trailing_cr);
TextDiff::configure()
.algorithm(Algorithm::Myers)
.diff_slices(&before, &after)
.iter_all_changes()
.map(|change| Line {
tag: change.tag(),
text: change.value(),
})
.collect()
}
pub(super) fn has_changes(lines: &[Line<'_>]) -> bool {
lines.iter().any(|line| line.tag != ChangeTag::Equal)
}
pub(super) fn render(lines: &[Line<'_>], context: Option<usize>) -> String {
let distances = context.map(|_| distances(lines));
let mut out = String::new();
let mut omitting = false;
for (index, line) in lines.iter().enumerate() {
if let (Some(context), Some(distances)) = (context, &distances)
&& distances[index] > context
{
if !omitting {
out.push_str("...\n");
omitting = true;
}
continue;
}
omitting = false;
match line.tag {
ChangeTag::Insert => out.push_str("+ "),
ChangeTag::Delete => out.push_str("- "),
ChangeTag::Equal if !line.text.is_empty() => out.push_str(" "),
ChangeTag::Equal => {}
}
out.push_str(line.text);
out.push('\n');
}
out
}
fn distances(lines: &[Line<'_>]) -> Vec<usize> {
let mut distances = vec![usize::MAX; lines.len()];
let mut last = None;
for (index, line) in lines.iter().enumerate() {
if line.tag != ChangeTag::Equal {
last = Some(index);
}
if let Some(last) = last {
distances[index] = index - last;
}
}
last = None;
for (index, line) in lines.iter().enumerate().rev() {
if line.tag != ChangeTag::Equal {
last = Some(index);
}
if let Some(last) = last {
distances[index] = distances[index].min(last - index);
}
}
distances
}