1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use crate::report::{DiffDetail, Difference};
use crate::Error;
use itertools::Itertools;
use regex::Regex;
use schemars_derive::JsonSchema;
use serde::{Deserialize, Serialize};
use std::path::Path;
use tracing::error;

#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone)]
/// configuration for the json compare module
pub struct JsonConfig {
    #[serde(default)]
    ignore_keys: Vec<String>,
}
impl JsonConfig {
    pub(crate) fn get_ignore_list(&self) -> Result<Vec<Regex>, regex::Error> {
        self.ignore_keys.iter().map(|v| Regex::new(v)).collect()
    }
}

pub(crate) fn compare_files<P: AsRef<Path>>(
    nominal: P,
    actual: P,
    config: &JsonConfig,
) -> Result<Difference, Error> {
    let mut diff = Difference::new_for_file(&nominal, &actual);
    let compared_file_name = nominal.as_ref().to_string_lossy().into_owned();

    let nominal = vg_errortools::fat_io_wrap_std(&nominal, &std::fs::read_to_string)?;
    let actual = vg_errortools::fat_io_wrap_std(&actual, &std::fs::read_to_string)?;
    let ignores = config.get_ignore_list()?;

    let json_diff = json_diff::process::compare_jsons(&nominal, &actual);
    let json_diff = match json_diff {
        Ok(diff) => diff,
        Err(e) => {
            let error_message =
                format!("JSON deserialization failed for {compared_file_name} (error: {e})");
            error!("{}", error_message);
            diff.push_detail(DiffDetail::Error(error_message));
            diff.error();
            return Ok(diff);
        }
    };
    let filtered_diff: Vec<_> = json_diff
        .all_diffs()
        .into_iter()
        .filter(|(_d, v)| !ignores.iter().any(|excl| excl.is_match(v.get_key())))
        .collect();

    if !filtered_diff.is_empty() {
        for (d_type, key) in filtered_diff.iter() {
            error!("{d_type}: {key}");
        }
        let left = filtered_diff
            .iter()
            .filter_map(|(k, v)| {
                if matches!(k, json_diff::enums::DiffType::LeftExtra) {
                    Some(v.to_string())
                } else {
                    None
                }
            })
            .join("\n");
        let right = filtered_diff
            .iter()
            .filter_map(|(k, v)| {
                if matches!(k, json_diff::enums::DiffType::RightExtra) {
                    Some(v.to_string())
                } else {
                    None
                }
            })
            .join("\n");
        let differences = filtered_diff
            .iter()
            .filter_map(|(k, v)| {
                if matches!(k, json_diff::enums::DiffType::Mismatch) {
                    Some(v.to_string())
                } else {
                    None
                }
            })
            .join("\n");
        let root_mismatch = filtered_diff
            .iter()
            .find(|(k, _v)| matches!(k, json_diff::enums::DiffType::RootMismatch))
            .map(|(_, v)| v.to_string());

        diff.push_detail(DiffDetail::Json {
            differences,
            left,
            right,
            root_mismatch,
        });

        diff.error();
    }

    Ok(diff)
}

#[cfg(test)]
mod test {
    use super::*;

    fn trim_split(list: &str) -> Vec<&str> {
        list.split('\n').map(|e| e.trim()).collect()
    }

    #[test]
    fn no_filter() {
        let cfg = JsonConfig {
            ignore_keys: vec![],
        };
        let result = compare_files(
            "tests/integ/data/json/expected/guy.json",
            "tests/integ/data/json/actual/guy.json",
            &cfg,
        )
        .unwrap();
        if let DiffDetail::Json {
            differences,
            left,
            right,
            root_mismatch,
        } = result.detail.first().unwrap()
        {
            let differences = trim_split(differences);
            assert!(differences.contains(&"car -> { \"RX7\" != \"Panda Trueno\" }"));
            assert!(differences.contains(&"age -> { 21 != 18 }"));
            assert!(differences.contains(&"name -> { \"Keisuke\" != \"Takumi\" }"));
            assert_eq!(differences.len(), 3);

            assert_eq!(left.as_str(), " brothers");
            assert!(right.is_empty());
            assert!(root_mismatch.is_none());
        } else {
            panic!("wrong diffdetail");
        }
    }

    #[test]
    fn filter_works() {
        let cfg = JsonConfig {
            ignore_keys: vec!["name".to_string(), "brother(s?)".to_string()],
        };
        let result = compare_files(
            "tests/integ/data/json/expected/guy.json",
            "tests/integ/data/json/actual/guy.json",
            &cfg,
        )
        .unwrap();
        if let DiffDetail::Json {
            differences,
            left,
            right,
            root_mismatch,
        } = result.detail.first().unwrap()
        {
            let differences = trim_split(differences);
            assert!(differences.contains(&"car -> { \"RX7\" != \"Panda Trueno\" }"));
            assert!(differences.contains(&"age -> { 21 != 18 }"));
            assert_eq!(differences.len(), 2);
            assert!(right.is_empty());
            assert!(left.is_empty());
            assert!(root_mismatch.is_none());
        } else {
            panic!("wrong diffdetail");
        }
    }
}