use std::fmt;
use std::ops::Range;
use std::path::Path;
use serde::{Deserialize, Serialize};
use similar::{ChangeTag, TextDiff};
use super::display::{Line, Role};
const CONTEXT: usize = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LineRange {
pub start: u32,
pub len: u32,
}
impl LineRange {
fn of(ops: &[similar::DiffOp], side: fn(&similar::DiffOp) -> Range<usize>) -> Self {
let first = side(&ops[0]).start;
let last = side(ops.last().expect("a hunk has an op")).end;
Self {
start: first as u32 + 1,
len: (last - first) as u32,
}
}
pub fn contains(self, line: u32) -> bool {
self.len > 0 && line >= self.start && line < self.start + self.len
}
}
impl fmt::Display for LineRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.len {
0 => write!(f, "{},0", self.start.saturating_sub(1)),
1 => write!(f, "{}", self.start),
n => write!(f, "{},{n}", self.start),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffKind {
Context,
Added,
Removed,
}
impl DiffKind {
pub fn marker(self) -> char {
match self {
Self::Context => ' ',
Self::Added => '+',
Self::Removed => '-',
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffLine {
pub kind: DiffKind,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hunk {
pub old: LineRange,
pub new: LineRange,
pub lines: Vec<DiffLine>,
}
impl Hunk {
pub fn header(&self) -> String {
format!("@@ -{} +{} @@", self.old, self.new)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(into = "String", from = "String")]
pub struct Diff {
text: String,
hunks: Vec<Hunk>,
}
impl Diff {
pub fn new(path: &Path, before: &str, after: &str) -> Self {
Self::between(path, path, before, after)
}
pub fn between(old_path: &Path, new_path: &Path, before: &str, after: &str) -> Self {
let changes = TextDiff::from_lines(before, after);
let mut rendered = changes.unified_diff();
rendered.context_radius(CONTEXT).header(
&format!("a/{}", old_path.display()),
&format!("b/{}", new_path.display()),
);
let hunks = rendered
.iter_hunks()
.map(|hunk| {
let ops = hunk.ops();
let lines = hunk
.iter_changes()
.map(|change| DiffLine {
kind: match change.tag() {
ChangeTag::Equal => DiffKind::Context,
ChangeTag::Delete => DiffKind::Removed,
ChangeTag::Insert => DiffKind::Added,
},
text: change.value().trim_end_matches(['\r', '\n']).to_owned(),
})
.collect();
Hunk {
old: LineRange::of(ops, |op| op.old_range()),
new: LineRange::of(ops, |op| op.new_range()),
lines,
}
})
.collect();
let mut text = rendered.to_string();
if text.is_empty() && old_path != new_path {
text = format!(
"--- a/{}\n+++ b/{}\n",
old_path.display(),
new_path.display()
);
}
Self { text, hunks }
}
pub fn as_str(&self) -> &str {
&self.text
}
pub fn hunks(&self) -> &[Hunk] {
&self.hunks
}
pub fn opening(&self, line: u32) -> usize {
let mut open = 0;
for (i, hunk) in self.hunks.iter().enumerate() {
if hunk.old.start > line {
break;
}
open = i;
}
open
}
pub fn lines(&self) -> impl Iterator<Item = Line> + '_ {
self.lines_from(0)
}
pub fn lines_from(&self, line: u32) -> impl Iterator<Item = Line> + '_ {
self.hunks[self.opening(line)..].iter().flat_map(|hunk| {
std::iter::once(Line::single(Role::Hunk, hunk.header())).chain(hunk.lines.iter().map(
|line| {
let role = match line.kind {
DiffKind::Context => Role::Plain,
DiffKind::Added => Role::Added,
DiffKind::Removed => Role::Removed,
};
Line::single(role, format!("{}{}", line.kind.marker(), line.text))
},
))
})
}
}
impl From<Diff> for String {
fn from(diff: Diff) -> Self {
diff.text
}
}
impl From<String> for Diff {
fn from(text: String) -> Self {
Self {
text,
hunks: Vec::new(),
}
}
}
impl fmt::Display for Diff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
fn two_hunks() -> Diff {
let before: String = (1..=12).map(|k| format!("line {k}\n")).collect();
let after = before
.replace("line 2\n", "line 2 changed\n")
.replace("line 10\n", "line 10 changed\n");
Diff::between(Path::new("a.rs"), Path::new("a.rs"), &before, &after)
}
#[test]
fn hunks_carry_their_ranges_and_lines() {
let diff = two_hunks();
assert_eq!(diff.hunks().len(), 2);
let first = &diff.hunks()[0];
assert_eq!((first.old.start, first.old.len), (1, 5));
assert!(first.old.contains(2), "the changed line is in the range");
assert!(
first
.lines
.iter()
.any(|l| l.kind == DiffKind::Removed && l.text == "line 2")
);
assert!(
first
.lines
.iter()
.any(|l| l.kind == DiffKind::Added && l.text == "line 2 changed")
);
}
#[test]
fn opening_finds_the_hunk_at_or_before_a_line() {
let diff = two_hunks();
assert_eq!(diff.opening(1), 0, "before the first hunk, the first hunk");
assert_eq!(diff.opening(2), 0);
assert_eq!(diff.opening(7), 1, "the second hunk opens at old line 7");
assert_eq!(diff.opening(10), 1);
}
#[test]
fn a_single_line_hunk_has_no_count_in_its_header() {
let diff = Diff::new(Path::new("a.rs"), "a\n", "b\n");
let hunk = &diff.hunks()[0];
assert_eq!(hunk.header(), "@@ -1 +1 @@");
assert_eq!((hunk.old.start, hunk.old.len), (1, 1));
}
}