patchkit 0.2.4

A library for parsing and manipulating patch files
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
//! Lossless AST structures for patch files
use crate::edit::lex::SyntaxKind;
use rowan::{ast::AstNode, SyntaxNode, SyntaxToken};

/// Language definition for patch file syntax
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Lang {}

impl rowan::Language for Lang {
    type Kind = SyntaxKind;

    fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind {
        assert!(raw.0 <= SyntaxKind::NO_NEWLINE_LINE as u16);
        unsafe { std::mem::transmute(raw.0) }
    }

    fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind {
        kind.into()
    }
}

/// Syntax element type for patch files
pub type SyntaxElement = rowan::SyntaxElement<Lang>;

/// The format of a diff
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffFormat {
    /// Unified diff format (diff -u)
    Unified,
    /// Context diff format (diff -c)
    Context,
    /// Ed script format (diff -e)
    Ed,
    /// Normal/traditional diff format
    Normal,
}

pub use super::{ParseError, PositionedParseError};

macro_rules! ast_node {
    ($name:ident, $kind:expr) => {
        #[doc = concat!("AST node for ", stringify!($name))]
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        pub struct $name {
            syntax: SyntaxNode<Lang>,
        }

        impl AstNode for $name {
            type Language = Lang;

            fn can_cast(kind: SyntaxKind) -> bool {
                kind == $kind
            }

            fn cast(syntax: SyntaxNode<Lang>) -> Option<Self> {
                if Self::can_cast(syntax.kind()) {
                    Some(Self { syntax })
                } else {
                    None
                }
            }

            fn syntax(&self) -> &SyntaxNode<Lang> {
                &self.syntax
            }
        }
    };
}

// Root and generic nodes
ast_node!(Patch, SyntaxKind::ROOT);
ast_node!(PatchFile, SyntaxKind::PATCH_FILE);

// Unified diff nodes
ast_node!(FileHeader, SyntaxKind::FILE_HEADER);
ast_node!(OldFile, SyntaxKind::OLD_FILE);
ast_node!(NewFile, SyntaxKind::NEW_FILE);
ast_node!(Hunk, SyntaxKind::HUNK);
ast_node!(HunkHeader, SyntaxKind::HUNK_HEADER);
ast_node!(HunkRange, SyntaxKind::HUNK_RANGE);
ast_node!(HunkLine, SyntaxKind::HUNK_LINE);
ast_node!(ContextLine, SyntaxKind::CONTEXT_LINE);
ast_node!(AddLine, SyntaxKind::ADD_LINE);
ast_node!(DeleteLine, SyntaxKind::DELETE_LINE);

// Context diff nodes
ast_node!(ContextDiffFile, SyntaxKind::CONTEXT_DIFF_FILE);
ast_node!(ContextOldFile, SyntaxKind::CONTEXT_OLD_FILE);
ast_node!(ContextNewFile, SyntaxKind::CONTEXT_NEW_FILE);
ast_node!(ContextHunk, SyntaxKind::CONTEXT_HUNK);
ast_node!(ContextHunkHeader, SyntaxKind::CONTEXT_HUNK_HEADER);
ast_node!(ContextOldSection, SyntaxKind::CONTEXT_OLD_SECTION);
ast_node!(ContextNewSection, SyntaxKind::CONTEXT_NEW_SECTION);
ast_node!(ContextChangeLine, SyntaxKind::CONTEXT_CHANGE_LINE);

// Ed diff nodes
ast_node!(EdCommand, SyntaxKind::ED_COMMAND);
ast_node!(EdAddCommand, SyntaxKind::ED_ADD_COMMAND);
ast_node!(EdDeleteCommand, SyntaxKind::ED_DELETE_COMMAND);
ast_node!(EdChangeCommand, SyntaxKind::ED_CHANGE_COMMAND);
ast_node!(EdContentLine, SyntaxKind::ED_CONTENT_LINE);

// Normal diff nodes
ast_node!(NormalHunk, SyntaxKind::NORMAL_HUNK);
ast_node!(NormalChangeCommand, SyntaxKind::NORMAL_CHANGE_COMMAND);
ast_node!(NormalOldLines, SyntaxKind::NORMAL_OLD_LINES);
ast_node!(NormalNewLines, SyntaxKind::NORMAL_NEW_LINES);
ast_node!(NormalSeparator, SyntaxKind::NORMAL_SEPARATOR);

impl Patch {
    /// Get all patch files in this patch
    pub fn patch_files(&self) -> impl Iterator<Item = PatchFile> {
        self.syntax().children().filter_map(PatchFile::cast)
    }

    /// Get all context diff files in this patch
    pub fn context_diff_files(&self) -> impl Iterator<Item = ContextDiffFile> {
        self.syntax().children().filter_map(ContextDiffFile::cast)
    }

    /// Get all ed commands in this patch
    pub fn ed_commands(&self) -> impl Iterator<Item = EdCommand> {
        self.syntax().children().filter_map(EdCommand::cast)
    }

    /// Get all normal diff hunks in this patch
    pub fn normal_hunks(&self) -> impl Iterator<Item = NormalHunk> {
        self.syntax().children().filter_map(NormalHunk::cast)
    }

    /// Try to detect the format of this patch
    pub fn detect_format(&self) -> Option<DiffFormat> {
        // Check for unified diff
        if self.patch_files().next().is_some() {
            return Some(DiffFormat::Unified);
        }

        // Check for context diff
        if self.context_diff_files().next().is_some() {
            return Some(DiffFormat::Context);
        }

        // Check for ed diff
        if self.ed_commands().next().is_some() {
            return Some(DiffFormat::Ed);
        }

        // Check for normal diff
        if self.normal_hunks().next().is_some() {
            return Some(DiffFormat::Normal);
        }

        None
    }
}

impl PatchFile {
    /// Get the old file header
    pub fn old_file(&self) -> Option<OldFile> {
        self.syntax().children().find_map(OldFile::cast)
    }

    /// Get the new file header
    pub fn new_file(&self) -> Option<NewFile> {
        self.syntax().children().find_map(NewFile::cast)
    }

    /// Get the old file path.
    pub fn old_path(&self) -> Option<String> {
        self.old_file()
            .and_then(|f| f.path())
            .map(|t| t.text().to_string())
    }

    /// Get the new file path.
    pub fn new_path(&self) -> Option<String> {
        self.new_file()
            .and_then(|f| f.path())
            .map(|t| t.text().to_string())
    }

    /// Get the file path, preferring the new file name.
    pub fn path(&self) -> Option<String> {
        self.new_path().or_else(|| self.old_path())
    }

    /// Get a display name for this file diff.
    ///
    /// Shows "old → new" if the paths differ, otherwise just the path.
    pub fn display_name(&self) -> String {
        match (self.old_path(), self.new_path()) {
            (Some(o), Some(n)) if o == n => o,
            (Some(o), Some(n)) => format!("{o}{n}"),
            (Some(o), None) => o,
            (None, Some(n)) => n,
            (None, None) => "<unknown>".to_string(),
        }
    }

    /// Get all hunks in this patch file
    pub fn hunks(&self) -> impl Iterator<Item = Hunk> {
        self.syntax().children().filter_map(Hunk::cast)
    }
}

impl OldFile {
    /// Get the file path
    pub fn path(&self) -> Option<SyntaxToken<Lang>> {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .find(|token| token.kind() == SyntaxKind::PATH)
    }
}

impl NewFile {
    /// Get the file path
    pub fn path(&self) -> Option<SyntaxToken<Lang>> {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .find(|token| token.kind() == SyntaxKind::PATH)
    }
}

/// Line count statistics for a hunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HunkStats {
    /// Number of context (unchanged) lines
    pub context: u32,
    /// Number of added lines
    pub additions: u32,
    /// Number of deleted lines
    pub deletions: u32,
}

impl Hunk {
    /// Get the hunk header
    pub fn header(&self) -> Option<HunkHeader> {
        self.syntax().children().find_map(HunkHeader::cast)
    }

    /// Get all lines in this hunk
    pub fn lines(&self) -> impl Iterator<Item = HunkLine> {
        self.syntax()
            .children()
            .filter_map(|child| match child.kind() {
                SyntaxKind::CONTEXT_LINE | SyntaxKind::ADD_LINE | SyntaxKind::DELETE_LINE => {
                    Some(HunkLine { syntax: child })
                }
                _ => None,
            })
    }

    /// Fix the line counts in the hunk header to match the actual content.
    ///
    /// Returns `true` if any counts were changed.
    pub fn fix_counts(&self) -> bool {
        let Some(header) = self.header() else {
            return false;
        };
        let stats = self.stats();
        let mut changed = false;

        if let Some(old_range) = header.old_range() {
            let actual = stats.context + stats.deletions;
            if old_range.count() != Some(actual) {
                old_range.set_count(actual);
                changed = true;
            }
        }

        if let Some(new_range) = header.new_range() {
            let actual = stats.context + stats.additions;
            if new_range.count() != Some(actual) {
                new_range.set_count(actual);
                changed = true;
            }
        }

        changed
    }

    /// Count the lines in this hunk by type.
    pub fn stats(&self) -> HunkStats {
        let mut stats = HunkStats {
            context: 0,
            additions: 0,
            deletions: 0,
        };
        for line in self.lines() {
            match line.syntax().kind() {
                SyntaxKind::CONTEXT_LINE => stats.context += 1,
                SyntaxKind::ADD_LINE => stats.additions += 1,
                SyntaxKind::DELETE_LINE => stats.deletions += 1,
                _ => {}
            }
        }
        stats
    }
}

impl HunkHeader {
    /// Get the old file range for this hunk
    pub fn old_range(&self) -> Option<HunkRange> {
        self.syntax().children().find_map(HunkRange::cast)
    }

    /// Get the new file range for this hunk
    pub fn new_range(&self) -> Option<HunkRange> {
        self.syntax().children().filter_map(HunkRange::cast).nth(1)
    }
}

/// Which side of a diff hunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HunkSide {
    /// The old (original) side
    Old,
    /// The new (modified) side
    New,
}

impl std::fmt::Display for HunkSide {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HunkSide::Old => write!(f, "old"),
            HunkSide::New => write!(f, "new"),
        }
    }
}

/// A mismatch between a hunk header's declared line count and the actual count.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HunkCountMismatch {
    /// Which side of the diff
    pub side: HunkSide,
    /// The count declared in the header
    pub expected: u32,
    /// The actual count of lines in the hunk
    pub actual: u32,
}

impl HunkHeader {
    /// Check whether the declared line counts match the actual hunk content.
    ///
    /// Returns a list of mismatches (empty if everything matches).
    /// Requires the parent `Hunk` node to count the lines.
    pub fn check_counts(&self, hunk: &Hunk) -> Vec<HunkCountMismatch> {
        let stats = hunk.stats();
        let mut mismatches = Vec::new();

        if let Some(old_range) = self.old_range() {
            let expected = old_range.count().unwrap_or(1);
            let actual = stats.context + stats.deletions;
            if expected != actual {
                mismatches.push(HunkCountMismatch {
                    side: HunkSide::Old,
                    expected,
                    actual,
                });
            }
        }

        if let Some(new_range) = self.new_range() {
            let expected = new_range.count().unwrap_or(1);
            let actual = stats.context + stats.additions;
            if expected != actual {
                mismatches.push(HunkCountMismatch {
                    side: HunkSide::New,
                    expected,
                    actual,
                });
            }
        }

        mismatches
    }
}

impl HunkRange {
    /// Get the starting line number
    pub fn start(&self) -> Option<u32> {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .find(|token| token.kind() == SyntaxKind::NUMBER)
            .and_then(|token| token.text().parse().ok())
    }

    /// Get the number of lines in this range
    pub fn count(&self) -> Option<u32> {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::NUMBER)
            .nth(1)
            .and_then(|token| token.text().parse().ok())
    }

    /// Set the line count, modifying the syntax tree in place.
    ///
    /// If the range already has a `,count` part, replaces the count token.
    /// If it only has a start number, inserts `,count` after it.
    pub fn set_count(&self, new_count: u32) {
        let count_str = new_count.to_string();

        // Build a replacement NUMBER token
        let new_token = Self::make_token(SyntaxKind::NUMBER, &count_str);

        // Find the second NUMBER token (the count)
        let mut number_indices = Vec::new();
        for (index, element) in self.syntax().children_with_tokens().enumerate() {
            if let rowan::NodeOrToken::Token(token) = element {
                if token.kind() == SyntaxKind::NUMBER {
                    number_indices.push(index);
                }
            }
        }

        if number_indices.len() >= 2 {
            // Replace the existing count token
            let idx = number_indices[1];
            self.syntax()
                .splice_children(idx..idx + 1, vec![rowan::NodeOrToken::Token(new_token)]);
        } else if !number_indices.is_empty() {
            // No count yet - insert comma + count after the start number
            let insert_at = number_indices[0] + 1;
            let comma_token = Self::make_token(SyntaxKind::COMMA, ",");
            self.syntax().splice_children(
                insert_at..insert_at,
                vec![
                    rowan::NodeOrToken::Token(comma_token),
                    rowan::NodeOrToken::Token(new_token),
                ],
            );
        }
    }

    fn make_token(kind: SyntaxKind, text: &str) -> rowan::SyntaxToken<Lang> {
        let mut builder = rowan::GreenNodeBuilder::new();
        builder.start_node(SyntaxKind::ROOT.into());
        builder.token(kind.into(), text);
        builder.finish_node();
        let green = builder.finish();
        let node = SyntaxNode::new_root_mut(green);
        node.first_token().unwrap()
    }
}

impl HunkLine {
    /// Attempt to cast this line as a context line
    pub fn as_context(&self) -> Option<ContextLine> {
        ContextLine::cast(self.syntax().clone())
    }

    /// Attempt to cast this line as an add line
    pub fn as_add(&self) -> Option<AddLine> {
        AddLine::cast(self.syntax().clone())
    }

    /// Attempt to cast this line as a delete line
    pub fn as_delete(&self) -> Option<DeleteLine> {
        DeleteLine::cast(self.syntax().clone())
    }

    /// Get the text content of this line
    pub fn text(&self) -> Option<String> {
        // Collect all tokens, skipping only the first one if it's a line prefix
        let tokens = self
            .syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() != SyntaxKind::NEWLINE);

        // Skip the first token if it's a line prefix (SPACE, MINUS, or PLUS)
        let mut iter = tokens.peekable();
        if let Some(first) = iter.peek() {
            if matches!(
                first.kind(),
                SyntaxKind::SPACE | SyntaxKind::MINUS | SyntaxKind::PLUS
            ) {
                iter.next(); // Skip the prefix
            }
        }

        let remaining: Vec<_> = iter.collect();
        if remaining.is_empty() {
            None
        } else {
            // Concatenate all tokens to form the line content
            Some(remaining.iter().map(|t| t.text()).collect::<String>())
        }
    }
}

// Context diff methods
impl ContextDiffFile {
    /// Get the old file header
    pub fn old_file(&self) -> Option<ContextOldFile> {
        self.syntax().children().find_map(ContextOldFile::cast)
    }

    /// Get the new file header
    pub fn new_file(&self) -> Option<ContextNewFile> {
        self.syntax().children().find_map(ContextNewFile::cast)
    }

    /// Get all hunks in this context diff file
    pub fn hunks(&self) -> impl Iterator<Item = ContextHunk> {
        self.syntax().children().filter_map(ContextHunk::cast)
    }
}

impl ContextOldFile {
    /// Get the file path token
    pub fn path(&self) -> Option<SyntaxToken<Lang>> {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .find(|token| token.kind() == SyntaxKind::PATH)
    }
}

impl ContextNewFile {
    /// Get the file path token
    pub fn path(&self) -> Option<SyntaxToken<Lang>> {
        self.syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .find(|token| token.kind() == SyntaxKind::PATH)
    }
}

impl ContextHunk {
    /// Get the hunk header
    pub fn header(&self) -> Option<ContextHunkHeader> {
        self.syntax().children().find_map(ContextHunkHeader::cast)
    }

    /// Get the old section
    pub fn old_section(&self) -> Option<ContextOldSection> {
        self.syntax().children().find_map(ContextOldSection::cast)
    }

    /// Get the new section
    pub fn new_section(&self) -> Option<ContextNewSection> {
        self.syntax().children().find_map(ContextNewSection::cast)
    }
}

// Ed diff methods
impl EdCommand {
    /// Try to cast as an add command
    pub fn as_add(&self) -> Option<EdAddCommand> {
        self.syntax().children().find_map(EdAddCommand::cast)
    }

    /// Try to cast as a delete command
    pub fn as_delete(&self) -> Option<EdDeleteCommand> {
        self.syntax().children().find_map(EdDeleteCommand::cast)
    }

    /// Try to cast as a change command
    pub fn as_change(&self) -> Option<EdChangeCommand> {
        self.syntax().children().find_map(EdChangeCommand::cast)
    }
}

impl EdAddCommand {
    /// Get the line numbers
    pub fn line_numbers(&self) -> (Option<u32>, Option<u32>) {
        let numbers: Vec<_> = self
            .syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::NUMBER)
            .filter_map(|token| token.text().parse().ok())
            .collect();

        (numbers.get(0).copied(), numbers.get(1).copied())
    }

    /// Get content lines
    pub fn content_lines(&self) -> impl Iterator<Item = EdContentLine> {
        self.syntax().children().filter_map(EdContentLine::cast)
    }
}

impl EdDeleteCommand {
    /// Get the line numbers
    pub fn line_numbers(&self) -> (Option<u32>, Option<u32>) {
        let numbers: Vec<_> = self
            .syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::NUMBER)
            .filter_map(|token| token.text().parse().ok())
            .collect();

        (numbers.get(0).copied(), numbers.get(1).copied())
    }
}

impl EdChangeCommand {
    /// Get the line numbers
    pub fn line_numbers(&self) -> (Option<u32>, Option<u32>) {
        let numbers: Vec<_> = self
            .syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::NUMBER)
            .filter_map(|token| token.text().parse().ok())
            .collect();

        (numbers.get(0).copied(), numbers.get(1).copied())
    }

    /// Get content lines
    pub fn content_lines(&self) -> impl Iterator<Item = EdContentLine> {
        self.syntax().children().filter_map(EdContentLine::cast)
    }
}

impl EdContentLine {
    /// Get the text content of this line
    pub fn text(&self) -> Option<String> {
        let tokens: Vec<_> = self
            .syntax()
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() != SyntaxKind::NEWLINE)
            .collect();

        if tokens.is_empty() {
            None
        } else {
            Some(tokens.iter().map(|t| t.text()).collect::<String>())
        }
    }
}

// Normal diff methods
impl NormalHunk {
    /// Get the change command
    pub fn command(&self) -> Option<NormalChangeCommand> {
        self.syntax().children().find_map(NormalChangeCommand::cast)
    }

    /// Get old lines section
    pub fn old_lines(&self) -> Option<NormalOldLines> {
        self.syntax().children().find_map(NormalOldLines::cast)
    }

    /// Get new lines section
    pub fn new_lines(&self) -> Option<NormalNewLines> {
        self.syntax().children().find_map(NormalNewLines::cast)
    }
}

/// Parse a patch file from text
pub fn parse(text: &str) -> super::Parse<Patch> {
    let tokens = super::lex::lex(text);
    let parser = super::parse::Parser::new(tokens);
    parser.parse()
}

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

    #[test]
    fn test_fix_counts_correct() {
        let text = "--- a/f\n+++ b/f\n@@ -1,3 +1,3 @@\n ctx\n-old\n+new\n ctx2\n";
        let parsed = parse(text);
        let patch = parsed.tree();
        let hunk = patch.patch_files().next().unwrap().hunks().next().unwrap();
        assert!(!hunk.fix_counts());
        assert_eq!(patch.syntax().to_string(), text);
    }

    #[test]
    fn test_fix_counts_wrong_old() {
        let text = "--- a/f\n+++ b/f\n@@ -1,99 +1,2 @@\n ctx\n-old\n";
        let parsed = parse(text);
        let patch = parsed.tree();
        let hunk = patch.patch_files().next().unwrap().hunks().next().unwrap();
        assert!(hunk.fix_counts());
        assert_eq!(
            patch.syntax().to_string(),
            "--- a/f\n+++ b/f\n@@ -1,2 +1,1 @@\n ctx\n-old\n"
        );
    }

    #[test]
    fn test_fix_counts_no_count_present() {
        let text = "--- a/f\n+++ b/f\n@@ -1 +1 @@\n-old\n+new1\n+new2\n";
        let parsed = parse(text);
        let patch = parsed.tree();
        let hunk = patch.patch_files().next().unwrap().hunks().next().unwrap();
        assert!(hunk.fix_counts());
        assert_eq!(
            patch.syntax().to_string(),
            "--- a/f\n+++ b/f\n@@ -1,1 +1,2 @@\n-old\n+new1\n+new2\n"
        );
    }

    #[test]
    fn test_set_count_replace() {
        let text = "--- a/f\n+++ b/f\n@@ -1,5 +1,5 @@\n ctx\n";
        let parsed = parse(text);
        let patch = parsed.tree();
        let hunk = patch.patch_files().next().unwrap().hunks().next().unwrap();
        let header = hunk.header().unwrap();
        header.old_range().unwrap().set_count(42);
        assert_eq!(
            patch.syntax().to_string(),
            "--- a/f\n+++ b/f\n@@ -1,42 +1,5 @@\n ctx\n"
        );
    }

    #[test]
    fn test_hunk_stats() {
        let text = "--- a/f\n+++ b/f\n@@ -1,4 +1,5 @@\n ctx1\n ctx2\n-del\n+add1\n+add2\n";
        let parsed = parse(text);
        let patch = parsed.tree();
        let hunk = patch.patch_files().next().unwrap().hunks().next().unwrap();
        let stats = hunk.stats();
        assert_eq!(stats.context, 2);
        assert_eq!(stats.deletions, 1);
        assert_eq!(stats.additions, 2);
    }

    #[test]
    fn test_check_counts_mismatch() {
        let text = "--- a/f\n+++ b/f\n@@ -1,99 +1,99 @@\n ctx\n-old\n+new\n";
        let parsed = parse(text);
        let patch = parsed.tree();
        let hunk = patch.patch_files().next().unwrap().hunks().next().unwrap();
        let mismatches = hunk.header().unwrap().check_counts(&hunk);
        assert_eq!(mismatches.len(), 2);
        assert_eq!(mismatches[0].side, HunkSide::Old);
        assert_eq!(mismatches[0].expected, 99);
        assert_eq!(mismatches[0].actual, 2);
        assert_eq!(mismatches[1].side, HunkSide::New);
        assert_eq!(mismatches[1].expected, 99);
        assert_eq!(mismatches[1].actual, 2);
    }

    #[test]
    fn test_patch_file_display_name() {
        let text = "--- a/old.txt\n+++ b/new.txt\n@@ -1 +1 @@\n-a\n+b\n";
        let parsed = parse(text);
        let patch = parsed.tree();
        let file = patch.patch_files().next().unwrap();
        assert_eq!(file.display_name(), "a/old.txt → b/new.txt");
    }

    #[test]
    fn test_patch_file_display_name_same() {
        let text = "--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-a\n+b\n";
        let parsed = parse(text);
        let patch = parsed.tree();
        let file = patch.patch_files().next().unwrap();
        // Paths differ (a/file.txt vs b/file.txt), so shows arrow
        assert_eq!(file.display_name(), "a/file.txt → b/file.txt");
    }
}