cool-diff 0.1.0

Compact, context-preserving diffs of structured data (serde_json::Value)
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
use serde_json::Value;

use crate::model::{ChildKind, DiffKind, DiffNode, DiffTree, PathSegment};
use crate::render::{DiffRenderer, indicator};

/// Controls whether the renderer emits ANSI colour codes.
#[cfg(feature = "color")]
#[derive(Debug, Clone, Copy, Default)]
pub enum ColorMode {
    /// Automatically detect terminal support.
    ///
    /// Uses `supports-color` to check if stdout supports ANSI colours.
    #[default]
    Auto,

    /// Always emit ANSI colour codes.
    Always,

    /// Never emit ANSI colour codes.
    Never,
}

/// Renders a `DiffTree` as YAML-like diff output.
///
/// Output uses unified diff conventions:
/// - ` ` prefix for context lines (unchanged values, comments, structural markers)
/// - `-` prefix for expected (what we wanted but didn't get)
/// - `+` prefix for actual (what we got instead)
pub struct YamlRenderer {
    /// Maximum lines to render per side for large values.
    ///
    /// `None` means no truncation.
    max_lines_per_side: Option<u32>,

    /// Number of spaces per indentation level.
    indent_width: u16,

    /// Controls ANSI colour output.
    #[cfg(feature = "color")]
    color_mode: ColorMode,
}

impl YamlRenderer {
    /// Default maximum lines to render per side.
    pub const DEFAULT_MAX_LINES_PER_SIDE: u32 = 20;

    /// Default number of spaces per indentation level.
    pub const DEFAULT_INDENT_WIDTH: u16 = 2;

    /// Creates a new renderer with default settings.
    pub fn new() -> Self {
        Self {
            max_lines_per_side: Some(Self::DEFAULT_MAX_LINES_PER_SIDE),
            indent_width: Self::DEFAULT_INDENT_WIDTH,
            #[cfg(feature = "color")]
            color_mode: ColorMode::default(),
        }
    }

    /// Sets the maximum lines to render per side.
    pub fn with_max_lines_per_side(mut self, max: Option<u32>) -> Self {
        self.max_lines_per_side = max;
        self
    }

    /// Sets the number of spaces per indentation level.
    pub fn with_indent_width(mut self, width: u16) -> Self {
        self.indent_width = width;
        self
    }

    /// Sets the colour mode for ANSI output.
    #[cfg(feature = "color")]
    pub fn with_color_mode(mut self, mode: ColorMode) -> Self {
        self.color_mode = mode;
        self
    }

    /// Renders a single diff node at the given indentation depth.
    fn render_node(&self, node: &DiffNode, indent: u16, output: &mut String) {
        match node {
            DiffNode::Container {
                segment,
                child_kind,
                omitted_count,
                children,
            } => {
                // Render the segment as a context line.
                // Key segments need a trailing colon (e.g. `spec:`), but
                // array segments already include their content (e.g. `- name: FOO`).
                // Index segments include the index as a comment (e.g. `- # index 0`).
                let label = format_segment_label(segment);
                let suffix = if matches!(segment, PathSegment::Key(_)) {
                    ":"
                } else {
                    ""
                };
                push_line(
                    output,
                    indicator::CONTEXT,
                    indent,
                    &format!("{label}{suffix}"),
                );

                let child_indent = indent + self.indent_width;

                if *omitted_count > 0 {
                    let unit = omitted_unit(child_kind, *omitted_count);
                    push_line(
                        output,
                        indicator::CONTEXT,
                        child_indent,
                        &format!("# {omitted_count} {unit} omitted"),
                    );
                }

                for child in children {
                    render_child(self, child, indent, output);
                }
            }

            DiffNode::Leaf { segment, kind } => {
                render_leaf(self, segment, kind, indent, output);
            }
        }
    }
}

impl Default for YamlRenderer {
    fn default() -> Self {
        Self::new()
    }
}

impl DiffRenderer for YamlRenderer {
    fn render(&self, tree: &DiffTree) -> String {
        let mut output = String::new();
        for node in &tree.roots {
            // Root nodes start at indent level 0 (no leading spaces)
            self.render_node(node, 0, &mut output);
        }

        #[cfg(feature = "color")]
        if self.should_colorize() {
            return self.colorize(&output);
        }

        output
    }
}

#[cfg(feature = "color")]
impl YamlRenderer {
    /// Returns true if output should be colorized based on the colour mode.
    fn should_colorize(&self) -> bool {
        match self.color_mode {
            ColorMode::Always => true,
            ColorMode::Never => false,
            ColorMode::Auto => {
                supports_color::on(supports_color::Stream::Stdout)
                    .is_some_and(|level| level.has_basic)
            }
        }
    }

    /// Colorizes each line of the plain output based on its prefix character.
    fn colorize(&self, plain: &str) -> String {
        use owo_colors::OwoColorize;

        let mut output = String::with_capacity(plain.len());
        for line in plain.lines() {
            let first = line.chars().next();
            let colored = match first {
                Some(indicator::EXPECTED) => {
                    format!("{colored_text}", colored_text = line.red())
                }
                Some(indicator::ACTUAL) => {
                    format!("{colored_text}", colored_text = line.green())
                }
                _ if line.trim_start().starts_with('#') => {
                    format!("{colored_text}", colored_text = line.bright_black())
                }
                _ => line.to_owned(),
            };
            output.push_str(&colored);
            output.push('\n');
        }
        output
    }
}

/// Renders a child node, increasing indent by the configured width.
///
/// Array element segments (NamedElement, Index, Unmatched) get special
/// handling: the `- ` prefix is rendered on the context line, and children
/// are indented from there.
fn render_child(renderer: &YamlRenderer, node: &DiffNode, parent_indent: u16, output: &mut String) {
    let child_indent = parent_indent + renderer.indent_width;
    renderer.render_node(node, child_indent, output);
}

/// Renders a leaf node (a single difference).
fn render_leaf(
    renderer: &YamlRenderer,
    segment: &PathSegment,
    kind: &DiffKind,
    indent: u16,
    output: &mut String,
) {
    match kind {
        // Changed values are always scalars (compound types produce
        // Container nodes, not Leaf nodes). Safe to call format_scalar.
        DiffKind::Changed { actual, expected } => {
            // Emit an index comment for position-matched array elements
            if let Some(comment) = index_comment(segment) {
                push_line(output, indicator::CONTEXT, indent, &comment);
            }

            if segment.is_array() {
                // Array element. Render as a YAML list item.
                push_line(
                    output,
                    indicator::EXPECTED,
                    indent,
                    &format!("- {val}", val = format_scalar(expected)),
                );
                push_line(
                    output,
                    indicator::ACTUAL,
                    indent,
                    &format!("- {val}", val = format_scalar(actual)),
                );
            } else {
                let label = format_segment_label(segment);
                push_line(
                    output,
                    indicator::EXPECTED,
                    indent,
                    &format!("{label}: {val}", val = format_scalar(expected)),
                );
                push_line(
                    output,
                    indicator::ACTUAL,
                    indent,
                    &format!("{label}: {val}", val = format_scalar(actual)),
                );
            }
        }

        DiffKind::Missing { expected } => {
            // Emit an index comment for position-matched array elements
            if let Some(comment) = index_comment(segment) {
                push_line(output, indicator::CONTEXT, indent, &comment);
            }

            if segment.is_array() {
                // Missing array element. Render as a YAML list item.
                render_missing_array_element(
                    output,
                    indicator::EXPECTED,
                    indent,
                    renderer.indent_width,
                    expected,
                    renderer.max_lines_per_side,
                );
            } else {
                let label = format_segment_label(segment);
                if is_scalar(expected) {
                    // Scalar missing value, safe to call format_scalar
                    push_line(
                        output,
                        indicator::EXPECTED,
                        indent,
                        &format!("{label}: {val}", val = format_scalar(expected)),
                    );
                } else {
                    // Compound missing value. Render the key, then the full
                    // expected value as `-` prefixed YAML lines.
                    push_line(output, indicator::EXPECTED, indent, &format!("{label}:"));
                    render_value_truncated(
                        output,
                        indicator::EXPECTED,
                        indent + renderer.indent_width,
                        renderer.indent_width,
                        expected,
                        renderer.max_lines_per_side,
                    );
                }
            }
        }

        DiffKind::TypeMismatch {
            actual,
            actual_type,
            expected,
            expected_type,
        } => {
            let label = format_segment_label(segment);

            // Build the content portion of each header line (before the comment)
            let expected_header = if is_scalar(expected) {
                format!("{label}: {val}", val = format_scalar(expected))
            } else {
                format!("{label}:")
            };
            let actual_header = if is_scalar(actual) {
                format!("{label}: {val}", val = format_scalar(actual))
            } else {
                format!("{label}:")
            };

            // Pad the shorter header so the type comments align
            let max_len = expected_header.len().max(actual_header.len());

            // Render expected side
            push_line(
                output,
                indicator::EXPECTED,
                indent,
                &format!(
                    "{expected_header:<width$} # expected: {expected_type}",
                    width = max_len
                ),
            );
            if !is_scalar(expected) {
                render_value_truncated(
                    output,
                    indicator::EXPECTED,
                    indent + renderer.indent_width,
                    renderer.indent_width,
                    expected,
                    renderer.max_lines_per_side,
                );
            }

            // Render actual side
            push_line(
                output,
                indicator::ACTUAL,
                indent,
                &format!(
                    "{actual_header:<width$} # actual: {actual_type}",
                    width = max_len
                ),
            );
            if !is_scalar(actual) {
                render_value_truncated(
                    output,
                    indicator::ACTUAL,
                    indent + renderer.indent_width,
                    renderer.indent_width,
                    actual,
                    renderer.max_lines_per_side,
                );
            }
        }
    }
}

/// Returns a trailing comment for Index segments (e.g. `# index 1`).
///
/// Returns `None` for non-Index segments.
fn index_comment(segment: &PathSegment) -> Option<String> {
    match segment {
        PathSegment::Index(i) => Some(format!("# index {i}")),
        _ => None,
    }
}

/// Renders a missing array element as a YAML list item.
///
/// Scalars render as `- value`. Objects render with the first key on
/// the same line as `- `. Applies truncation for compound values.
fn render_missing_array_element(
    output: &mut String,
    prefix: char,
    indent: u16,
    indent_width: u16,
    value: &Value,
    max_lines: Option<u32>,
) {
    if is_scalar(value) {
        push_line(
            output,
            prefix,
            indent,
            &format!("- {val}", val = format_scalar(value)),
        );
    } else {
        let mut buf = String::new();
        render_array_element(&mut buf, prefix, indent, indent_width, value);
        match max_lines {
            Some(max) => {
                let lines: Vec<&str> = buf.lines().collect();
                let total = lines.len() as u32;
                if total <= max {
                    output.push_str(&buf);
                } else {
                    for line in &lines[..max as usize] {
                        output.push_str(line);
                        output.push('\n');
                    }
                    let remaining = total - max;
                    push_line(
                        output,
                        prefix,
                        indent + indent_width,
                        &format!("# {remaining} more lines"),
                    );
                }
            }
            None => {
                output.push_str(&buf);
            }
        }
    }
}

/// Returns the appropriate unit word for omitted count based on the segment
/// type and count.
///
/// Object keys use "field"/"fields", array segments use "item"/"items".
fn omitted_unit(child_kind: &ChildKind, count: u16) -> &'static str {
    match (child_kind, count) {
        (ChildKind::Fields, 1) => "field",
        (ChildKind::Fields, _) => "fields",
        (ChildKind::Items, 1) => "item",
        (ChildKind::Items, _) => "items",
    }
}

/// Formats a path segment as a label for rendering.
fn format_segment_label(segment: &PathSegment) -> String {
    match segment {
        PathSegment::Key(key) => key.clone(),
        PathSegment::NamedElement {
            match_key,
            match_value,
        } => format!("- {match_key}: {match_value}"),
        PathSegment::Index(i) => format!("- # index {i}"),
        PathSegment::Unmatched => "-".to_owned(),
    }
}

/// Renders a compound value with optional line truncation.
///
/// Renders into a temporary buffer, then appends to `output`. If the
/// rendered output exceeds `max_lines`, only the first `max_lines` lines
/// are kept and a `# N more lines` marker is appended.
fn render_value_truncated(
    output: &mut String,
    prefix: char,
    indent: u16,
    indent_width: u16,
    value: &Value,
    max_lines: Option<u32>,
) {
    let mut buf = String::new();
    render_value(&mut buf, prefix, indent, indent_width, value);

    match max_lines {
        Some(max) => {
            let lines: Vec<&str> = buf.lines().collect();
            let total = lines.len() as u32;

            if total <= max {
                output.push_str(&buf);
            } else {
                // Append the first max_lines lines
                for line in &lines[..max as usize] {
                    output.push_str(line);
                    output.push('\n');
                }
                // Append the truncation marker with the same prefix
                let remaining = total - max;
                push_line(output, prefix, indent, &format!("# {remaining} more lines"));
            }
        }
        None => {
            output.push_str(&buf);
        }
    }
}

/// Renders a single key-value pair as YAML.
///
/// Scalars render as `key: value` on one line. Objects and arrays render
/// `key:` followed by the recursively rendered value on subsequent lines.
/// Also used for array element first keys via `render_array_element`,
/// where `key` is prefixed with `- ` (e.g. `- name`).
fn render_key_value(
    output: &mut String,
    prefix: char,
    indent: u16,
    indent_width: u16,
    key: &str,
    value: &Value,
) {
    if is_scalar(value) {
        push_line(
            output,
            prefix,
            indent,
            &format!("{key}: {val}", val = format_scalar(value)),
        );
    } else {
        push_line(output, prefix, indent, &format!("{key}:"));
        render_value(output, prefix, indent + indent_width, indent_width, value);
    }
}

/// Recursively renders a JSON value as YAML lines with the given prefix.
///
/// Used for rendering compound values in Missing and TypeMismatch diffs.
/// Each line is prefixed with the indicator character (e.g. `-` for expected).
fn render_value(output: &mut String, prefix: char, indent: u16, indent_width: u16, value: &Value) {
    match value {
        // Scalars render as a single value (caller handles the key)
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {
            push_line(output, prefix, indent, &format_scalar(value));
        }

        Value::Object(map) => {
            for (key, val) in map {
                render_key_value(output, prefix, indent, indent_width, key, val);
            }
        }

        Value::Array(arr) => {
            for elem in arr {
                if is_scalar(elem) {
                    push_line(
                        output,
                        prefix,
                        indent,
                        &format!("- {val}", val = format_scalar(elem)),
                    );
                } else {
                    // Render first key on the same line as `- `, rest indented
                    render_array_element(output, prefix, indent, indent_width, elem);
                }
            }
        }
    }
}

/// Renders a compound array element, placing the first object key on the
/// same line as the `- ` marker for natural YAML formatting.
fn render_array_element(
    output: &mut String,
    prefix: char,
    indent: u16,
    indent_width: u16,
    value: &Value,
) {
    match value {
        Value::Object(map) => {
            let mut first = true;
            for (key, val) in map {
                if first {
                    // First key goes on the `- ` line
                    render_key_value(
                        output,
                        prefix,
                        indent,
                        indent_width,
                        &format!("- {key}"),
                        val,
                    );
                    first = false;
                } else {
                    // Subsequent keys are indented past the `- `
                    render_key_value(
                        output,
                        prefix,
                        indent + indent_width,
                        indent_width,
                        key,
                        val,
                    );
                }
            }
        }

        // Non-object array elements (nested arrays)
        _ => {
            push_line(output, prefix, indent, "-");
            render_value(output, prefix, indent + indent_width, indent_width, value);
        }
    }
}

/// Builds a line string from prefix, indentation, and content.
fn build_line(prefix: char, indent: u16, content: &str) -> String {
    let mut line = String::with_capacity(1 + indent as usize + content.len());
    line.push(prefix);
    for _ in 0..indent {
        line.push(' ');
    }
    line.push_str(content);
    line
}

/// Pushes a single line to the output with the given prefix and indentation.
fn push_line(output: &mut String, prefix: char, indent: u16, content: &str) {
    let line = build_line(prefix, indent, content);
    output.push_str(&line);
    output.push('\n');
}


/// Formats a JSON value as a YAML scalar.
fn format_scalar(value: &Value) -> String {
    match value {
        Value::Null => "null".to_owned(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::String(s) => {
            if needs_yaml_quoting(s) {
                let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
                format!("\"{escaped}\"")
            } else {
                s.clone()
            }
        }
        Value::Array(_) | Value::Object(_) => {
            unreachable!("format_scalar called with compound value")
        }
    }
}

/// Returns true if a string needs quoting in YAML.
fn needs_yaml_quoting(s: &str) -> bool {
    if s.is_empty() {
        return true;
    }

    // Values that YAML would interpret as non-strings
    const SPECIAL: &[&str] = &[
        "true", "false", "null", "yes", "no", "on", "off", "True", "False", "Null", "Yes", "No",
        "On", "Off", "TRUE", "FALSE", "NULL", "YES", "NO", "ON", "OFF",
    ];
    if SPECIAL.contains(&s) {
        return true;
    }

    // Strings that look like numbers
    if s.parse::<f64>().is_ok() {
        return true;
    }

    // Strings with special YAML characters
    s.contains(':')
        || s.contains('#')
        || s.contains('\n')
        || s.starts_with(' ')
        || s.ends_with(' ')
        || s.starts_with('{')
        || s.starts_with('[')
        || s.starts_with('*')
        || s.starts_with('&')
        || s.starts_with('!')
        || s.starts_with('|')
        || s.starts_with('>')
}

/// Returns true if a value is a scalar (not an object or array).
fn is_scalar(value: &Value) -> bool {
    matches!(
        value,
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_)
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DiffConfig, diff};
    use indoc::indoc;
    use serde_json::json;

    fn render(actual: &Value, expected: &Value) -> String {
        let config = DiffConfig::default();
        let tree = diff(actual, expected, &config).expect("diff with valid inputs");
        YamlRenderer::new().render(&tree)
    }

    #[test]
    fn scalar_changed_renders_minus_plus() {
        let output = render(
            &json!({"name": "actual_value"}),
            &json!({"name": "expected_value"}),
        );
        assert_eq!(
            output,
            indoc! {"
                -name: expected_value
                +name: actual_value
            "}
        );
    }

    #[test]
    fn nested_scalar_changed() {
        let output = render(
            &json!({"a": {"b": "actual"}}),
            &json!({"a": {"b": "expected"}}),
        );
        assert_eq!(
            output,
            indoc! {"
                 a:
                -  b: expected
                +  b: actual
            "}
        );
    }

    #[test]
    fn missing_scalar_key() {
        let output = render(&json!({"a": 1}), &json!({"a": 1, "b": 2}));
        assert_eq!(
            output,
            indoc! {"
                -b: 2
            "}
        );
    }

    #[test]
    fn equal_values_render_empty() {
        let output = render(&json!({"a": 1}), &json!({"a": 1}));
        assert_eq!(output, "");
    }

    #[test]
    #[allow(clippy::approx_constant)]
    fn type_mismatch_scalar() {
        // actual has number 42, expected has string "42".
        // "42" is quoted because it looks like a number in YAML.
        // Comments are aligned by padding the shorter line.
        let output = render(&json!({"a": 42}), &json!({"a": "42"}));
        assert_eq!(
            output,
            indoc! {r#"
                -a: "42" # expected: string
                +a: 42   # actual: number
            "#}
        );
    }

    #[test]
    fn type_mismatch_null_vs_object() {
        let output = render(&json!({"a": null}), &json!({"a": {"b": 1}}));
        assert_eq!(
            output,
            indoc! {"
                -a:      # expected: object
                -  b: 1
                +a: null # actual: null
            "}
        );
    }

    #[test]
    fn missing_object_subtree() {
        let output = render(&json!({"a": 1}), &json!({"a": 1, "b": {"x": 1, "y": 2}}));
        assert_eq!(
            output,
            indoc! {"
                -b:
                -  x: 1
                -  y: 2
            "}
        );
    }

    #[test]
    fn missing_array_subtree() {
        let output = render(&json!({"a": 1}), &json!({"a": 1, "items": [1, 2, 3]}));
        assert_eq!(
            output,
            indoc! {"
                -items:
                -  - 1
                -  - 2
                -  - 3
            "}
        );
    }

    #[test]
    fn missing_nested_object_in_array() {
        let output = render(
            &json!({"a": 1}),
            &json!({"a": 1, "items": [{"name": "foo", "value": "bar"}]}),
        );
        assert_eq!(
            output,
            indoc! {"
                -items:
                -  - name: foo
                -    value: bar
            "}
        );
    }

    #[test]
    fn missing_subtree_truncated() {
        // Use a renderer with max 2 lines per side.
        // Keys are alphabetically ordered (serde_json uses BTreeMap).
        let config = DiffConfig::default();
        let actual = json!({"a": 1});
        let expected = json!({"a": 1, "b": {"p": 1, "q": 2, "r": 3, "s": 4}});
        let tree = diff(&actual, &expected, &config).expect("diff with valid inputs");
        let output = YamlRenderer::new()
            .with_max_lines_per_side(Some(2))
            .render(&tree);
        assert_eq!(
            output,
            indoc! {"
                -b:
                -  p: 1
                -  q: 2
                -  # 2 more lines
            "}
        );
    }

    #[test]
    fn truncation_disabled_renders_all_lines() {
        let config = DiffConfig::default();
        let actual = json!({"a": 1});
        let expected = json!({"a": 1, "b": {"x": 1, "y": 2, "z": 3}});
        let tree = diff(&actual, &expected, &config).expect("diff with valid inputs");
        let output = YamlRenderer::new()
            .with_max_lines_per_side(None)
            .render(&tree);
        assert_eq!(
            output,
            indoc! {"
                -b:
                -  x: 1
                -  y: 2
                -  z: 3
            "}
        );
    }

    #[test]
    fn omitted_fields_comment() {
        // inner object has 3 keys, expected checks 1 that differs. 2 fields omitted.
        let output = render(
            &json!({"outer": {"a": 1, "b": 2, "c": 3}}),
            &json!({"outer": {"a": 99}}),
        );
        assert_eq!(
            output,
            indoc! {"
                 outer:
                   # 2 fields omitted
                -  a: 99
                +  a: 1
            "}
        );
    }
}