lemming 0.1.0

A patch editor
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
use std::borrow::Cow;
use std::fmt;

/// A complete patch summarizing the differences between two files
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Patch<'a> {
    /// The file information of the `-` side of the diff, line prefix: `---`
    pub old: File<'a>,
    /// The file information of the `+` side of the diff, line prefix: `+++`
    pub new: File<'a>,
    /// hunks of differences; each hunk shows one area where the files differ
    pub hunks: Vec<Hunk<'a>>,
    /// true if the last line of the file ends in a newline character
    ///
    /// This will only be false if at the end of the patch we encounter the text:
    /// `\ No newline at end of file`
    pub end_newline: bool,
}

impl<'a> fmt::Display for Patch<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Display implementations typically hold up the invariant that there is no trailing
        // newline. This isn't enforced, but it allows them to work well with `println!`

        write!(f, "--- {}", self.old)?;
        write!(f, "\n+++ {}", self.new)?;
        for hunk in &self.hunks {
            write!(f, "\n{}", hunk)?;
        }
        if !self.end_newline {
            write!(f, "\n\\ No newline at end of file")?;
        }
        Ok(())
    }
}

impl<'a> Patch<'a> {
    #[allow(clippy::tabs_in_doc_comments)]
    /// Attempt to parse a patch from the given string.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), patch::ParseError<'static>> {
    /// # use patch::Patch;
    /// let sample = "\
    /// --- lao	2002-02-21 23:30:39.942229878 -0800
    /// +++ tzu	2002-02-21 23:30:50.442260588 -0800
    /// @@ -1,7 +1,6 @@
    /// -The Way that can be told of is not the eternal Way;
    /// -The name that can be named is not the eternal name.
    ///  The Nameless is the origin of Heaven and Earth;
    /// -The Named is the mother of all things.
    /// +The named is the mother of all things.
    /// +
    ///  Therefore let there always be non-being,
    ///  so we may see their subtlety,
    ///  And let there always be being,
    /// @@ -9,3 +8,6 @@
    ///  The two are the same,
    ///  But after they are produced,
    ///  they have different names.
    /// +They both may be called deep and profound.
    /// +Deeper and more profound,
    /// +The door of all subtleties!
    /// \\ No newline at end of file\n";
    ///
    /// let patch = Patch::from_single(sample)?;
    /// assert_eq!(&patch.old.path, "lao");
    /// assert_eq!(&patch.new.path, "tzu");
    /// assert_eq!(patch.end_newline, false);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_single(s: &'a str) -> Result<Self, ParseError<'a>> {
        parse_single_patch(s)
    }
}

/// Check if a string needs to be quoted, and format it accordingly
fn maybe_escape_quote(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
    let quote = s
        .chars()
        .any(|ch| matches!(ch, ' ' | '\t' | '\r' | '\n' | '\"' | '\0' | '\\'));

    if quote {
        write!(f, "\"")?;
        for ch in s.chars() {
            match ch {
                '\0' => write!(f, r"\0")?,
                '\n' => write!(f, r"\n")?,
                '\r' => write!(f, r"\r")?,
                '\t' => write!(f, r"\t")?,
                '"' => write!(f, r#"\""#)?,
                '\\' => write!(f, r"\\")?,
                _ => write!(f, "{}", ch)?,
            }
        }
        write!(f, "\"")
    } else {
        write!(f, "{}", s)
    }
}

/// The file path and any additional info of either the old file or the new file
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct File<'a> {
    /// The parsed path or file name of the file
    ///
    /// Avoids allocation if at all possible. Only allocates if the file path is a quoted string
    /// literal. String literals are necessary in some cases, for example if the file path has
    /// spaces in it. These literals can contain escaped characters which are initially seen as
    /// groups of two characters by the parser (e.g. '\\' + 'n'). A newly allocated string is
    /// used to unescape those characters (e.g. "\\n" -> '\n').
    ///
    /// **Note:** While this string is typically a file path, this library makes no attempt to
    /// verify the format of that path. That means that **this field can potentially be any
    /// string**. You should verify it before doing anything that may be security-critical.
    pub path: Cow<'a, str>,
    /// Any additional information provided with the file path
    pub meta: Option<FileMetadata<'a>>,
}

impl<'a> fmt::Display for File<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        maybe_escape_quote(f, &self.path)?;
        if let Some(meta) = &self.meta {
            write!(f, "\t{}", meta)?;
        }
        Ok(())
    }
}

/// Additional metadata provided with the file path
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum FileMetadata<'a> {
    /// Any other string provided after the file path, e.g. git hash, unrecognized timestamp, etc.
    Other(Cow<'a, str>),
}

impl<'a> fmt::Display for FileMetadata<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FileMetadata::Other(data) => maybe_escape_quote(f, data),
        }
    }
}

/// One area where the files differ
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Hunk<'a> {
    /// The range of lines in the old file that this hunk represents
    pub old_range: Range,
    /// The range of lines in the new file that this hunk represents
    pub new_range: Range,
    /// Any trailing text after the hunk's range information
    pub range_hint: &'a str,
    /// Each line of text in the hunk, prefixed with the type of change it represents
    pub lines: Vec<Line<'a>>,
}

impl<'a> Hunk<'a> {
    /// A nicer way to access the optional hint
    pub fn hint(&self) -> Option<&str> {
        let h = self.range_hint.trim_start();
        if h.is_empty() { None } else { Some(h) }
    }
}

impl<'a> fmt::Display for Hunk<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "@@ -{} +{} @@{}",
            self.old_range, self.new_range, self.range_hint
        )?;

        for line in &self.lines {
            write!(f, "\n{}", line)?;
        }

        Ok(())
    }
}

/// A range of lines in a given file
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Range {
    /// The start line of the chunk in the old or new file
    pub start: u64,
    /// The chunk size (number of lines) in the old or new file
    pub count: u64,
}

impl fmt::Display for Range {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{},{}", self.start, self.count)
    }
}

/// A line of the old file, new file, or both
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Line<'a> {
    /// A line added to the old file in the new file
    Add(&'a str),
    /// A line removed from the old file in the new file
    Remove(&'a str),
    /// A line provided for context in the diff (unchanged); from both the old and the new file
    Context(&'a str),
}

impl<'a> fmt::Display for Line<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Line::Add(line) => write!(f, "+{}", line),
            Line::Remove(line) => write!(f, "-{}", line),
            Line::Context(line) => write!(f, " {}", line),
        }
    }
}

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

//     #[test]
//     fn test_hint_helper() {
//         let mut h = Hunk {
//             old_range: Range { start: 0, count: 0 },
//             new_range: Range { start: 0, count: 0 },
//             range_hint: "",
//             lines: vec![],
//         };
//         for (input, expected) in vec![
//             ("", None),
//             (" ", None),
//             ("  ", None),
//             ("x", Some("x")),
//             (" x", Some("x")),
//             ("x ", Some("x ")),
//             (" x ", Some("x ")),
//             ("  abc def ", Some("abc def ")),
//         ] {
//             h.range_hint = input;
//             assert_eq!(h.hint(), expected);
//         }
//     }
// }

use std::error::Error;

use nom::*;
use nom::{
    branch::alt,
    bytes::complete::{is_not, tag, take_until},
    character::complete::{char, digit1, line_ending, none_of, not_line_ending, one_of},
    combinator::{map, not, opt},
    multi::{many0, many1},
    sequence::{delimited, preceded, terminated, tuple},
};

type Input<'a> = Span<&'a str>;

/// Type returned when an error occurs while parsing a patch
#[derive(Debug, Clone)]
pub struct ParseError<'a> {
    /// The line where the parsing error occurred
    pub line: u32,
    /// The offset within the input where the parsing error occurred
    pub offset: usize,
    /// The failed input
    pub fragment: &'a str,
    /// The actual parsing error
    pub kind: nom::error::ErrorKind,
}

#[doc(hidden)]
impl<'a> From<nom::Err<nom::error::Error<Input<'a>>>> for ParseError<'a> {
    fn from(err: nom::Err<nom::error::Error<Input<'a>>>) -> Self {
        match err {
            nom::Err::Incomplete(_) => unreachable!("bug: parser should not return incomplete"),
            // Unify both error types because at this point the error is not recoverable
            nom::Err::Error(error) | nom::Err::Failure(error) => Self {
                line: error.input.location_line(),
                offset: error.input.location_offset(),
                fragment: error.input.fragment(),
                kind: error.code,
            },
        }
    }
}

impl<'a> std::fmt::Display for ParseError<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Line {}: Error while parsing: {}",
            self.line, self.fragment
        )
    }
}

impl<'a> Error for ParseError<'a> {
    fn description(&self) -> &str {
        self.kind.description()
    }
}

fn consume_content_line(input: Input<'_>) -> IResult<Input<'_>, &str> {
    let (input, raw) = terminated(not_line_ending, line_ending)(input)?;
    Ok((input, raw.fragment()))
}

pub(crate) fn parse_single_patch(s: &str) -> Result<Patch, ParseError<'_>> {
    let (remaining_input, patch) = patch(Input::new(s))?;
    // Parser should return an error instead of producing remaining input
    assert!(
        remaining_input.fragment().is_empty(),
        "bug: failed to parse entire input. \
        Remaining: '{}'",
        remaining_input.fragment()
    );
    Ok(patch)
}

fn patch(input: Input<'_>) -> IResult<Input<'_>, Patch> {
    let (input, files) = headers(input)?;
    let (input, hunks) = chunks(input)?;
    let (input, no_newline_indicator) = no_newline_indicator(input)?;
    // Ignore trailing empty lines produced by some diff programs
    let (input, _) = many0(line_ending)(input)?;

    let (old, new) = files;
    Ok((
        input,
        Patch {
            old,
            new,
            hunks,
            end_newline: !no_newline_indicator,
        },
    ))
}

// Header lines
fn headers(input: Input<'_>) -> IResult<Input<'_>, (File, File)> {
    // Ignore any preamble lines in produced diffs
    let (input, _) = take_until("---")(input)?;
    let (input, _) = tag("--- ")(input)?;
    let (input, oldfile) = header_line_content(input)?;
    let (input, _) = line_ending(input)?;
    let (input, _) = tag("+++ ")(input)?;
    let (input, newfile) = header_line_content(input)?;
    let (input, _) = line_ending(input)?;
    Ok((input, (oldfile, newfile)))
}

fn header_line_content(input: Input<'_>) -> IResult<Input<'_>, File<'_>> {
    let (input, filename) = filename(input)?;
    let (input, after) = opt(preceded(char('\t'), file_metadata))(input)?;

    Ok((
        input,
        File {
            path: filename,
            meta: after.and_then(|after| match after {
                Cow::Borrowed("") => None,
                Cow::Borrowed("\t") => None,
                _ => Some(
                    DateTime::parse_from_str(after.as_ref(), "%F %T%.f %z")
                        .or_else(|_| DateTime::parse_from_str(after.as_ref(), "%F %T %z"))
                        .ok()
                        .map_or_else(|| FileMetadata::Other(after), FileMetadata::DateTime),
                ),
            }),
        },
    ))
}

// Hunks of the file differences
fn chunks(input: Input<'_>) -> IResult<Input<'_>, Vec<Hunk<'_>>> {
    many1(chunk)(input)
}

fn chunk(input: Input<'_>) -> IResult<Input<'_>, Hunk<'_>> {
    let (input, ranges) = chunk_header(input)?;
    let (input, lines) = many1(chunk_line)(input)?;

    let (old_range, new_range, range_hint) = ranges;
    Ok((
        input,
        Hunk {
            old_range,
            new_range,
            range_hint,
            lines,
        },
    ))
}

fn chunk_header(input: Input<'_>) -> IResult<Input<'_>, (Range, Range, &'_ str)> {
    let (input, _) = tag("@@ -")(input)?;
    let (input, old_range) = range(input)?;
    let (input, _) = tag(" +")(input)?;
    let (input, new_range) = range(input)?;
    let (input, _) = tag(" @@")(input)?;

    // Save hint provided after @@ (git sometimes adds this)
    let (input, range_hint) = not_line_ending(input)?;
    let (input, _) = line_ending(input)?;
    Ok((input, (old_range, new_range, &range_hint)))
}

fn range(input: Input<'_>) -> IResult<Input<'_>, Range> {
    let (input, start) = u64_digit(input)?;
    let (input, count) = opt(preceded(char(','), u64_digit))(input)?;
    let count = count.unwrap_or(1);
    Ok((input, Range { start, count }))
}

fn u64_digit(input: Input<'_>) -> IResult<Input<'_>, u64> {
    let (input, digits) = digit1(input)?;
    let num = digits.fragment().parse::<u64>().unwrap();
    Ok((input, num))
}

// Looks for lines starting with + or - or space, but not +++ or ---. Not a foolproof check.
//
// For example, if someone deletes a line that was using the pre-decrement (--) operator or adds a
// line that was using the pre-increment (++) operator, this will fail.
//
// Example where this doesn't work:
//
// --- main.c
// +++ main.c
// @@ -1,4 +1,7 @@
// +#include<stdio.h>
// +
//  int main() {
//  double a;
// --- a;
// +++ a;
// +printf("%d\n", a);
//  }
//
// We will fail to parse this entire diff.
//
// By checking for `+++ ` instead of just `+++`, we add at least a little more robustness because
// we know that people typically write `++a`, not `++ a`. That being said, this is still not enough
// to guarantee correctness in all cases.
//
//FIXME: Use the ranges in the chunk header to figure out how many chunk lines to parse. Will need
// to figure out how to count in nom more robustly than many1!(). Maybe using switch!()?
//FIXME: The test_parse_triple_plus_minus_hack test will no longer panic when this is fixed.
fn chunk_line(input: Input<'_>) -> IResult<Input<'_>, Line> {
    alt((
        map(
            preceded(tuple((char('+'), not(tag("++ ")))), consume_content_line),
            Line::Add,
        ),
        map(
            preceded(tuple((char('-'), not(tag("-- ")))), consume_content_line),
            Line::Remove,
        ),
        map(preceded(char(' '), consume_content_line), Line::Context),
    ))(input)
}

// Trailing newline indicator
fn no_newline_indicator(input: Input<'_>) -> IResult<Input<'_>, bool> {
    map(
        opt(terminated(
            tag("\\ No newline at end of file"),
            opt(line_ending),
        )),
        |matched| matched.is_some(),
    )(input)
}

fn filename(input: Input<'_>) -> IResult<Input<'_>, Cow<str>> {
    alt((quoted, bare))(input)
}

fn file_metadata(input: Input<'_>) -> IResult<Input<'_>, Cow<str>> {
    alt((
        quoted,
        map(not_line_ending, |data: Input<'_>| {
            Cow::Borrowed(*data.fragment())
        }),
    ))(input)
}

fn quoted(input: Input<'_>) -> IResult<Input<'_>, Cow<str>> {
    delimited(char('\"'), unescaped_str, char('\"'))(input)
}

fn bare(input: Input<'_>) -> IResult<Input<'_>, Cow<str>> {
    map(is_not("\t\r\n"), |data: Input<'_>| {
        Cow::Borrowed(*data.fragment())
    })(input)
}

fn unescaped_str(input: Input<'_>) -> IResult<Input<'_>, Cow<str>> {
    let (input, raw) = many1(alt((unescaped_char, escaped_char)))(input)?;
    Ok((input, raw.into_iter().collect::<Cow<str>>()))
}

// Parses an unescaped character
fn unescaped_char(input: Input<'_>) -> IResult<Input<'_>, char> {
    none_of("\0\n\r\t\\\"")(input)
}

// Parses an escaped character and returns its unescaped equivalent
fn escaped_char(input: Input<'_>) -> IResult<Input<'_>, char> {
    map(preceded(char('\\'), one_of(r#"0nrt"\"#)), |ch| match ch {
        '0' => '\0',
        'n' => '\n',
        'r' => '\r',
        't' => '\t',
        '"' => '"',
        '\\' => '\\',
        _ => unreachable!(),
    })(input)
}

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

//     use pretty_assertions::assert_eq;

//     type ParseResult<'a, T> = Result<T, nom::Err<nom::error::Error<Input<'a>>>>;

//     // Using a macro instead of a function so that error messages cite the most helpful line number
//     macro_rules! test_parser {
//         ($parser:ident($input:expr) -> @($expected_remaining_input:expr, $expected:expr $(,)*)) => {
//             let (remaining_input, result) = $parser(Input::new($input))?;
//             assert_eq!(*remaining_input.fragment(), $expected_remaining_input,
//                 "unexpected remaining input after parse");
//             assert_eq!(result, $expected);
//         };
//         ($parser:ident($input:expr) -> $expected:expr) => {
//             test_parser!($parser($input) -> @("", $expected));
//         };
//     }

//     #[test]
//     fn test_unescape() -> ParseResult<'static, ()> {
//         test_parser!(unescaped_str("file \\\"name\\\"") -> "file \"name\"".to_string());
//         Ok(())
//     }

//     #[test]
//     fn test_quoted() -> ParseResult<'static, ()> {
//         test_parser!(quoted("\"file name\"") -> "file name".to_string());
//         Ok(())
//     }

//     #[test]
//     fn test_bare() -> ParseResult<'static, ()> {
//         test_parser!(bare("file-name ") -> @("", "file-name ".to_string()));
//         test_parser!(bare("file-name\t") -> @("\t", "file-name".to_string()));
//         test_parser!(bare("file-name\n") -> @("\n", "file-name".to_string()));
//         Ok(())
//     }

//     #[test]
//     fn test_filename() -> ParseResult<'static, ()> {
//         // bare
//         test_parser!(filename("asdf\t") -> @("\t", "asdf".to_string()));

//         // quoted
//         test_parser!(filename(r#""a/My Project/src/foo.rs" "#) -> @(" ", "a/My Project/src/foo.rs".to_string()));
//         test_parser!(filename(r#""\"asdf\" fdsh \\\t\r" "#) -> @(" ", "\"asdf\" fdsh \\\t\r".to_string()));
//         test_parser!(filename(r#""a s\"\nd\0f" "#) -> @(" ", "a s\"\nd\0f".to_string()));
//         Ok(())
//     }

//     #[test]
//     fn test_header_line_contents() -> ParseResult<'static, ()> {
//         test_parser!(header_line_content("lao\n") -> @("\n", File {
//             path: "lao".into(),
//             meta: None,
//         }));

//         test_parser!(header_line_content("lao\t2002-02-21 23:30:39.942229878 -0800\n") -> @(
//             "\n",
//             File {
//                 path: "lao".into(),
//                 meta: Some(FileMetadata::DateTime(
//                     DateTime::parse_from_rfc3339("2002-02-21T23:30:39.942229878-08:00").unwrap()
//                 )),
//             },
//         ));

//         test_parser!(header_line_content("lao\t2002-02-21 23:30:39 -0800\n") -> @(
//             "\n",
//             File {
//                 path: "lao".into(),
//                 meta: Some(FileMetadata::DateTime(
//                     DateTime::parse_from_rfc3339("2002-02-21T23:30:39-08:00").unwrap()
//                 )),
//             },
//         ));

//         test_parser!(header_line_content("lao\t08f78e0addd5bf7b7aa8887e406493e75e8d2b55\n") -> @(
//             "\n",
//             File {
//                 path: "lao".into(),
//                 meta: Some(FileMetadata::Other("08f78e0addd5bf7b7aa8887e406493e75e8d2b55".into()))
//             },
//         ));
//         Ok(())
//     }

//     #[test]
//     fn test_headers() -> ParseResult<'static, ()> {
//         let sample = "\
// --- lao	2002-02-21 23:30:39.942229878 -0800
// +++ tzu	2002-02-21 23:30:50.442260588 -0800\n";
//         test_parser!(headers(sample) -> (
//             File {
//                 path: "lao".into(),
//                 meta: Some(FileMetadata::DateTime(
//                     DateTime::parse_from_rfc3339("2002-02-21T23:30:39.942229878-08:00").unwrap()
//                 )),
//             },
//             File {
//                 path: "tzu".into(),
//                 meta: Some(FileMetadata::DateTime(
//                     DateTime::parse_from_rfc3339("2002-02-21T23:30:50.442260588-08:00").unwrap()
//                 )),
//             },
//         ));

//         let sample2 = "\
// --- lao
// +++ tzu\n";
//         test_parser!(headers(sample2) -> (
//             File {path: "lao".into(), meta: None},
//             File {path: "tzu".into(), meta: None},
//         ));

//         let sample2b = "\
// --- lao
// +++ tzu	\n";
//         test_parser!(headers(sample2b) -> (
//             File {path: "lao".into(), meta: None},
//             File {path: "tzu".into(), meta: None},
//         ));

//         let sample3 = "\
// --- lao	08f78e0addd5bf7b7aa8887e406493e75e8d2b55
// +++ tzu	e044048282ce75186ecc7a214fd3d9ba478a2816\n";
//         test_parser!(headers(sample3) -> (
//             File {
//                 path: "lao".into(),
//                 meta: Some(FileMetadata::Other("08f78e0addd5bf7b7aa8887e406493e75e8d2b55".into())),
//             },
//             File {
//                 path: "tzu".into(),
//                 meta: Some(FileMetadata::Other("e044048282ce75186ecc7a214fd3d9ba478a2816".into())),
//             },
//         ));
//         Ok(())
//     }

//     #[test]
//     fn test_headers_crlf() -> ParseResult<'static, ()> {
//         let sample = "\
// --- lao	2002-02-21 23:30:39.942229878 -0800\r
// +++ tzu	2002-02-21 23:30:50.442260588 -0800\r\n";
//         test_parser!(headers(sample) -> (
//             File {
//                 path: "lao".into(),
//                 meta: Some(FileMetadata::DateTime(
//                     DateTime::parse_from_rfc3339("2002-02-21T23:30:39.942229878-08:00").unwrap()
//                 )),
//             },
//             File {
//                 path: "tzu".into(),
//                 meta: Some(FileMetadata::DateTime(
//                     DateTime::parse_from_rfc3339("2002-02-21T23:30:50.442260588-08:00").unwrap()
//                 )),
//             },
//         ));
//         Ok(())
//     }

//     #[test]
//     fn test_range() -> ParseResult<'static, ()> {
//         test_parser!(range("1,7") -> Range { start: 1, count: 7 });

//         test_parser!(range("2") -> Range { start: 2, count: 1 });
//         Ok(())
//     }

//     #[test]
//     fn test_chunk_header() -> ParseResult<'static, ()> {
//         test_parser!(chunk_header("@@ -1,7 +1,6 @@ foo bar\n") -> (
//             Range { start: 1, count: 7 },
//             Range { start: 1, count: 6 },
//             " foo bar",
//         ));
//         Ok(())
//     }

//     #[test]
//     fn test_chunk() -> ParseResult<'static, ()> {
//         let sample = "\
// @@ -1,7 +1,6 @@
// -The Way that can be told of is not the eternal Way;
// -The name that can be named is not the eternal name.
//  The Nameless is the origin of Heaven and Earth;
// -The Named is the mother of all things.
// +The named is the mother of all things.
// +
//  Therefore let there always be non-being,
//    so we may see their subtlety,
//  And let there always be being,\n";
//         let expected = Hunk {
//             old_range: Range { start: 1, count: 7 },
//             new_range: Range { start: 1, count: 6 },
//             range_hint: "",
//             lines: vec![
//                 Line::Remove("The Way that can be told of is not the eternal Way;"),
//                 Line::Remove("The name that can be named is not the eternal name."),
//                 Line::Context("The Nameless is the origin of Heaven and Earth;"),
//                 Line::Remove("The Named is the mother of all things."),
//                 Line::Add("The named is the mother of all things."),
//                 Line::Add(""),
//                 Line::Context("Therefore let there always be non-being,"),
//                 Line::Context("  so we may see their subtlety,"),
//                 Line::Context("And let there always be being,"),
//             ],
//         };
//         test_parser!(chunk(sample) -> expected);
//         Ok(())
//     }

//     #[test]
//     fn test_patch() -> ParseResult<'static, ()> {
//         // https://www.gnu.org/software/diffutils/manual/html_node/Example-Unified.html
//         let sample = "\
// --- lao	2002-02-21 23:30:39.942229878 -0800
// +++ tzu	2002-02-21 23:30:50.442260588 -0800
// @@ -1,7 +1,6 @@
// -The Way that can be told of is not the eternal Way;
// -The name that can be named is not the eternal name.
//  The Nameless is the origin of Heaven and Earth;
// -The Named is the mother of all things.
// +The named is the mother of all things.
// +
//  Therefore let there always be non-being,
//    so we may see their subtlety,
//  And let there always be being,
// @@ -9,3 +8,6 @@
//  The two are the same,
//  But after they are produced,
//    they have different names.
// +They both may be called deep and profound.
// +Deeper and more profound,
// +The door of all subtleties!\n";

//         let expected = Patch {
//             old: File {
//                 path: "lao".into(),
//                 meta: Some(FileMetadata::DateTime(
//                     DateTime::parse_from_rfc3339("2002-02-21T23:30:39.942229878-08:00").unwrap(),
//                 )),
//             },
//             new: File {
//                 path: "tzu".into(),
//                 meta: Some(FileMetadata::DateTime(
//                     DateTime::parse_from_rfc3339("2002-02-21T23:30:50.442260588-08:00").unwrap(),
//                 )),
//             },
//             hunks: vec![
//                 Hunk {
//                     old_range: Range { start: 1, count: 7 },
//                     new_range: Range { start: 1, count: 6 },
//                     range_hint: "",
//                     lines: vec![
//                         Line::Remove("The Way that can be told of is not the eternal Way;"),
//                         Line::Remove("The name that can be named is not the eternal name."),
//                         Line::Context("The Nameless is the origin of Heaven and Earth;"),
//                         Line::Remove("The Named is the mother of all things."),
//                         Line::Add("The named is the mother of all things."),
//                         Line::Add(""),
//                         Line::Context("Therefore let there always be non-being,"),
//                         Line::Context("  so we may see their subtlety,"),
//                         Line::Context("And let there always be being,"),
//                     ],
//                 },
//                 Hunk {
//                     old_range: Range { start: 9, count: 3 },
//                     new_range: Range { start: 8, count: 6 },
//                     range_hint: "",
//                     lines: vec![
//                         Line::Context("The two are the same,"),
//                         Line::Context("But after they are produced,"),
//                         Line::Context("  they have different names."),
//                         Line::Add("They both may be called deep and profound."),
//                         Line::Add("Deeper and more profound,"),
//                         Line::Add("The door of all subtleties!"),
//                     ],
//                 },
//             ],
//             end_newline: true,
//         };

//         test_parser!(patch(sample) -> expected);

//         assert_eq!(format!("{}\n", expected), sample);

//         Ok(())
//     }
// }