Skip to main content

griz_core/
diff.rs

1//! Renders planned changes as unified diffs.
2
3use 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/// The diff of one file.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
14pub struct FileDiff {
15    /// File path.
16    pub path: PathBuf,
17    /// What happens to it.
18    pub kind: ChangeKind,
19    /// Lines added.
20    pub added: usize,
21    /// Lines removed.
22    pub removed: usize,
23    /// Unified diff text with three lines of context.
24    pub text: String,
25    /// Named definitions this file's before and after disagree on, in an
26    /// enabled language.
27    pub items: Vec<DiffItem>,
28}
29
30/// Renders every change as a unified diff, naming files relative to `base`
31/// when they are inside it.
32#[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}