diffo 0.2.0

Semantic diffing for Rust structs via serde
Documentation
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::{Path, SequenceDiffAlgorithm};
use glob::Pattern;
use serde_value::Value;
use std::rc::Rc;

/// Type alias for custom comparator functions.
///
/// Returns `true` if values should be considered equal, `false` otherwise.
pub type Comparator = Rc<dyn Fn(&Value, &Value) -> bool>;

/// Configuration for diff computation.
///
/// # Examples
///
/// ```
/// use diffo::{DiffConfig, SequenceDiffAlgorithm};
///
/// let config = DiffConfig::new()
///     .mask("*.password")
///     .mask("api.secret")
///     .float_tolerance("metrics.*", 1e-6)
///     .collection_limit(500)
///     .sequence_algorithm("users", SequenceDiffAlgorithm::Patience)
///     .default_sequence_algorithm(SequenceDiffAlgorithm::IndexBased);
/// ```
#[derive(Clone)]
pub struct DiffConfig {
    /// Paths to completely ignore (won't appear in diff)
    ignore_paths: Vec<Pattern>,

    /// Paths to mask (show as "***" instead of actual values)
    mask_paths: Vec<Pattern>,

    /// Per-path float comparison tolerances
    float_tolerances: Vec<(Pattern, f64)>,

    /// Default float tolerance (if None, exact comparison)
    default_float_tolerance: Option<f64>,

    /// Maximum depth to traverse (prevents stack overflow)
    max_depth: Option<usize>,

    /// Maximum number of items to diff in a collection
    collection_limit: usize,

    /// Per-path sequence diff algorithms
    sequence_algorithms: Vec<(Pattern, SequenceDiffAlgorithm)>,

    /// Default sequence diff algorithm
    default_sequence_algorithm: SequenceDiffAlgorithm,

    /// Custom comparator functions per path
    comparators: Vec<(Pattern, Comparator)>,
}

impl DiffConfig {
    /// Create a new configuration with default settings.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::DiffConfig;
    ///
    /// let config = DiffConfig::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Ignore changes at matching paths.
    ///
    /// Supports glob patterns like `*.password` or `database.*.credentials`.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::DiffConfig;
    ///
    /// let config = DiffConfig::new()
    ///     .ignore("internal.*")
    ///     .ignore("*.temp");
    /// ```
    pub fn ignore(mut self, pattern: &str) -> Self {
        if let Ok(p) = Pattern::new(pattern) {
            self.ignore_paths.push(p);
        }
        self
    }

    /// Mask values at matching paths.
    ///
    /// Masked values will show as "***" in output instead of actual values.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::DiffConfig;
    ///
    /// let config = DiffConfig::new()
    ///     .mask("*.password")
    ///     .mask("api.secret");
    /// ```
    pub fn mask(mut self, pattern: &str) -> Self {
        if let Ok(p) = Pattern::new(pattern) {
            self.mask_paths.push(p);
        }
        self
    }

    /// Set float tolerance for specific paths.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::DiffConfig;
    ///
    /// let config = DiffConfig::new()
    ///     .float_tolerance("metrics.*.value", 1e-6);
    /// ```
    pub fn float_tolerance(mut self, pattern: &str, tolerance: f64) -> Self {
        if let Ok(p) = Pattern::new(pattern) {
            self.float_tolerances.push((p, tolerance));
        }
        self
    }

    /// Set default float tolerance for all floats.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::DiffConfig;
    ///
    /// let config = DiffConfig::new()
    ///     .default_float_tolerance(1e-9);
    /// ```
    pub fn default_float_tolerance(mut self, tolerance: f64) -> Self {
        self.default_float_tolerance = Some(tolerance);
        self
    }

    /// Set maximum traversal depth.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::DiffConfig;
    ///
    /// let config = DiffConfig::new()
    ///     .max_depth(32);
    /// ```
    pub fn max_depth(mut self, depth: usize) -> Self {
        self.max_depth = Some(depth);
        self
    }

    /// Set maximum collection size to diff.
    ///
    /// Collections larger than this limit will be elided.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::DiffConfig;
    ///
    /// let config = DiffConfig::new()
    ///     .collection_limit(500);
    /// ```
    pub fn collection_limit(mut self, limit: usize) -> Self {
        self.collection_limit = limit;
        self
    }

    /// Set sequence diff algorithm for specific paths.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::{DiffConfig, SequenceDiffAlgorithm};
    ///
    /// let config = DiffConfig::new()
    ///     .sequence_algorithm("users", SequenceDiffAlgorithm::Patience)
    ///     .sequence_algorithm("logs.*", SequenceDiffAlgorithm::Myers);
    /// ```
    pub fn sequence_algorithm(mut self, pattern: &str, algorithm: SequenceDiffAlgorithm) -> Self {
        if let Ok(p) = Pattern::new(pattern) {
            self.sequence_algorithms.push((p, algorithm));
        }
        self
    }

    /// Set default sequence diff algorithm.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::{DiffConfig, SequenceDiffAlgorithm};
    ///
    /// let config = DiffConfig::new()
    ///     .default_sequence_algorithm(SequenceDiffAlgorithm::Myers);
    /// ```
    pub fn default_sequence_algorithm(mut self, algorithm: SequenceDiffAlgorithm) -> Self {
        self.default_sequence_algorithm = algorithm;
        self
    }

    /// Check if a path should be ignored.
    pub(crate) fn should_ignore(&self, path: &Path) -> bool {
        let path_str = path.as_str();
        self.ignore_paths.iter().any(|p| p.matches(path_str))
    }

    /// Check if a path should be masked.
    #[allow(dead_code)] // Will be used in formatters in next phase
    pub(crate) fn should_mask(&self, path: &Path) -> bool {
        let path_str = path.as_str();
        self.mask_paths.iter().any(|p| p.matches(path_str))
    }

    /// Get float tolerance for a specific path.
    pub(crate) fn float_tolerance_for(&self, path: &Path) -> Option<f64> {
        let path_str = path.as_str();

        // Check for path-specific tolerance
        for (pattern, tolerance) in &self.float_tolerances {
            if pattern.matches(path_str) {
                return Some(*tolerance);
            }
        }

        // Fall back to default tolerance
        self.default_float_tolerance
    }

    /// Check if the path exceeds the maximum depth.
    pub(crate) fn exceeds_depth(&self, path: &Path) -> bool {
        if let Some(max) = self.max_depth {
            path.depth() > max
        } else {
            false
        }
    }

    /// Get the collection limit.
    pub(crate) fn get_collection_limit(&self) -> usize {
        self.collection_limit
    }

    /// Get sequence diff algorithm for a specific path.
    pub(crate) fn get_sequence_algorithm(&self, path: &Path) -> SequenceDiffAlgorithm {
        let path_str = path.as_str();

        // Check for path-specific algorithm
        for (pattern, algorithm) in &self.sequence_algorithms {
            if pattern.matches(path_str) {
                return *algorithm;
            }
        }

        // Fall back to default
        self.default_sequence_algorithm
    }

    /// Add a custom comparator for a specific path pattern.
    ///
    /// When comparing values at paths matching the pattern, the comparator
    /// will be called first. If it returns `true`, values are considered equal
    /// and no diff is recorded. If it returns `false`, normal diffing proceeds.
    ///
    /// Uses glob patterns for matching. Note: Array indices like `[0]`, `[1]`
    /// require workaround patterns (e.g., `?0?`, `?1?`) due to glob syntax
    /// treating `[]` as character classes.
    ///
    /// # Examples
    ///
    /// ```
    /// use diffo::{DiffConfig, ValueExt};
    /// use std::rc::Rc;
    ///
    /// let config = DiffConfig::new()
    ///     // Field-level comparison
    ///     .comparator("url", Rc::new(|old, new| {
    ///         if let (Some(a), Some(b)) = (old.as_string(), new.as_string()) {
    ///             a.to_lowercase() == b.to_lowercase()
    ///         } else {
    ///             old == new
    ///         }
    ///     }))
    ///     // Array element (workaround pattern)
    ///     .comparator("?0?", Rc::new(|old, new| {
    ///         old.get_field("id") == new.get_field("id")
    ///     }));
    /// ```
    pub fn comparator(mut self, pattern: &str, comparator: Comparator) -> Self {
        if let Ok(p) = Pattern::new(pattern) {
            self.comparators.push((p, comparator));
        }
        self
    }

    /// Get custom comparator for a specific path.
    pub(crate) fn get_comparator(&self, path: &Path) -> Option<&Comparator> {
        let path_str = path.as_str();

        // Check for path-specific comparator
        for (pattern, comparator) in &self.comparators {
            if pattern.matches(path_str) {
                return Some(comparator);
            }
        }

        None
    }
}

impl std::fmt::Debug for DiffConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DiffConfig")
            .field("ignore_paths", &self.ignore_paths.len())
            .field("mask_paths", &self.mask_paths.len())
            .field("float_tolerances", &self.float_tolerances.len())
            .field("default_float_tolerance", &self.default_float_tolerance)
            .field("max_depth", &self.max_depth)
            .field("collection_limit", &self.collection_limit)
            .field("sequence_algorithms", &self.sequence_algorithms.len())
            .field(
                "default_sequence_algorithm",
                &self.default_sequence_algorithm,
            )
            .field("comparators", &self.comparators.len())
            .finish()
    }
}

impl Default for DiffConfig {
    fn default() -> Self {
        Self {
            ignore_paths: vec![],
            mask_paths: vec![],
            float_tolerances: vec![],
            default_float_tolerance: None,
            max_depth: Some(64),
            collection_limit: 1000,
            sequence_algorithms: vec![],
            default_sequence_algorithm: SequenceDiffAlgorithm::IndexBased,
            comparators: vec![],
        }
    }
}

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

    #[test]
    fn test_default_config() {
        let config = DiffConfig::default();
        assert_eq!(config.max_depth, Some(64));
        assert_eq!(config.collection_limit, 1000);
    }

    #[test]
    fn test_ignore() {
        let config = DiffConfig::new().ignore("*.temp");
        let path = Path::root().field("foo").field("temp");
        assert!(config.should_ignore(&path));
    }

    #[test]
    fn test_mask() {
        let config = DiffConfig::new().mask("*.password");
        let path = Path::root().field("user").field("password");
        assert!(config.should_mask(&path));
    }

    #[test]
    fn test_float_tolerance() {
        let config = DiffConfig::new()
            .float_tolerance("metrics.*", 1e-6)
            .default_float_tolerance(1e-9);

        let metrics_path = Path::root().field("metrics").field("value");
        assert_eq!(config.float_tolerance_for(&metrics_path), Some(1e-6));

        let other_path = Path::root().field("other");
        assert_eq!(config.float_tolerance_for(&other_path), Some(1e-9));
    }

    #[test]
    fn test_max_depth() {
        let config = DiffConfig::new().max_depth(2);

        let shallow = Path::root().field("a");
        assert!(!config.exceeds_depth(&shallow));

        let deep = Path::root().field("a").field("b").field("c");
        assert!(config.exceeds_depth(&deep));
    }

    #[test]
    fn test_collection_limit() {
        let config = DiffConfig::new().collection_limit(100);
        assert_eq!(config.get_collection_limit(), 100);
    }

    #[test]
    fn test_builder_pattern() {
        let config = DiffConfig::new()
            .mask("*.secret")
            .ignore("*.internal")
            .float_tolerance("*.value", 0.001)
            .max_depth(32)
            .collection_limit(500);

        assert_eq!(config.max_depth, Some(32));
        assert_eq!(config.collection_limit, 500);
    }
}