1use crate::{
4 ChangeKind, FileChange,
5 definitions::{DiffItem, diff_items},
6};
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9use similar::TextDiff;
10use std::path::{Path, PathBuf};
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
14pub struct FileDiff {
15 pub path: PathBuf,
17 pub kind: ChangeKind,
19 pub added: usize,
21 pub removed: usize,
23 pub text: String,
25 pub items: Vec<DiffItem>,
28}
29
30#[must_use]
33pub fn render_diff(changes: &[FileChange], base: &Path) -> Vec<FileDiff> {
34 changes
35 .iter()
36 .map(|change| render_one(change, base))
37 .collect()
38}
39
40fn render_one(change: &FileChange, base: &Path) -> FileDiff {
41 let before = change.before.as_deref().unwrap_or_default();
42 let after = change.after.as_deref().unwrap_or_default();
43 let shown = change.path.strip_prefix(base).unwrap_or(&change.path);
44 let name = shown.display().to_string();
45 let name = name.trim_start_matches('/');
46 let old_header = match change.kind {
47 ChangeKind::Create => "/dev/null".to_string(),
48 _ => format!("a/{name}"),
49 };
50 let new_header = match change.kind {
51 ChangeKind::Delete => "/dev/null".to_string(),
52 _ => format!("b/{name}"),
53 };
54 let diff = TextDiff::from_lines(before, after);
55 let (added, removed) =
56 diff.iter_all_changes()
57 .fold((0, 0), |(add, del), line| match line.tag() {
58 similar::ChangeTag::Insert => (add + 1, del),
59 similar::ChangeTag::Delete => (add, del + 1),
60 similar::ChangeTag::Equal => (add, del),
61 });
62 let text = diff
63 .unified_diff()
64 .context_radius(3)
65 .header(&old_header, &new_header)
66 .to_string();
67 let items = diff_items(
68 &change.path,
69 change.before.as_deref(),
70 change.after.as_deref(),
71 );
72 FileDiff {
73 path: change.path.clone(),
74 kind: change.kind,
75 added,
76 removed,
77 text,
78 items,
79 }
80}