Skip to main content

utf8_forge/
differ.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Report-to-report comparison for the `diff` subcommand.
16//!
17//! Reads any utf8-forge JSON report that carries a `files[]` array and
18//! compares per path: `added`, `removed`, and `changed` (action or byte-count
19//! drift). Paths are compared as exact strings — both reports must come from
20//! the same `--root` and the same platform's path spelling; a differing
21//! `root` field triggers a warning, not an error. Input reports are data, not
22//! configuration, so unknown JSON fields are ignored (lenient
23//! deserialization).
24
25use std::collections::HashMap;
26
27use serde::{Deserialize, Serialize};
28
29/// Lenient view of one report row (also serialized into the diff output).
30#[derive(Debug, Clone, Deserialize, Serialize)]
31pub struct DiffInputFile {
32    pub path: String,
33    #[serde(default)]
34    pub action: Option<String>,
35    #[serde(default)]
36    pub bytes_before: Option<u64>,
37    #[serde(default)]
38    pub bytes_after: Option<u64>,
39}
40
41/// Lenient view of a whole report.
42#[derive(Debug, Deserialize)]
43pub struct DiffInput {
44    #[serde(default)]
45    pub mode: Option<String>,
46    #[serde(default)]
47    pub root: Option<String>,
48    #[serde(default)]
49    pub files: Vec<DiffInputFile>,
50}
51
52/// Counts for the diff summary.
53#[derive(Debug, Serialize)]
54pub struct DiffSummary {
55    pub added: u64,
56    pub removed: u64,
57    /// Common paths whose action or byte counts differ between the reports.
58    pub action_changed: u64,
59    pub unchanged: u64,
60}
61
62/// One common path whose record drifted.
63#[derive(Debug, Serialize)]
64pub struct ChangedEntry {
65    pub path: String,
66    pub before: DiffInputFile,
67    pub after: DiffInputFile,
68}
69
70/// The `diff` output document (a new document type, not the run report).
71#[derive(Debug, Serialize)]
72pub struct DiffReport {
73    pub tool: &'static str,
74    pub version: &'static str,
75    pub mode: &'static str,
76    pub before: String,
77    pub after: String,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub before_mode: Option<String>,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub after_mode: Option<String>,
82    pub summary: DiffSummary,
83    pub added: Vec<DiffInputFile>,
84    pub removed: Vec<DiffInputFile>,
85    pub changed: Vec<ChangedEntry>,
86}
87
88/// Compare two parsed reports. Duplicate paths within one report resolve to
89/// the last occurrence (the tool never produces duplicates; sorted unique by
90/// construction). Arrays are sorted by path.
91pub fn compare(before: &DiffInput, after: &DiffInput) -> DiffReport {
92    let index_before: HashMap<&str, &DiffInputFile> =
93        before.files.iter().map(|f| (f.path.as_str(), f)).collect();
94    let index_after: HashMap<&str, &DiffInputFile> =
95        after.files.iter().map(|f| (f.path.as_str(), f)).collect();
96
97    let mut added: Vec<DiffInputFile> = Vec::new();
98    let mut removed: Vec<DiffInputFile> = Vec::new();
99    let mut changed: Vec<ChangedEntry> = Vec::new();
100    let mut unchanged: u64 = 0;
101
102    for (path, after_file) in &index_after {
103        match index_before.get(path) {
104            None => added.push((*after_file).clone()),
105            Some(before_file) => {
106                if before_file.action != after_file.action
107                    || before_file.bytes_before != after_file.bytes_before
108                    || before_file.bytes_after != after_file.bytes_after
109                {
110                    changed.push(ChangedEntry {
111                        path: (*path).to_string(),
112                        before: (*before_file).clone(),
113                        after: (*after_file).clone(),
114                    });
115                } else {
116                    unchanged += 1;
117                }
118            }
119        }
120    }
121    for (path, before_file) in &index_before {
122        if !index_after.contains_key(path) {
123            removed.push((*before_file).clone());
124        }
125    }
126
127    let sort_by_path = |files: &mut [DiffInputFile]| files.sort_by(|a, b| a.path.cmp(&b.path));
128    sort_by_path(&mut added);
129    sort_by_path(&mut removed);
130    changed.sort_by(|a, b| a.path.cmp(&b.path));
131
132    let summary = DiffSummary {
133        added: added.len() as u64,
134        removed: removed.len() as u64,
135        action_changed: changed.len() as u64,
136        unchanged,
137    };
138    DiffReport {
139        tool: "utf8-forge",
140        version: env!("CARGO_PKG_VERSION"),
141        mode: "diff",
142        before: String::new(),
143        after: String::new(),
144        before_mode: before.mode.clone(),
145        after_mode: after.mode.clone(),
146        summary,
147        added,
148        removed,
149        changed,
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    fn report(files: &[(&str, &str)]) -> DiffInput {
158        DiffInput {
159            mode: Some("convert".into()),
160            root: Some("/tmp/tree".into()),
161            files: files
162                .iter()
163                .map(|(p, a)| DiffInputFile {
164                    path: (*p).to_string(),
165                    action: Some((*a).to_string()),
166                    bytes_before: Some(10),
167                    bytes_after: Some(12),
168                })
169                .collect(),
170        }
171    }
172
173    #[test]
174    fn partitions_added_removed_changed_unchanged() {
175        let before = report(&[("x.cpp", "converted"), ("y.cpp", "unchanged")]);
176        let after = report(&[("y.cpp", "unchanged"), ("z.cpp", "converted")]);
177        let doc = compare(&before, &after);
178        assert_eq!(doc.summary.added, 1);
179        assert_eq!(doc.summary.removed, 1);
180        assert_eq!(doc.summary.action_changed, 0);
181        assert_eq!(doc.summary.unchanged, 1);
182        assert_eq!(doc.removed[0].path, "x.cpp");
183        assert_eq!(doc.added[0].path, "z.cpp");
184    }
185
186    #[test]
187    fn byte_count_drift_counts_as_changed() {
188        let mut before = report(&[("a.cpp", "converted")]);
189        before.files[0].bytes_after = Some(100);
190        let after = report(&[("a.cpp", "converted")]);
191        let doc = compare(&before, &after);
192        assert_eq!(doc.summary.action_changed, 1);
193    }
194
195    #[test]
196    fn identical_reports_are_all_unchanged() {
197        let before = report(&[("a.cpp", "converted")]);
198        let after = report(&[("a.cpp", "converted")]);
199        let doc = compare(&before, &after);
200        assert_eq!(doc.summary.action_changed, 0);
201        assert_eq!(doc.summary.unchanged, 1);
202    }
203
204    #[test]
205    fn same_file_twice_resolves_to_last_occurrence() {
206        // The first occurrence says "converted"; the last says "unchanged".
207        // Last-match-wins must resolve the record to "unchanged" and match
208        // the after side exactly.
209        let before = DiffInput {
210            mode: None,
211            root: None,
212            files: vec![
213                DiffInputFile {
214                    path: "a".into(),
215                    action: Some("converted".into()),
216                    bytes_before: Some(10),
217                    bytes_after: Some(99),
218                },
219                DiffInputFile {
220                    path: "a".into(),
221                    action: Some("unchanged".into()),
222                    bytes_before: Some(10),
223                    bytes_after: Some(12),
224                },
225            ],
226        };
227        let after = report(&[("a", "unchanged")]);
228        let doc = compare(&before, &after);
229        assert_eq!(doc.summary.unchanged, 1);
230        assert_eq!(doc.summary.action_changed, 0);
231    }
232
233    #[test]
234    fn missing_optional_fields_are_tolerated() {
235        let raw = r#"{"files": [{"path": "a.cpp"}]}"#;
236        let input: DiffInput = serde_json::from_str(raw).unwrap();
237        assert_eq!(input.files[0].path, "a.cpp");
238        assert!(input.files[0].action.is_none());
239    }
240}