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 utf8-forge JSON reports that carry a `files[]` array and compares
18//! per path: `added`, `removed`, and `changed` (action or byte-count drift).
19//! A report without a `files` array is not a report and fails to parse, so a
20//! mistyped input path can never masquerade as an empty baseline. Paths are
21//! compared relative to each report's `root` (the root prefix is stripped,
22//! separators normalized to `/`), so the same tree scanned under two
23//! different roots diffs clean; a differing `root` field triggers a warning,
24//! not an error. Unknown JSON fields are ignored (lenient deserialization).
25
26use std::collections::HashMap;
27
28use serde::{Deserialize, Serialize};
29
30/// Lenient view of one report row (also serialized into the diff output).
31#[derive(Debug, Clone, Deserialize, Serialize)]
32pub struct DiffInputFile {
33    pub path: String,
34    #[serde(default)]
35    pub action: Option<String>,
36    #[serde(default)]
37    pub bytes_before: Option<u64>,
38    #[serde(default)]
39    pub bytes_after: Option<u64>,
40}
41
42/// Lenient view of a whole report. `files` is required: any JSON object
43/// without it (or a bare JSON array) is rejected as not-a-report.
44#[derive(Debug, Deserialize)]
45pub struct DiffInput {
46    #[serde(default)]
47    pub mode: Option<String>,
48    #[serde(default)]
49    pub root: Option<String>,
50    pub files: Vec<DiffInputFile>,
51}
52
53/// Counts for the diff summary.
54#[derive(Debug, Serialize)]
55pub struct DiffSummary {
56    pub added: u64,
57    pub removed: u64,
58    /// Common paths whose action or byte counts differ between the reports.
59    pub action_changed: u64,
60    pub unchanged: u64,
61}
62
63/// One common path whose record drifted.
64#[derive(Debug, Serialize)]
65pub struct ChangedEntry {
66    pub path: String,
67    pub before: DiffInputFile,
68    pub after: DiffInputFile,
69}
70
71/// The `diff` output document (a new document type, not the run report).
72#[derive(Debug, Serialize)]
73pub struct DiffReport {
74    pub tool: &'static str,
75    pub version: &'static str,
76    pub mode: &'static str,
77    pub before: String,
78    pub after: String,
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub before_root: Option<String>,
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub after_root: Option<String>,
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub before_mode: Option<String>,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub after_mode: Option<String>,
87    pub summary: DiffSummary,
88    pub added: Vec<DiffInputFile>,
89    pub removed: Vec<DiffInputFile>,
90    pub changed: Vec<ChangedEntry>,
91}
92
93/// Rewrite each record path relative to the report's `root`: separators are
94/// normalized to `/` and the root prefix (always with its trailing separator)
95/// is stripped. Records whose path does not start with the root are kept
96/// verbatim. Paths in the diff output are therefore root-relative and stable
97/// across root spellings, which is what makes two scans of the same tree
98/// under different roots comparable.
99pub fn relativize_files(files: Vec<DiffInputFile>, root: Option<&str>) -> Vec<DiffInputFile> {
100    let Some(root) = root else {
101        return files;
102    };
103    let root_norm = root.replace('\\', "/");
104    let prefix = if root_norm == "." {
105        "./".to_string()
106    } else if root_norm.ends_with('/') {
107        root_norm
108    } else {
109        format!("{root_norm}/")
110    };
111    files
112        .into_iter()
113        .map(|mut f| {
114            f.path = f.path.replace('\\', "/");
115            if let Some(stripped) = f.path.strip_prefix(&prefix) {
116                f.path = stripped.to_string();
117            }
118            f
119        })
120        .collect()
121}
122
123/// Compare two parsed reports. Duplicate paths within one report resolve to
124/// the last occurrence (the tool never produces duplicates; sorted unique by
125/// construction). Arrays are sorted by path.
126pub fn compare(before: &DiffInput, after: &DiffInput) -> DiffReport {
127    let index_before: HashMap<&str, &DiffInputFile> =
128        before.files.iter().map(|f| (f.path.as_str(), f)).collect();
129    let index_after: HashMap<&str, &DiffInputFile> =
130        after.files.iter().map(|f| (f.path.as_str(), f)).collect();
131
132    let mut added: Vec<DiffInputFile> = Vec::new();
133    let mut removed: Vec<DiffInputFile> = Vec::new();
134    let mut changed: Vec<ChangedEntry> = Vec::new();
135    let mut unchanged: u64 = 0;
136
137    for (path, after_file) in &index_after {
138        match index_before.get(path) {
139            None => added.push((*after_file).clone()),
140            Some(before_file) => {
141                if before_file.action != after_file.action
142                    || before_file.bytes_before != after_file.bytes_before
143                    || before_file.bytes_after != after_file.bytes_after
144                {
145                    changed.push(ChangedEntry {
146                        path: (*path).to_string(),
147                        before: (*before_file).clone(),
148                        after: (*after_file).clone(),
149                    });
150                } else {
151                    unchanged += 1;
152                }
153            }
154        }
155    }
156    for (path, before_file) in &index_before {
157        if !index_after.contains_key(path) {
158            removed.push((*before_file).clone());
159        }
160    }
161
162    let sort_by_path = |files: &mut [DiffInputFile]| files.sort_by(|a, b| a.path.cmp(&b.path));
163    sort_by_path(&mut added);
164    sort_by_path(&mut removed);
165    changed.sort_by(|a, b| a.path.cmp(&b.path));
166
167    let summary = DiffSummary {
168        added: added.len() as u64,
169        removed: removed.len() as u64,
170        action_changed: changed.len() as u64,
171        unchanged,
172    };
173    DiffReport {
174        tool: "utf8-forge",
175        version: env!("CARGO_PKG_VERSION"),
176        mode: "diff",
177        before: String::new(),
178        after: String::new(),
179        before_root: before.root.clone(),
180        after_root: after.root.clone(),
181        before_mode: before.mode.clone(),
182        after_mode: after.mode.clone(),
183        summary,
184        added,
185        removed,
186        changed,
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    fn report(files: &[(&str, &str)]) -> DiffInput {
195        DiffInput {
196            mode: Some("convert".into()),
197            root: Some("/tmp/tree".into()),
198            files: files
199                .iter()
200                .map(|(p, a)| DiffInputFile {
201                    path: (*p).to_string(),
202                    action: Some((*a).to_string()),
203                    bytes_before: Some(10),
204                    bytes_after: Some(12),
205                })
206                .collect(),
207        }
208    }
209
210    #[test]
211    fn partitions_added_removed_changed_unchanged() {
212        let before = report(&[("x.cpp", "converted"), ("y.cpp", "unchanged")]);
213        let after = report(&[("y.cpp", "unchanged"), ("z.cpp", "converted")]);
214        let doc = compare(&before, &after);
215        assert_eq!(doc.summary.added, 1);
216        assert_eq!(doc.summary.removed, 1);
217        assert_eq!(doc.summary.action_changed, 0);
218        assert_eq!(doc.summary.unchanged, 1);
219        assert_eq!(doc.removed[0].path, "x.cpp");
220        assert_eq!(doc.added[0].path, "z.cpp");
221    }
222
223    #[test]
224    fn byte_count_drift_counts_as_changed() {
225        let mut before = report(&[("a.cpp", "converted")]);
226        before.files[0].bytes_after = Some(100);
227        let after = report(&[("a.cpp", "converted")]);
228        let doc = compare(&before, &after);
229        assert_eq!(doc.summary.action_changed, 1);
230    }
231
232    #[test]
233    fn identical_reports_are_all_unchanged() {
234        let before = report(&[("a.cpp", "converted")]);
235        let after = report(&[("a.cpp", "converted")]);
236        let doc = compare(&before, &after);
237        assert_eq!(doc.summary.action_changed, 0);
238        assert_eq!(doc.summary.unchanged, 1);
239    }
240
241    #[test]
242    fn same_file_twice_resolves_to_last_occurrence() {
243        // The first occurrence says "converted"; the last says "unchanged".
244        // Last-match-wins must resolve the record to "unchanged" and match
245        // the after side exactly.
246        let before = DiffInput {
247            mode: None,
248            root: None,
249            files: vec![
250                DiffInputFile {
251                    path: "a".into(),
252                    action: Some("converted".into()),
253                    bytes_before: Some(10),
254                    bytes_after: Some(99),
255                },
256                DiffInputFile {
257                    path: "a".into(),
258                    action: Some("unchanged".into()),
259                    bytes_before: Some(10),
260                    bytes_after: Some(12),
261                },
262            ],
263        };
264        let after = report(&[("a", "unchanged")]);
265        let doc = compare(&before, &after);
266        assert_eq!(doc.summary.unchanged, 1);
267        assert_eq!(doc.summary.action_changed, 0);
268    }
269
270    #[test]
271    fn missing_optional_fields_are_tolerated() {
272        let raw = r#"{"files": [{"path": "a.cpp"}]}"#;
273        let input: DiffInput = serde_json::from_str(raw).unwrap();
274        assert_eq!(input.files[0].path, "a.cpp");
275        assert!(input.files[0].action.is_none());
276    }
277
278    #[test]
279    fn json_without_files_array_is_rejected() {
280        // Anything that is not a utf8-forge report must fail loudly instead
281        // of behaving like an empty baseline.
282        assert!(serde_json::from_str::<DiffInput>(r#"{"schema": "wrong"}"#).is_err());
283        assert!(serde_json::from_str::<DiffInput>("[]").is_err());
284        assert!(serde_json::from_str::<DiffInput>(r#"{"files": "nope"}"#).is_err());
285    }
286
287    #[test]
288    fn root_prefix_is_stripped_from_record_paths() {
289        let files: Vec<DiffInputFile> = vec![
290            file("tree/a.cpp"),
291            file("./b.h"),
292            file("outside/c.txt"),
293            file(r"tree\sub\d.rs"),
294        ];
295        let rel = relativize_files(files, Some("tree"));
296        let paths: Vec<&str> = rel.iter().map(|f| f.path.as_str()).collect();
297        assert_eq!(paths, vec!["a.cpp", "./b.h", "outside/c.txt", "sub/d.rs"]);
298    }
299
300    #[test]
301    fn dot_root_strips_leading_dot_slash() {
302        let rel = relativize_files(vec![file("./a.cpp")], Some("."));
303        assert_eq!(rel[0].path, "a.cpp");
304    }
305
306    #[test]
307    fn missing_root_keeps_paths_untouched() {
308        let rel = relativize_files(vec![file("tree/a.cpp")], None);
309        assert_eq!(rel[0].path, "tree/a.cpp");
310    }
311
312    fn file(path: &str) -> DiffInputFile {
313        DiffInputFile {
314            path: path.to_string(),
315            action: Some("unchanged".into()),
316            bytes_before: Some(1),
317            bytes_after: Some(1),
318        }
319    }
320}