1use std::collections::hash_map::DefaultHasher;
13use std::hash::{Hash as _, Hasher as _};
14use std::ops::Range;
15
16use serde_json::Value;
17use similar::{Algorithm, DiffOp, capture_diff_slices};
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum LineChange {
23 Added,
25 Modified,
27 Removed,
30}
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct ChangeMark {
35 pub line: usize,
37 pub lines: usize,
39 pub change: LineChange,
41}
42
43pub fn line_changes(old: &str, new: &str) -> Vec<ChangeMark> {
45 let a: Vec<&str> = old.lines().collect();
46 let b: Vec<&str> = new.lines().collect();
47 let mut marks = Vec::new();
48 for op in capture_diff_slices(Algorithm::Myers, &a, &b) {
49 match op {
50 DiffOp::Equal { .. } => {}
51 DiffOp::Insert { new_index, new_len, .. } => marks.push(ChangeMark { line: new_index + 1, lines: new_len, change: LineChange::Added }),
52 DiffOp::Delete { old_len, new_index, .. } => marks.push(ChangeMark { line: new_index + 1, lines: old_len, change: LineChange::Removed }),
53 DiffOp::Replace { old_len, new_index, new_len, .. } => {
56 let paired = old_len.min(new_len);
57 if paired > 0 {
58 marks.push(ChangeMark { line: new_index + 1, lines: paired, change: LineChange::Modified });
59 }
60 if new_len > paired {
61 marks.push(ChangeMark { line: new_index + paired + 1, lines: new_len - paired, change: LineChange::Added });
62 } else if old_len > paired {
63 marks.push(ChangeMark { line: new_index + paired + 1, lines: old_len - paired, change: LineChange::Removed });
64 }
65 }
66 }
67 }
68 marks
69}
70
71pub const CONTEXT: usize = 3;
73pub const ARRAY_SUMMARY: usize = 16;
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum LineKind {
79 Context,
81 Added,
83 Removed,
85 Summary,
87}
88
89#[derive(Clone, Debug, PartialEq, Eq)]
91pub struct DiffLine {
92 pub kind: LineKind,
94 pub old: Option<usize>,
96 pub new: Option<usize>,
98 pub text: String,
100}
101
102#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct Hunk {
105 pub lines: Range<usize>,
107 pub old_start: usize,
109 pub old_len: usize,
111 pub new_start: usize,
113 pub new_len: usize,
115}
116
117impl Hunk {
118 pub fn header(&self) -> String {
120 format!("@@ -{},{} +{},{} @@", self.old_start, self.old_len, self.new_start, self.new_len)
121 }
122}
123
124#[derive(Clone, Debug, Default, PartialEq, Eq)]
126pub struct Diff {
127 pub lines: Vec<DiffLine>,
130 pub hunks: Vec<Hunk>,
133 pub json: bool,
135 pub note: Option<String>,
137}
138
139impl Diff {
140 pub fn text(old: &str, new: &str, context: usize) -> Diff {
142 let (a, b): (Vec<&str>, Vec<&str>) = (old.lines().collect(), new.lines().collect());
143 let lines = walk(&a, &b, |i| a[i].to_string(), |i| b[i].to_string());
144 let hunks = hunks(&lines, context);
145 Diff { lines, hunks, json: false, note: None }
146 }
147
148 pub fn json(old: &str, new: &str, context: usize, array_summary: usize) -> Diff {
151 let parse = |s: &str| if s.trim().is_empty() { Ok(Value::Null) } else { serde_json::from_str::<Value>(s) };
152 match (parse(old), parse(new)) {
153 (Ok(a), Ok(b)) => Diff::json_values(&a, &b, context, array_summary),
154 (a, b) => {
155 let which = if a.is_err() { "old" } else { "new" };
156 let e = a.err().or(b.err()).map(|e| e.to_string()).unwrap_or_default();
157 Diff { note: Some(format!("The {which} side is not JSON ({e}); compared as text.")), ..Diff::text(old, new, context) }
158 }
159 }
160 }
161
162 pub fn json_values(old: &Value, new: &Value, context: usize, array_summary: usize) -> Diff {
167 let (a, b) = (print_json(old, array_summary), print_json(new, array_summary));
168 let (ka, kb): (Vec<&str>, Vec<&str>) = (a.iter().map(|l| l.key.as_str()).collect(), b.iter().map(|l| l.key.as_str()).collect());
169 let mut lines = walk(&ka, &kb, |i| a[i].display.clone(), |i| b[i].display.clone());
170 merge_summaries(&mut lines, &a, &b);
171 let hunks = hunks(&lines, context);
172 Diff { lines, hunks, json: true, note: None }
173 }
174
175 pub fn is_empty(&self) -> bool {
177 self.hunks.is_empty()
178 }
179
180 pub fn added(&self) -> usize {
182 self.lines.iter().filter(|l| matches!(l.kind, LineKind::Added | LineKind::Summary)).count()
183 }
184
185 pub fn removed(&self) -> usize {
187 self.lines.iter().filter(|l| matches!(l.kind, LineKind::Removed | LineKind::Summary)).count()
188 }
189
190 pub fn gaps(&self) -> Vec<Range<usize>> {
194 let mut out = Vec::new();
195 let mut at = 0;
196 for h in &self.hunks {
197 if h.lines.start > at {
198 out.push(at..h.lines.start);
199 }
200 at = h.lines.end;
201 }
202 if at < self.lines.len() {
203 out.push(at..self.lines.len());
204 }
205 out
206 }
207
208 pub fn unified(&self) -> String {
211 let mut out = String::new();
212 for h in &self.hunks {
213 out.push_str(&h.header());
214 out.push('\n');
215 for l in &self.lines[h.lines.clone()] {
216 out.push(match l.kind {
217 LineKind::Context => ' ',
218 LineKind::Added => '+',
219 LineKind::Removed => '-',
220 LineKind::Summary => '~',
221 });
222 out.push_str(&l.text);
223 out.push('\n');
224 }
225 }
226 out
227 }
228
229 pub fn apply(&self, accepted: &[bool]) -> Option<String> {
233 if self.json {
234 return None;
235 }
236 let hunk_of = |i: usize| self.hunks.iter().position(|h| h.lines.contains(&i));
237 let mut out: Vec<&str> = Vec::new();
238 for (i, l) in self.lines.iter().enumerate() {
239 let take = match l.kind {
240 LineKind::Context | LineKind::Summary => true,
241 LineKind::Added => hunk_of(i).is_some_and(|h| accepted.get(h).copied().unwrap_or(false)),
242 LineKind::Removed => !hunk_of(i).is_some_and(|h| accepted.get(h).copied().unwrap_or(false)),
243 };
244 if take {
245 out.push(&l.text);
246 }
247 }
248 let mut s = out.join("\n");
249 if !s.is_empty() {
250 s.push('\n');
251 }
252 Some(s)
253 }
254}
255
256fn walk<K: Eq + std::hash::Hash>(a: &[K], b: &[K], old_text: impl Fn(usize) -> String, new_text: impl Fn(usize) -> String) -> Vec<DiffLine> {
258 let mut lines = Vec::with_capacity(a.len().max(b.len()));
259 let removed = |lines: &mut Vec<DiffLine>, from: usize, len: usize| {
260 lines.extend((from..from + len).map(|i| DiffLine { kind: LineKind::Removed, old: Some(i + 1), new: None, text: old_text(i) }));
261 };
262 let added = |lines: &mut Vec<DiffLine>, from: usize, len: usize| {
263 lines.extend((from..from + len).map(|i| DiffLine { kind: LineKind::Added, old: None, new: Some(i + 1), text: new_text(i) }));
264 };
265 for op in capture_diff_slices(Algorithm::Myers, a, b) {
266 match op {
267 DiffOp::Equal { old_index, new_index, len } => {
268 lines.extend((0..len).map(|k| DiffLine { kind: LineKind::Context, old: Some(old_index + k + 1), new: Some(new_index + k + 1), text: new_text(new_index + k) }));
270 }
271 DiffOp::Delete { old_index, old_len, .. } => removed(&mut lines, old_index, old_len),
272 DiffOp::Insert { new_index, new_len, .. } => added(&mut lines, new_index, new_len),
273 DiffOp::Replace { old_index, old_len, new_index, new_len } => {
274 removed(&mut lines, old_index, old_len);
275 added(&mut lines, new_index, new_len);
276 }
277 }
278 }
279 lines
280}
281
282fn hunks(lines: &[DiffLine], context: usize) -> Vec<Hunk> {
285 let mut ranges: Vec<Range<usize>> = Vec::new();
286 for (i, l) in lines.iter().enumerate() {
287 if l.kind == LineKind::Context {
288 continue;
289 }
290 let r = i.saturating_sub(context)..(i + 1 + context).min(lines.len());
291 match ranges.last_mut() {
292 Some(last) if r.start <= last.end => last.end = last.end.max(r.end),
293 _ => ranges.push(r),
294 }
295 }
296 ranges
297 .into_iter()
298 .map(|r| {
299 let before = &lines[..r.start];
300 let old_before = before.iter().filter(|l| l.old.is_some()).count();
301 let new_before = before.iter().filter(|l| l.new.is_some()).count();
302 let inside = &lines[r.clone()];
303 let old_len = inside.iter().filter(|l| l.old.is_some()).count();
304 let new_len = inside.iter().filter(|l| l.new.is_some()).count();
305 Hunk {
306 lines: r,
307 old_start: if old_len > 0 { old_before + 1 } else { old_before },
308 old_len,
309 new_start: if new_len > 0 { new_before + 1 } else { new_before },
310 new_len,
311 }
312 })
313 .collect()
314}
315
316struct JsonLine {
318 key: String,
319 display: String,
320 array: Option<(String, usize)>,
321}
322
323fn print_json(v: &Value, array_summary: usize) -> Vec<JsonLine> {
325 let mut out = Vec::new();
326 print_value(v, 0, "", None, false, array_summary, &mut out);
327 out
328}
329
330fn print_value(v: &Value, depth: usize, prefix: &str, label: Option<&str>, comma: bool, max: usize, out: &mut Vec<JsonLine>) {
331 let pad = " ".repeat(depth);
332 let c = if comma { "," } else { "" };
333 let mut line = |body: String, array: Option<(String, usize)>, hash: Option<u64>| {
334 let key = match hash {
335 Some(h) => format!("{pad}{prefix}{body}#{h:016x}"),
336 None => format!("{pad}{prefix}{body}"),
337 };
338 out.push(JsonLine { display: format!("{pad}{prefix}{body}{c}"), key, array });
339 };
340 match v {
341 Value::Object(map) if !map.is_empty() => {
342 line("{".into(), None, None);
343 let mut keys: Vec<&String> = map.keys().collect();
344 keys.sort();
345 let n = keys.len();
346 for (i, k) in keys.into_iter().enumerate() {
347 let p = format!("{}: ", Value::String(k.clone()));
348 print_value(&map[k], depth + 1, &p, Some(k), i + 1 < n, max, out);
349 }
350 out.push(JsonLine { key: format!("{pad}}}"), display: format!("{pad}}}{c}"), array: None });
351 }
352 Value::Array(items) if items.len() > max => {
353 let mut h = DefaultHasher::new();
354 serde_json::to_string(v).unwrap_or_default().hash(&mut h);
355 let name = label.unwrap_or("items").to_string();
356 line(format!("[{} items]", group_digits(items.len())), Some((name, items.len())), Some(h.finish()));
357 }
358 Value::Array(items) if !items.is_empty() => {
359 line("[".into(), None, None);
360 let n = items.len();
361 for (i, item) in items.iter().enumerate() {
362 print_value(item, depth + 1, "", label, i + 1 < n, max, out);
363 }
364 out.push(JsonLine { key: format!("{pad}]"), display: format!("{pad}]{c}"), array: None });
365 }
366 _ => line(serde_json::to_string(v).unwrap_or_default(), None, None),
367 }
368}
369
370fn merge_summaries(lines: &mut Vec<DiffLine>, a: &[JsonLine], b: &[JsonLine]) {
373 let array_of = |l: &DiffLine| match l.kind {
374 LineKind::Removed => l.old.and_then(|n| a[n - 1].array.clone()),
375 LineKind::Added => l.new.and_then(|n| b[n - 1].array.clone()),
376 _ => None,
377 };
378 let mut i = 0;
379 while i < lines.len() {
380 if lines[i].kind == LineKind::Context {
381 i += 1;
382 continue;
383 }
384 let end = (i..lines.len()).find(|&j| lines[j].kind == LineKind::Context).unwrap_or(lines.len());
385 let mut drop = Vec::new();
386 for r in i..end {
387 if lines[r].kind != LineKind::Removed {
388 continue;
389 }
390 let Some((name, old_len)) = array_of(&lines[r]) else { continue };
391 let found = (i..end).find(|&j| !drop.contains(&j) && lines[j].kind == LineKind::Added && array_of(&lines[j]).is_some_and(|(n, _)| n == name));
392 if let Some(j) = found {
393 let new_len = array_of(&lines[j]).map(|(_, n)| n).unwrap_or(0);
394 let pad: String = lines[r].text.chars().take_while(|c| *c == ' ').collect();
395 let text = if old_len == new_len {
396 format!("{pad}{name}: {} items, changed", group_digits(new_len))
397 } else {
398 format!("{pad}{name}: {} → {}", group_digits(old_len), group_digits(new_len))
399 };
400 lines[r] = DiffLine { kind: LineKind::Summary, old: lines[r].old, new: lines[j].new, text };
401 drop.push(j);
402 }
403 }
404 drop.sort_unstable();
405 for j in drop.iter().rev() {
406 lines.remove(*j);
407 }
408 i = end - drop.len();
409 }
410}
411
412pub fn group_digits(n: usize) -> String {
414 let s = n.to_string();
415 let mut out = String::with_capacity(s.len() + s.len() / 3);
416 for (i, ch) in s.chars().enumerate() {
417 if i > 0 && (s.len() - i) % 3 == 0 {
418 out.push(',');
419 }
420 out.push(ch);
421 }
422 out
423}
424
425#[cfg(test)]
426mod tests {
427 #[test]
428 fn change_marks_say_what_changed_on_which_lines() {
429 let old = "a\nb\nc\nd\ne\n";
430 let new = "a\nB\nc\nx\ny\nd\n";
431 assert_eq!(
432 super::line_changes(old, new),
433 vec![
434 ChangeMark { line: 2, lines: 1, change: LineChange::Modified },
435 ChangeMark { line: 4, lines: 2, change: LineChange::Added },
436 ChangeMark { line: 7, lines: 1, change: LineChange::Removed },
437 ]
438 );
439 assert!(super::line_changes(old, old).is_empty());
440 assert_eq!(
442 super::line_changes("a\nb\n", "a\nB\nc\n"),
443 vec![ChangeMark { line: 2, lines: 1, change: LineChange::Modified }, ChangeMark { line: 3, lines: 1, change: LineChange::Added }]
444 );
445 }
446
447 use super::*;
448 use serde_json::json;
449
450 fn kinds(d: &Diff) -> String {
451 d.lines
452 .iter()
453 .map(|l| match l.kind {
454 LineKind::Context => ' ',
455 LineKind::Added => '+',
456 LineKind::Removed => '-',
457 LineKind::Summary => '~',
458 })
459 .collect()
460 }
461
462 #[test]
463 fn text_diff_numbers_lines_and_folds_context() {
464 let old: String = (1..=20).map(|i| format!("line {i}\n")).collect();
465 let new = old.replace("line 5\n", "line five\n").replace("line 18\n", "line 18\nline 18b\n");
466 let d = Diff::text(&old, &new, 2);
467 assert_eq!(d.added(), 2);
468 assert_eq!(d.removed(), 1);
469 assert_eq!(d.hunks.len(), 2, "two changes far apart: two hunks");
470 let h = &d.hunks[0];
471 assert_eq!(h.header(), "@@ -3,5 +3,5 @@");
472 let first: Vec<&DiffLine> = d.lines[h.lines.clone()].iter().collect();
473 assert_eq!(first[2].kind, LineKind::Removed);
474 assert_eq!((first[2].old, first[2].new), (Some(5), None));
475 assert_eq!(first[3].kind, LineKind::Added);
476 assert_eq!((first[3].old, first[3].new), (None, Some(5)));
477 assert_eq!(d.hunks[1].header(), "@@ -17,4 +17,5 @@");
478 let gaps = d.gaps();
480 assert_eq!(gaps.len(), 2);
481 assert_eq!(gaps[0], 0..2);
482 assert_eq!(gaps[1].len(), 9);
483 assert!(d.gaps().iter().flat_map(|g| d.lines[g.clone()].iter()).all(|l| l.kind == LineKind::Context));
484 }
485
486 #[test]
487 fn near_changes_share_a_hunk() {
488 let d = Diff::text("a\nb\nc\nd\ne\n", "a\nB\nc\nD\ne\n", 3);
489 assert_eq!(d.hunks.len(), 1);
490 assert_eq!(kinds(&d), " -+ -+ ");
491 assert!(Diff::text("same\n", "same\n", 3).is_empty());
492 }
493
494 #[test]
495 fn apply_takes_only_accepted_hunks() {
496 let old: String = (1..=20).map(|i| format!("l{i}\n")).collect();
497 let new = old.replace("l2\n", "two\n").replace("l19\n", "nineteen\n");
498 let d = Diff::text(&old, &new, 1);
499 assert_eq!(d.hunks.len(), 2);
500 assert_eq!(d.apply(&[true, true]).unwrap(), new);
501 assert_eq!(d.apply(&[false, false]).unwrap(), old);
502 assert_eq!(d.apply(&[false, true]).unwrap(), old.replace("l19\n", "nineteen\n"));
503 assert!(d.unified().starts_with("@@ -1,3 +1,3 @@\n l1\n-l2\n+two\n"), "{}", d.unified());
504 }
505
506 #[test]
507 fn json_ignores_key_order_and_trailing_commas() {
508 let old = r#"{"b": 1, "a": {"y": 2, "x": 1}}"#;
509 let new = r#"{"a": {"x": 1, "y": 2}, "b": 1}"#;
510 assert!(Diff::json(old, new, CONTEXT, ARRAY_SUMMARY).is_empty());
511 let d = Diff::json(r#"{"a": 1}"#, r#"{"a": 1, "b": 2}"#, CONTEXT, ARRAY_SUMMARY);
513 assert_eq!(kinds(&d), " + ");
514 assert_eq!(d.lines[1].text, r#" "a": 1,"#);
515 assert_eq!(d.lines[2].text, r#" "b": 2"#);
516 }
517
518 #[test]
519 fn json_long_arrays_are_one_summary_line() {
520 let old = json!({"cells": (0..2539).collect::<Vec<_>>(), "image": "slide-01", "tiles": (0..40).collect::<Vec<_>>()});
521 let new = json!({"tiles": (0..40).collect::<Vec<_>>(), "image": "slide-01", "cells": (0..2712).collect::<Vec<_>>()});
522 let d = Diff::json_values(&old, &new, CONTEXT, ARRAY_SUMMARY);
523 assert_eq!(d.lines.len(), 5, "{:#?}", d.lines);
524 assert_eq!(kinds(&d), " ~ ");
525 assert_eq!(d.lines[1].text, " cells: 2,539 → 2,712");
526 assert_eq!(d.lines[3].text, r#" "tiles": [40 items]"#);
527 let d = Diff::json_values(&json!({"cells": (0..100).collect::<Vec<_>>()}), &json!({"cells": (1..101).collect::<Vec<_>>()}), CONTEXT, ARRAY_SUMMARY);
529 assert_eq!(d.lines[1].text, " cells: 100 items, changed");
530 let d = Diff::json_values(&json!({"steps": [1, 2]}), &json!({"steps": [1, 3]}), CONTEXT, ARRAY_SUMMARY);
532 assert_eq!(kinds(&d), " -+ ");
533 }
534
535 #[test]
536 fn json_that_does_not_parse_falls_back_to_text() {
537 let d = Diff::json("{\"a\": 1}", "{oops", CONTEXT, ARRAY_SUMMARY);
538 assert!(!d.json);
539 assert!(d.note.as_deref().is_some_and(|n| n.starts_with("The new side is not JSON")));
540 assert_eq!(d.added(), 1);
541 }
542
543 #[test]
544 fn digits_are_grouped() {
545 assert_eq!(group_digits(0), "0");
546 assert_eq!(group_digits(999), "999");
547 assert_eq!(group_digits(2539), "2,539");
548 assert_eq!(group_digits(1234567), "1,234,567");
549 }
550}