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, .. } => {
52 marks.push(ChangeMark { line: new_index + 1, lines: new_len, change: LineChange::Added })
53 }
54 DiffOp::Delete { old_len, new_index, .. } => {
55 marks.push(ChangeMark { line: new_index + 1, lines: old_len, change: LineChange::Removed })
56 }
57 DiffOp::Replace { old_len, new_index, new_len, .. } => {
60 let paired = old_len.min(new_len);
61 if paired > 0 {
62 marks.push(ChangeMark { line: new_index + 1, lines: paired, change: LineChange::Modified });
63 }
64 if new_len > paired {
65 marks.push(ChangeMark {
66 line: new_index + paired + 1,
67 lines: new_len - paired,
68 change: LineChange::Added,
69 });
70 } else if old_len > paired {
71 marks.push(ChangeMark {
72 line: new_index + paired + 1,
73 lines: old_len - paired,
74 change: LineChange::Removed,
75 });
76 }
77 }
78 }
79 }
80 marks
81}
82
83pub const CONTEXT: usize = 3;
85pub const ARRAY_SUMMARY: usize = 16;
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum LineKind {
91 Context,
93 Added,
95 Removed,
97 Summary,
99}
100
101#[derive(Clone, Debug, PartialEq, Eq)]
103pub struct DiffLine {
104 pub kind: LineKind,
106 pub old: Option<usize>,
108 pub new: Option<usize>,
110 pub text: String,
112}
113
114#[derive(Clone, Debug, PartialEq, Eq)]
116pub struct Hunk {
117 pub lines: Range<usize>,
119 pub old_start: usize,
121 pub old_len: usize,
123 pub new_start: usize,
125 pub new_len: usize,
127}
128
129impl Hunk {
130 pub fn header(&self) -> String {
132 format!("@@ -{},{} +{},{} @@", self.old_start, self.old_len, self.new_start, self.new_len)
133 }
134}
135
136#[derive(Clone, Debug, Default, PartialEq, Eq)]
138pub struct Diff {
139 pub lines: Vec<DiffLine>,
142 pub hunks: Vec<Hunk>,
145 pub json: bool,
147 pub note: Option<String>,
149}
150
151impl Diff {
152 pub fn text(old: &str, new: &str, context: usize) -> Diff {
154 let (a, b): (Vec<&str>, Vec<&str>) = (old.lines().collect(), new.lines().collect());
155 let lines = walk(&a, &b, |i| a[i].to_string(), |i| b[i].to_string());
156 let hunks = hunks(&lines, context);
157 Diff { lines, hunks, json: false, note: None }
158 }
159
160 pub fn json(old: &str, new: &str, context: usize, array_summary: usize) -> Diff {
163 let parse = |s: &str| if s.trim().is_empty() { Ok(Value::Null) } else { serde_json::from_str::<Value>(s) };
164 match (parse(old), parse(new)) {
165 (Ok(a), Ok(b)) => Diff::json_values(&a, &b, context, array_summary),
166 (a, b) => {
167 let which = if a.is_err() { "old" } else { "new" };
168 let e = a.err().or(b.err()).map(|e| e.to_string()).unwrap_or_default();
169 Diff {
170 note: Some(format!("The {which} side is not JSON ({e}); compared as text.")),
171 ..Diff::text(old, new, context)
172 }
173 }
174 }
175 }
176
177 pub fn json_values(old: &Value, new: &Value, context: usize, array_summary: usize) -> Diff {
182 let (a, b) = (print_json(old, array_summary), print_json(new, array_summary));
183 let (ka, kb): (Vec<&str>, Vec<&str>) =
184 (a.iter().map(|l| l.key.as_str()).collect(), b.iter().map(|l| l.key.as_str()).collect());
185 let mut lines = walk(&ka, &kb, |i| a[i].display.clone(), |i| b[i].display.clone());
186 merge_summaries(&mut lines, &a, &b);
187 let hunks = hunks(&lines, context);
188 Diff { lines, hunks, json: true, note: None }
189 }
190
191 pub fn is_empty(&self) -> bool {
193 self.hunks.is_empty()
194 }
195
196 pub fn added(&self) -> usize {
198 self.lines.iter().filter(|l| matches!(l.kind, LineKind::Added | LineKind::Summary)).count()
199 }
200
201 pub fn removed(&self) -> usize {
203 self.lines.iter().filter(|l| matches!(l.kind, LineKind::Removed | LineKind::Summary)).count()
204 }
205
206 pub fn gaps(&self) -> Vec<Range<usize>> {
210 let mut out = Vec::new();
211 let mut at = 0;
212 for h in &self.hunks {
213 if h.lines.start > at {
214 out.push(at..h.lines.start);
215 }
216 at = h.lines.end;
217 }
218 if at < self.lines.len() {
219 out.push(at..self.lines.len());
220 }
221 out
222 }
223
224 pub fn unified(&self) -> String {
227 let mut out = String::new();
228 for h in &self.hunks {
229 out.push_str(&h.header());
230 out.push('\n');
231 for l in &self.lines[h.lines.clone()] {
232 out.push(match l.kind {
233 LineKind::Context => ' ',
234 LineKind::Added => '+',
235 LineKind::Removed => '-',
236 LineKind::Summary => '~',
237 });
238 out.push_str(&l.text);
239 out.push('\n');
240 }
241 }
242 out
243 }
244
245 pub fn apply(&self, accepted: &[bool]) -> Option<String> {
249 if self.json {
250 return None;
251 }
252 let hunk_of = |i: usize| self.hunks.iter().position(|h| h.lines.contains(&i));
253 let mut out: Vec<&str> = Vec::new();
254 for (i, l) in self.lines.iter().enumerate() {
255 let take = match l.kind {
256 LineKind::Context | LineKind::Summary => true,
257 LineKind::Added => hunk_of(i).is_some_and(|h| accepted.get(h).copied().unwrap_or(false)),
258 LineKind::Removed => !hunk_of(i).is_some_and(|h| accepted.get(h).copied().unwrap_or(false)),
259 };
260 if take {
261 out.push(&l.text);
262 }
263 }
264 let mut s = out.join("\n");
265 if !s.is_empty() {
266 s.push('\n');
267 }
268 Some(s)
269 }
270}
271
272fn walk<K: Eq + std::hash::Hash>(
274 a: &[K],
275 b: &[K],
276 old_text: impl Fn(usize) -> String,
277 new_text: impl Fn(usize) -> String,
278) -> Vec<DiffLine> {
279 let mut lines = Vec::with_capacity(a.len().max(b.len()));
280 let removed = |lines: &mut Vec<DiffLine>, from: usize, len: usize| {
281 lines.extend((from..from + len).map(|i| DiffLine {
282 kind: LineKind::Removed,
283 old: Some(i + 1),
284 new: None,
285 text: old_text(i),
286 }));
287 };
288 let added = |lines: &mut Vec<DiffLine>, from: usize, len: usize| {
289 lines.extend((from..from + len).map(|i| DiffLine {
290 kind: LineKind::Added,
291 old: None,
292 new: Some(i + 1),
293 text: new_text(i),
294 }));
295 };
296 for op in capture_diff_slices(Algorithm::Myers, a, b) {
297 match op {
298 DiffOp::Equal { old_index, new_index, len } => {
299 lines.extend((0..len).map(|k| DiffLine {
301 kind: LineKind::Context,
302 old: Some(old_index + k + 1),
303 new: Some(new_index + k + 1),
304 text: new_text(new_index + k),
305 }));
306 }
307 DiffOp::Delete { old_index, old_len, .. } => removed(&mut lines, old_index, old_len),
308 DiffOp::Insert { new_index, new_len, .. } => added(&mut lines, new_index, new_len),
309 DiffOp::Replace { old_index, old_len, new_index, new_len } => {
310 removed(&mut lines, old_index, old_len);
311 added(&mut lines, new_index, new_len);
312 }
313 }
314 }
315 lines
316}
317
318fn hunks(lines: &[DiffLine], context: usize) -> Vec<Hunk> {
321 let mut ranges: Vec<Range<usize>> = Vec::new();
322 for (i, l) in lines.iter().enumerate() {
323 if l.kind == LineKind::Context {
324 continue;
325 }
326 let r = i.saturating_sub(context)..(i + 1 + context).min(lines.len());
327 match ranges.last_mut() {
328 Some(last) if r.start <= last.end => last.end = last.end.max(r.end),
329 _ => ranges.push(r),
330 }
331 }
332 ranges
333 .into_iter()
334 .map(|r| {
335 let before = &lines[..r.start];
336 let old_before = before.iter().filter(|l| l.old.is_some()).count();
337 let new_before = before.iter().filter(|l| l.new.is_some()).count();
338 let inside = &lines[r.clone()];
339 let old_len = inside.iter().filter(|l| l.old.is_some()).count();
340 let new_len = inside.iter().filter(|l| l.new.is_some()).count();
341 Hunk {
342 lines: r,
343 old_start: if old_len > 0 { old_before + 1 } else { old_before },
344 old_len,
345 new_start: if new_len > 0 { new_before + 1 } else { new_before },
346 new_len,
347 }
348 })
349 .collect()
350}
351
352struct JsonLine {
354 key: String,
355 display: String,
356 array: Option<(String, usize)>,
357}
358
359fn print_json(v: &Value, array_summary: usize) -> Vec<JsonLine> {
361 let mut out = Vec::new();
362 print_value(v, 0, "", None, false, array_summary, &mut out);
363 out
364}
365
366fn print_value(
367 v: &Value,
368 depth: usize,
369 prefix: &str,
370 label: Option<&str>,
371 comma: bool,
372 max: usize,
373 out: &mut Vec<JsonLine>,
374) {
375 let pad = " ".repeat(depth);
376 let c = if comma { "," } else { "" };
377 let mut line = |body: String, array: Option<(String, usize)>, hash: Option<u64>| {
378 let key = match hash {
379 Some(h) => format!("{pad}{prefix}{body}#{h:016x}"),
380 None => format!("{pad}{prefix}{body}"),
381 };
382 out.push(JsonLine { display: format!("{pad}{prefix}{body}{c}"), key, array });
383 };
384 match v {
385 Value::Object(map) if !map.is_empty() => {
386 line("{".into(), None, None);
387 let mut keys: Vec<&String> = map.keys().collect();
388 keys.sort();
389 let n = keys.len();
390 for (i, k) in keys.into_iter().enumerate() {
391 let p = format!("{}: ", Value::String(k.clone()));
392 print_value(&map[k], depth + 1, &p, Some(k), i + 1 < n, max, out);
393 }
394 out.push(JsonLine { key: format!("{pad}}}"), display: format!("{pad}}}{c}"), array: None });
395 }
396 Value::Array(items) if items.len() > max => {
397 let mut h = DefaultHasher::new();
398 serde_json::to_string(v).unwrap_or_default().hash(&mut h);
399 let name = label.unwrap_or("items").to_string();
400 line(format!("[{} items]", group_digits(items.len())), Some((name, items.len())), Some(h.finish()));
401 }
402 Value::Array(items) if !items.is_empty() => {
403 line("[".into(), None, None);
404 let n = items.len();
405 for (i, item) in items.iter().enumerate() {
406 print_value(item, depth + 1, "", label, i + 1 < n, max, out);
407 }
408 out.push(JsonLine { key: format!("{pad}]"), display: format!("{pad}]{c}"), array: None });
409 }
410 _ => line(serde_json::to_string(v).unwrap_or_default(), None, None),
411 }
412}
413
414fn merge_summaries(lines: &mut Vec<DiffLine>, a: &[JsonLine], b: &[JsonLine]) {
417 let array_of = |l: &DiffLine| match l.kind {
418 LineKind::Removed => l.old.and_then(|n| a[n - 1].array.clone()),
419 LineKind::Added => l.new.and_then(|n| b[n - 1].array.clone()),
420 _ => None,
421 };
422 let mut i = 0;
423 while i < lines.len() {
424 if lines[i].kind == LineKind::Context {
425 i += 1;
426 continue;
427 }
428 let end = (i..lines.len()).find(|&j| lines[j].kind == LineKind::Context).unwrap_or(lines.len());
429 let mut drop = Vec::new();
430 for r in i..end {
431 if lines[r].kind != LineKind::Removed {
432 continue;
433 }
434 let Some((name, old_len)) = array_of(&lines[r]) else { continue };
435 let found = (i..end).find(|&j| {
436 !drop.contains(&j)
437 && lines[j].kind == LineKind::Added
438 && array_of(&lines[j]).is_some_and(|(n, _)| n == name)
439 });
440 if let Some(j) = found {
441 let new_len = array_of(&lines[j]).map(|(_, n)| n).unwrap_or(0);
442 let pad: String = lines[r].text.chars().take_while(|c| *c == ' ').collect();
443 let text = if old_len == new_len {
444 format!("{pad}{name}: {} items, changed", group_digits(new_len))
445 } else {
446 format!("{pad}{name}: {} → {}", group_digits(old_len), group_digits(new_len))
447 };
448 lines[r] = DiffLine { kind: LineKind::Summary, old: lines[r].old, new: lines[j].new, text };
449 drop.push(j);
450 }
451 }
452 drop.sort_unstable();
453 for j in drop.iter().rev() {
454 lines.remove(*j);
455 }
456 i = end - drop.len();
457 }
458}
459
460pub fn group_digits(n: usize) -> String {
462 let s = n.to_string();
463 let mut out = String::with_capacity(s.len() + s.len() / 3);
464 for (i, ch) in s.chars().enumerate() {
465 if i > 0 && (s.len() - i) % 3 == 0 {
466 out.push(',');
467 }
468 out.push(ch);
469 }
470 out
471}
472
473#[cfg(test)]
474mod tests {
475 #[test]
476 fn change_marks_say_what_changed_on_which_lines() {
477 let old = "a\nb\nc\nd\ne\n";
478 let new = "a\nB\nc\nx\ny\nd\n";
479 assert_eq!(
480 super::line_changes(old, new),
481 vec![
482 ChangeMark { line: 2, lines: 1, change: LineChange::Modified },
483 ChangeMark { line: 4, lines: 2, change: LineChange::Added },
484 ChangeMark { line: 7, lines: 1, change: LineChange::Removed },
485 ]
486 );
487 assert!(super::line_changes(old, old).is_empty());
488 assert_eq!(
490 super::line_changes("a\nb\n", "a\nB\nc\n"),
491 vec![
492 ChangeMark { line: 2, lines: 1, change: LineChange::Modified },
493 ChangeMark { line: 3, lines: 1, change: LineChange::Added }
494 ]
495 );
496 }
497
498 use super::*;
499 use serde_json::json;
500
501 fn kinds(d: &Diff) -> String {
502 d.lines
503 .iter()
504 .map(|l| match l.kind {
505 LineKind::Context => ' ',
506 LineKind::Added => '+',
507 LineKind::Removed => '-',
508 LineKind::Summary => '~',
509 })
510 .collect()
511 }
512
513 #[test]
514 fn text_diff_numbers_lines_and_folds_context() {
515 let old: String = (1..=20).map(|i| format!("line {i}\n")).collect();
516 let new = old.replace("line 5\n", "line five\n").replace("line 18\n", "line 18\nline 18b\n");
517 let d = Diff::text(&old, &new, 2);
518 assert_eq!(d.added(), 2);
519 assert_eq!(d.removed(), 1);
520 assert_eq!(d.hunks.len(), 2, "two changes far apart: two hunks");
521 let h = &d.hunks[0];
522 assert_eq!(h.header(), "@@ -3,5 +3,5 @@");
523 let first: Vec<&DiffLine> = d.lines[h.lines.clone()].iter().collect();
524 assert_eq!(first[2].kind, LineKind::Removed);
525 assert_eq!((first[2].old, first[2].new), (Some(5), None));
526 assert_eq!(first[3].kind, LineKind::Added);
527 assert_eq!((first[3].old, first[3].new), (None, Some(5)));
528 assert_eq!(d.hunks[1].header(), "@@ -17,4 +17,5 @@");
529 let gaps = d.gaps();
531 assert_eq!(gaps.len(), 2);
532 assert_eq!(gaps[0], 0..2);
533 assert_eq!(gaps[1].len(), 9);
534 assert!(d.gaps().iter().flat_map(|g| d.lines[g.clone()].iter()).all(|l| l.kind == LineKind::Context));
535 }
536
537 #[test]
538 fn near_changes_share_a_hunk() {
539 let d = Diff::text("a\nb\nc\nd\ne\n", "a\nB\nc\nD\ne\n", 3);
540 assert_eq!(d.hunks.len(), 1);
541 assert_eq!(kinds(&d), " -+ -+ ");
542 assert!(Diff::text("same\n", "same\n", 3).is_empty());
543 }
544
545 #[test]
546 fn apply_takes_only_accepted_hunks() {
547 let old: String = (1..=20).map(|i| format!("l{i}\n")).collect();
548 let new = old.replace("l2\n", "two\n").replace("l19\n", "nineteen\n");
549 let d = Diff::text(&old, &new, 1);
550 assert_eq!(d.hunks.len(), 2);
551 assert_eq!(d.apply(&[true, true]).unwrap(), new);
552 assert_eq!(d.apply(&[false, false]).unwrap(), old);
553 assert_eq!(d.apply(&[false, true]).unwrap(), old.replace("l19\n", "nineteen\n"));
554 assert!(d.unified().starts_with("@@ -1,3 +1,3 @@\n l1\n-l2\n+two\n"), "{}", d.unified());
555 }
556
557 #[test]
558 fn json_ignores_key_order_and_trailing_commas() {
559 let old = r#"{"b": 1, "a": {"y": 2, "x": 1}}"#;
560 let new = r#"{"a": {"x": 1, "y": 2}, "b": 1}"#;
561 assert!(Diff::json(old, new, CONTEXT, ARRAY_SUMMARY).is_empty());
562 let d = Diff::json(r#"{"a": 1}"#, r#"{"a": 1, "b": 2}"#, CONTEXT, ARRAY_SUMMARY);
564 assert_eq!(kinds(&d), " + ");
565 assert_eq!(d.lines[1].text, r#" "a": 1,"#);
566 assert_eq!(d.lines[2].text, r#" "b": 2"#);
567 }
568
569 #[test]
570 fn json_long_arrays_are_one_summary_line() {
571 let old =
572 json!({"cells": (0..2539).collect::<Vec<_>>(), "image": "slide-01", "tiles": (0..40).collect::<Vec<_>>()});
573 let new =
574 json!({"tiles": (0..40).collect::<Vec<_>>(), "image": "slide-01", "cells": (0..2712).collect::<Vec<_>>()});
575 let d = Diff::json_values(&old, &new, CONTEXT, ARRAY_SUMMARY);
576 assert_eq!(d.lines.len(), 5, "{:#?}", d.lines);
577 assert_eq!(kinds(&d), " ~ ");
578 assert_eq!(d.lines[1].text, " cells: 2,539 → 2,712");
579 assert_eq!(d.lines[3].text, r#" "tiles": [40 items]"#);
580 let d = Diff::json_values(
582 &json!({"cells": (0..100).collect::<Vec<_>>()}),
583 &json!({"cells": (1..101).collect::<Vec<_>>()}),
584 CONTEXT,
585 ARRAY_SUMMARY,
586 );
587 assert_eq!(d.lines[1].text, " cells: 100 items, changed");
588 let d = Diff::json_values(&json!({"steps": [1, 2]}), &json!({"steps": [1, 3]}), CONTEXT, ARRAY_SUMMARY);
590 assert_eq!(kinds(&d), " -+ ");
591 }
592
593 #[test]
594 fn json_that_does_not_parse_falls_back_to_text() {
595 let d = Diff::json("{\"a\": 1}", "{oops", CONTEXT, ARRAY_SUMMARY);
596 assert!(!d.json);
597 assert!(d.note.as_deref().is_some_and(|n| n.starts_with("The new side is not JSON")));
598 assert_eq!(d.added(), 1);
599 }
600
601 #[test]
602 fn digits_are_grouped() {
603 assert_eq!(group_digits(0), "0");
604 assert_eq!(group_digits(999), "999");
605 assert_eq!(group_digits(2539), "2,539");
606 assert_eq!(group_digits(1234567), "1,234,567");
607 }
608}