Skip to main content

adk_devtools/
patch.rs

1//! The `*** Begin Patch` envelope `apply_patch` takes: its parser and its matcher
2//! (spec 3.1 §7.26, §10 D8).
3//!
4//! ```text
5//! *** Begin Patch
6//! *** Add File: docs/new.md
7//! +first line
8//! *** Delete File: old.txt
9//! *** Update File: src/lib.rs
10//! *** Move to: src/core.rs
11//! @@ fn main()
12//!  context line
13//! -removed line
14//! +added line
15//! *** End Patch
16//! ```
17//!
18//! A hunk is located by its context and removed lines, never by line numbers: an exact
19//! match first, then one that ignores trailing whitespace and line endings, and never an
20//! ambiguous or fuzzy one. A hunk with an `@@` anchor matches at the first place at or
21//! after the anchor line — the line equal to the anchor, or starting with it — and the
22//! first anchor of a hunk must name one line; a hunk without one must match exactly once
23//! after the previous hunk. Each line keeps its own line
24//! ending, and added lines take the file's prevailing one.
25
26use std::fmt::Write as _;
27
28/// A parsed patch: its file operations in order.
29///
30/// # Example
31///
32/// ```rust
33/// use adk_devtools::patch::{PatchOp, parse_patch};
34///
35/// let patch = parse_patch("*** Begin Patch\n*** Delete File: old.txt\n*** End Patch\n")?;
36/// assert_eq!(patch.ops, vec![PatchOp::Delete { path: "old.txt".into() }]);
37/// # Ok::<(), adk_devtools::patch::PatchError>(())
38/// ```
39#[derive(Clone, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct Patch {
42    /// The file operations, in the order the patch lists them.
43    pub ops: Vec<PatchOp>,
44}
45
46impl Patch {
47    /// Every path the patch names — the source and destination of a move included — in
48    /// order, as the headers write them. The harness policy reads these (spec 3.1 §7.26).
49    ///
50    /// # Example
51    ///
52    /// ```rust
53    /// let patch = adk_devtools::patch::parse_patch(
54    ///     "*** Begin Patch\n*** Update File: a.rs\n*** Move to: b.rs\n@@\n-x\n+y\n*** End Patch",
55    /// )?;
56    /// assert_eq!(patch.paths(), vec!["a.rs", "b.rs"]);
57    /// # Ok::<(), adk_devtools::patch::PatchError>(())
58    /// ```
59    pub fn paths(&self) -> Vec<&str> {
60        let mut out = Vec::new();
61        for op in &self.ops {
62            match op {
63                PatchOp::Add { path, .. } | PatchOp::Delete { path } => out.push(path.as_str()),
64                PatchOp::Update { path, move_to, .. } => {
65                    out.push(path.as_str());
66                    if let Some(to) = move_to {
67                        out.push(to.as_str());
68                    }
69                }
70            }
71        }
72        out
73    }
74}
75
76/// One file operation of a [`Patch`].
77#[derive(Clone, Debug, PartialEq, Eq)]
78#[non_exhaustive]
79pub enum PatchOp {
80    /// Create a file that does not exist.
81    Add {
82        /// The new file's path.
83        path: String,
84        /// Its content, each line ending in `\n`.
85        contents: String,
86    },
87    /// Delete a file.
88    Delete {
89        /// The file's path.
90        path: String,
91    },
92    /// Change a file, and optionally move it.
93    Update {
94        /// The file's path.
95        path: String,
96        /// Where the changed file goes instead, when it moves.
97        move_to: Option<String>,
98        /// The changes, in file order.
99        hunks: Vec<Hunk>,
100    },
101}
102
103/// One located change of an `Update File`.
104#[derive(Clone, Debug, PartialEq, Eq)]
105#[non_exhaustive]
106pub struct Hunk {
107    /// The `@@` anchor lines that precede the change, outermost first.
108    pub anchors: Vec<String>,
109    /// The change's lines.
110    pub lines: Vec<HunkLine>,
111    /// Whether the change must sit at the end of the file (`*** End of File`).
112    pub end_of_file: bool,
113}
114
115impl Hunk {
116    /// The lines the hunk expects in the file: context and removed lines.
117    fn old_lines(&self) -> Vec<&str> {
118        self.lines
119            .iter()
120            .filter_map(|line| match line {
121                HunkLine::Context(text) | HunkLine::Remove(text) => Some(text.as_str()),
122                HunkLine::Add(_) => None,
123            })
124            .collect()
125    }
126}
127
128/// A line of a [`Hunk`].
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub enum HunkLine {
131    /// Kept as the file has it.
132    Context(String),
133    /// Removed.
134    Remove(String),
135    /// Added.
136    Add(String),
137}
138
139/// Why a patch does not parse or does not apply.
140#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
141#[error("{0}")]
142pub struct PatchError(pub String);
143
144const BEGIN: &str = "*** Begin Patch";
145const END: &str = "*** End Patch";
146const ADD: &str = "*** Add File: ";
147const DELETE: &str = "*** Delete File: ";
148const UPDATE: &str = "*** Update File: ";
149const MOVE: &str = "*** Move to: ";
150const EOF_MARKER: &str = "*** End of File";
151
152/// Parses the `*** Begin Patch` envelope (spec 3.1 §7.26).
153///
154/// A shell heredoc around the envelope (`<<'EOF'` … `EOF`) is tolerated, since models
155/// trained on a shell-run `apply_patch` sometimes keep it. A `@@ -1,3 +1,4 @@` range header
156/// is read as an `@@` line without an anchor: the format has no line numbers.
157///
158/// # Errors
159///
160/// Returns a [`PatchError`] naming the line that does not fit the format.
161///
162/// # Example
163///
164/// ```rust
165/// use adk_devtools::patch::parse_patch;
166///
167/// let error = parse_patch("*** Update File: a.rs\n").unwrap_err();
168/// assert!(error.to_string().contains("*** Begin Patch"));
169/// ```
170pub fn parse_patch(text: &str) -> Result<Patch, PatchError> {
171    let mut lines: Vec<&str> =
172        text.trim().lines().map(|line| line.trim_end_matches('\r')).collect();
173    if lines.first().is_some_and(|first| first.trim_start().starts_with("<<")) && lines.len() >= 2 {
174        lines.remove(0);
175        lines.pop();
176    }
177    let mut lines = lines.into_iter().enumerate().peekable();
178    match lines.next() {
179        Some((_, first)) if first.trim() == BEGIN => {}
180        _ => {
181            return Err(PatchError(format!(
182                "a patch starts with the line '{BEGIN}' and ends with '{END}'"
183            )));
184        }
185    }
186    let mut ops = Vec::new();
187    let mut ended = false;
188    while let Some((index, line)) = lines.next() {
189        let number = index + 1;
190        let trimmed = line.trim();
191        if trimmed == END {
192            ended = true;
193            break;
194        }
195        if let Some(path) = header(line, ADD) {
196            let mut contents = String::new();
197            while let Some((_, next)) = lines.peek() {
198                if next.starts_with("***") {
199                    break;
200                }
201                let (index, next) = lines.next().unwrap_or_default();
202                let Some(text) = next.strip_prefix('+') else {
203                    return Err(PatchError(format!(
204                        "line {}: every line of an added file starts with '+'",
205                        index + 1
206                    )));
207                };
208                contents.push_str(text);
209                contents.push('\n');
210            }
211            ops.push(PatchOp::Add { path, contents });
212        } else if let Some(path) = header(line, DELETE) {
213            ops.push(PatchOp::Delete { path });
214        } else if let Some(path) = header(line, UPDATE) {
215            let move_to = match lines.peek() {
216                Some((_, next)) if header(next, MOVE).is_some() => {
217                    lines.next().and_then(|(_, next)| header(next, MOVE))
218                }
219                _ => None,
220            };
221            let mut hunks: Vec<Hunk> = Vec::new();
222            let mut current = Hunk { anchors: Vec::new(), lines: Vec::new(), end_of_file: false };
223            while let Some((_, next)) = lines.peek() {
224                let next = *next;
225                if next.trim() == EOF_MARKER {
226                    lines.next();
227                    current.end_of_file = true;
228                    continue;
229                }
230                if next.starts_with("***") {
231                    break;
232                }
233                let (index, next) = lines.next().unwrap_or_default();
234                if let Some(rest) = next.strip_prefix("@@") {
235                    if !current.lines.is_empty() {
236                        hunks.push(std::mem::replace(
237                            &mut current,
238                            Hunk { anchors: Vec::new(), lines: Vec::new(), end_of_file: false },
239                        ));
240                    }
241                    let anchor = rest.trim();
242                    if !anchor.is_empty() && !is_range_header(anchor) {
243                        current.anchors.push(anchor.to_string());
244                    }
245                    continue;
246                }
247                let line = match next.chars().next() {
248                    Some('+') => HunkLine::Add(next[1..].to_string()),
249                    Some('-') => HunkLine::Remove(next[1..].to_string()),
250                    Some(' ') => HunkLine::Context(next[1..].to_string()),
251                    // A blank line in a hunk is an empty context line.
252                    None => HunkLine::Context(String::new()),
253                    Some(_) => {
254                        return Err(PatchError(format!(
255                            "line {}: a line of an Update File hunk starts with ' ', '-' or \
256                             '+', or is an '@@' line; got: {next}",
257                            index + 1
258                        )));
259                    }
260                };
261                current.lines.push(line);
262            }
263            if !current.lines.is_empty() {
264                hunks.push(current);
265            }
266            if hunks.is_empty() && move_to.is_none() {
267                return Err(PatchError(format!("line {number}: '{line}' has no changes")));
268            }
269            ops.push(PatchOp::Update { path, move_to, hunks });
270        } else if trimmed.is_empty() {
271            continue;
272        } else {
273            return Err(PatchError(format!(
274                "line {number}: expected '{ADD}<path>', '{DELETE}<path>', '{UPDATE}<path>' or \
275                 '{END}'; got: {line}"
276            )));
277        }
278    }
279    if !ended {
280        return Err(PatchError(format!("the patch does not end with '{END}'")));
281    }
282    if ops.is_empty() {
283        return Err(PatchError("the patch changes no file".to_string()));
284    }
285    Ok(Patch { ops })
286}
287
288/// The path of a `prefix` header line, or `None` when `line` is not one.
289fn header(line: &str, prefix: &str) -> Option<String> {
290    let path = line.trim_start().strip_prefix(prefix)?.trim();
291    (!path.is_empty()).then(|| path.to_string())
292}
293
294/// Whether `anchor` is a unified-diff range header such as `-1,3 +1,4 @@`.
295fn is_range_header(anchor: &str) -> bool {
296    let mut parts = anchor.split_whitespace();
297    let range = |part: Option<&str>, sign: char| {
298        part.and_then(|part| part.strip_prefix(sign)).is_some_and(|numbers| {
299            !numbers.is_empty() && numbers.split(',').all(|n| n.parse::<u64>().is_ok())
300        })
301    };
302    range(parts.next(), '-') && range(parts.next(), '+')
303}
304
305/// A file split into lines, each with the line ending it had.
306struct Lines<'a> {
307    lines: Vec<(&'a str, &'a str)>,
308    /// The ending added lines take: the file's prevailing one.
309    eol: &'static str,
310}
311
312impl<'a> Lines<'a> {
313    fn split(text: &'a str) -> Self {
314        let mut lines = Vec::new();
315        let (mut crlf, mut lf) = (0usize, 0usize);
316        let mut rest = text;
317        while !rest.is_empty() {
318            match rest.find('\n') {
319                Some(end) => {
320                    let (line, eol) = if end > 0 && rest.as_bytes()[end - 1] == b'\r' {
321                        crlf += 1;
322                        (&rest[..end - 1], &rest[end - 1..=end])
323                    } else {
324                        lf += 1;
325                        (&rest[..end], &rest[end..=end])
326                    };
327                    lines.push((line, eol));
328                    rest = &rest[end + 1..];
329                }
330                None => {
331                    lines.push((rest, ""));
332                    rest = "";
333                }
334            }
335        }
336        Self { lines, eol: if crlf > lf { "\r\n" } else { "\n" } }
337    }
338}
339
340/// How two lines are compared: exactly, then ignoring trailing whitespace.
341#[derive(Clone, Copy)]
342enum Compare {
343    Exact,
344    TrailingWhitespace,
345}
346
347impl Compare {
348    fn eq(self, file: &str, patch: &str) -> bool {
349        match self {
350            Self::Exact => file == patch,
351            Self::TrailingWhitespace => file.trim_end() == patch.trim_end(),
352        }
353    }
354}
355
356/// Every start at or after `from` where `needle` matches the file under `compare`.
357fn matches_from(lines: &Lines<'_>, needle: &[&str], from: usize, compare: Compare) -> Vec<usize> {
358    if needle.is_empty() || needle.len() > lines.lines.len() {
359        return Vec::new();
360    }
361    (from..=lines.lines.len() - needle.len())
362        .filter(|start| {
363            needle
364                .iter()
365                .enumerate()
366                .all(|(offset, want)| compare.eq(lines.lines[start + offset].0, want))
367        })
368        .collect()
369}
370
371/// The anchor line at or after `from`: the line equal to the anchor, else equal ignoring
372/// surrounding whitespace, else starting with it (`@@ fn main()` names `fn main() {`).
373/// The first anchor of a hunk must name one line; a later one takes the first after it.
374fn find_anchor(
375    lines: &Lines<'_>,
376    anchor: &str,
377    from: usize,
378    unique: bool,
379) -> Result<usize, String> {
380    let wanted = anchor.trim();
381    let tests: [&dyn Fn(&str) -> bool; 3] =
382        [&|line| line == anchor, &|line| line.trim() == wanted, &|line| {
383            line.trim_start().starts_with(wanted)
384        }];
385    let mut found = Vec::new();
386    for test in tests {
387        found = (from..lines.lines.len()).filter(|&index| test(lines.lines[index].0)).collect();
388        if !found.is_empty() {
389            break;
390        }
391    }
392    match found.as_slice() {
393        [] => Err(format!("its anchor '@@ {anchor}' was not found")),
394        [one] => Ok(*one),
395        [first, ..] if !unique => Ok(*first),
396        many => Err(format!(
397            "its anchor '@@ {anchor}' occurs {} times (lines {}); add an outer anchor or more \
398             context",
399            many.len(),
400            many.iter().take(5).map(|index| (index + 1).to_string()).collect::<Vec<_>>().join(", ")
401        )),
402    }
403}
404
405/// Applies `hunks` to `text`, returning the new text (spec 3.1 §7.26).
406///
407/// # Errors
408///
409/// Returns a [`PatchError`] naming `path`, the hunk that does not apply, its lines and the
410/// nearest candidate lines in the file.
411///
412/// # Example
413///
414/// ```rust
415/// use adk_devtools::patch::{PatchOp, apply_hunks, parse_patch};
416///
417/// let patch = parse_patch("*** Begin Patch\n*** Update File: a.txt\n@@\n one\n-two\n+2\n*** End Patch")?;
418/// let PatchOp::Update { hunks, .. } = &patch.ops[0] else { unreachable!() };
419/// assert_eq!(apply_hunks("a.txt", "one\r\ntwo\r\n", hunks)?, "one\r\n2\r\n");
420/// # Ok::<(), adk_devtools::patch::PatchError>(())
421/// ```
422pub fn apply_hunks(path: &str, text: &str, hunks: &[Hunk]) -> Result<String, PatchError> {
423    let lines = Lines::split(text);
424    // Each hunk's replaced range in the original file, in order.
425    let mut edits: Vec<(usize, usize, &Hunk)> = Vec::new();
426    let mut cursor = 0usize;
427    for (number, hunk) in hunks.iter().enumerate() {
428        let fail = |why: String| {
429            PatchError(describe_failure(path, number + 1, hunks.len(), hunk, &lines, &why))
430        };
431        let mut from = cursor;
432        let mut anchored = false;
433        for (index, anchor) in hunk.anchors.iter().enumerate() {
434            from = find_anchor(&lines, anchor, from, index == 0).map_err(&fail)?;
435            anchored = true;
436        }
437        let old = hunk.old_lines();
438        let start = if old.is_empty() {
439            // A pure addition goes after its anchor line, or at the end of the file.
440            if anchored { from + 1 } else { lines.lines.len() }
441        } else {
442            let mut found = Vec::new();
443            for compare in [Compare::Exact, Compare::TrailingWhitespace] {
444                found = matches_from(&lines, &old, from, compare);
445                if hunk.end_of_file {
446                    found.retain(|start| start + old.len() == lines.lines.len());
447                }
448                if !found.is_empty() {
449                    break;
450                }
451            }
452            match found.as_slice() {
453                [] => {
454                    return Err(fail(if hunk.end_of_file {
455                        "its lines were not found at the end of the file".to_string()
456                    } else {
457                        "its lines were not found".to_string()
458                    }));
459                }
460                [one] => *one,
461                [first, ..] if anchored => *first,
462                many => {
463                    return Err(fail(format!(
464                        "its lines occur {} times (at lines {}); add an '@@' anchor or more \
465                         context so it matches once",
466                        many.len(),
467                        many.iter()
468                            .take(5)
469                            .map(|start| (start + 1).to_string())
470                            .collect::<Vec<_>>()
471                            .join(", ")
472                    )));
473                }
474            }
475        };
476        edits.push((start, start + old.len(), hunk));
477        cursor = start + old.len();
478    }
479
480    let mut out = String::with_capacity(text.len());
481    let mut position = 0usize;
482    let push = |out: &mut String, (line, eol): (&str, &str)| {
483        out.push_str(line);
484        out.push_str(eol);
485    };
486    for (start, end, hunk) in edits {
487        for &line in &lines.lines[position..start] {
488            push(&mut out, line);
489        }
490        // Inserting after a last line that had no ending gives it one.
491        if start == lines.lines.len()
492            && start > 0
493            && lines.lines[start - 1].1.is_empty()
494            && hunk.lines.iter().any(|line| matches!(line, HunkLine::Add(_)))
495        {
496            out.push_str(lines.eol);
497        }
498        let mut file_line = start;
499        for line in &hunk.lines {
500            match line {
501                HunkLine::Context(_) => {
502                    push(&mut out, lines.lines[file_line]);
503                    file_line += 1;
504                }
505                HunkLine::Remove(_) => file_line += 1,
506                HunkLine::Add(text) => {
507                    out.push_str(text);
508                    out.push_str(lines.eol);
509                }
510            }
511        }
512        debug_assert_eq!(file_line, end);
513        position = end;
514    }
515    for &line in &lines.lines[position..] {
516        push(&mut out, line);
517    }
518    Ok(out)
519}
520
521/// The failure message: the file, the hunk, its lines and the nearest candidate lines.
522fn describe_failure(
523    path: &str,
524    number: usize,
525    of: usize,
526    hunk: &Hunk,
527    lines: &Lines<'_>,
528    why: &str,
529) -> String {
530    const SHOWN: usize = 8;
531    let mut out = format!("hunk {number} of {of} for {path} does not apply: {why}.\nThe hunk:\n");
532    for anchor in &hunk.anchors {
533        let _ = writeln!(out, "  @@ {anchor}");
534    }
535    for line in hunk.lines.iter().take(SHOWN) {
536        let (sign, text) = match line {
537            HunkLine::Context(text) => (' ', text),
538            HunkLine::Remove(text) => ('-', text),
539            HunkLine::Add(text) => ('+', text),
540        };
541        let _ = writeln!(out, "  {sign}{text}");
542    }
543    if hunk.lines.len() > SHOWN {
544        let _ = writeln!(out, "  … {} more lines", hunk.lines.len() - SHOWN);
545    }
546    let old = hunk.old_lines();
547    let best = (0..lines.lines.len())
548        .map(|start| {
549            let score = old
550                .iter()
551                .enumerate()
552                .filter(|(offset, want)| {
553                    lines.lines.get(start + offset).is_some_and(|line| line.0.trim() == want.trim())
554                })
555                .count();
556            (score, start)
557        })
558        .filter(|(score, _)| *score > 0)
559        .max_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
560    match best {
561        Some((_, start)) => {
562            let _ = writeln!(out, "The nearest candidate in the file, from line {}:", start + 1);
563            for (index, line) in
564                lines.lines.iter().enumerate().skip(start).take(old.len().clamp(1, SHOWN))
565            {
566                let _ = writeln!(out, "  {:>5} | {}", index + 1, line.0);
567            }
568        }
569        None => out.push_str("No line of the file resembles the hunk; read the file again.\n"),
570    }
571    out.trim_end().to_string()
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577
578    fn update(patch: &str) -> Vec<Hunk> {
579        match parse_patch(patch).unwrap().ops.remove(0) {
580            PatchOp::Update { hunks, .. } => hunks,
581            other => panic!("{other:?}"),
582        }
583    }
584
585    #[test]
586    fn parses_every_operation() {
587        let patch = parse_patch(
588            "*** Begin Patch\n*** Add File: new.txt\n+a\n+b\n*** Delete File: old.txt\n\
589             *** Update File: src/a.rs\n*** Move to: src/b.rs\n@@ fn main()\n x\n-y\n+z\n\
590             *** End of File\n*** End Patch\n",
591        )
592        .unwrap();
593        assert_eq!(
594            patch.ops,
595            vec![
596                PatchOp::Add { path: "new.txt".into(), contents: "a\nb\n".into() },
597                PatchOp::Delete { path: "old.txt".into() },
598                PatchOp::Update {
599                    path: "src/a.rs".into(),
600                    move_to: Some("src/b.rs".into()),
601                    hunks: vec![Hunk {
602                        anchors: vec!["fn main()".into()],
603                        lines: vec![
604                            HunkLine::Context("x".into()),
605                            HunkLine::Remove("y".into()),
606                            HunkLine::Add("z".into()),
607                        ],
608                        end_of_file: true,
609                    }],
610                },
611            ]
612        );
613        assert_eq!(patch.paths(), vec!["new.txt", "old.txt", "src/a.rs", "src/b.rs"]);
614    }
615
616    #[test]
617    fn a_heredoc_wrapper_and_range_headers_are_tolerated() {
618        let hunks = update(
619            "<<'EOF'\n*** Begin Patch\n*** Update File: a\n@@ -1,2 +1,2 @@\n-x\n+y\n*** End Patch\nEOF",
620        );
621        assert!(hunks[0].anchors.is_empty());
622    }
623
624    #[test]
625    fn malformed_patches_name_the_problem() {
626        for (patch, says) in [
627            ("*** Update File: a\n", "starts with"),
628            ("*** Begin Patch\n*** Update File: a\n-x\n", "does not end"),
629            ("*** Begin Patch\n*** Add File: a\nno plus\n*** End Patch", "starts with '+'"),
630            ("*** Begin Patch\n*** Update File: a\n*** End Patch", "has no changes"),
631            ("*** Begin Patch\n*** Update File: a\n@@\nxyz\n*** End Patch", "starts with ' '"),
632            ("*** Begin Patch\n*** End Patch", "changes no file"),
633            ("*** Begin Patch\n*** Rename: a\n*** End Patch", "expected"),
634        ] {
635            let error = parse_patch(patch).unwrap_err().to_string();
636            assert!(error.contains(says), "{patch:?}: {error}");
637        }
638    }
639
640    #[test]
641    fn an_exact_match_applies_and_keeps_context_lines() {
642        let hunks =
643            update("*** Begin Patch\n*** Update File: f\n@@\n a\n-b\n+B\n c\n*** End Patch");
644        assert_eq!(apply_hunks("f", "a\nb\nc\nd\n", &hunks).unwrap(), "a\nB\nc\nd\n");
645    }
646
647    #[test]
648    fn trailing_whitespace_is_tolerated_and_the_file_keeps_its_own() {
649        let hunks = update("*** Begin Patch\n*** Update File: f\n@@\n a\n-b\n+B\n*** End Patch");
650        assert_eq!(apply_hunks("f", "a  \nb\t\nc\n", &hunks).unwrap(), "a  \nB\nc\n");
651    }
652
653    #[test]
654    fn leading_whitespace_is_not_tolerated() {
655        let hunks = update("*** Begin Patch\n*** Update File: f\n@@\n-b\n+B\n*** End Patch");
656        let error = apply_hunks("f", "  b\n", &hunks).unwrap_err().to_string();
657        assert!(error.contains("not found"), "{error}");
658        assert!(error.contains("nearest candidate"), "{error}");
659    }
660
661    #[test]
662    fn an_ambiguous_hunk_is_refused_and_an_anchor_settles_it() {
663        let file = "fn a() {\n    x\n}\nfn b() {\n    x\n}\n";
664        let hunks =
665            update("*** Begin Patch\n*** Update File: f\n@@\n-    x\n+    y\n*** End Patch");
666        let error = apply_hunks("f", file, &hunks).unwrap_err().to_string();
667        assert!(error.contains("occur 2 times"), "{error}");
668        let hunks = update(
669            "*** Begin Patch\n*** Update File: f\n@@ fn b() {\n-    x\n+    y\n*** End Patch",
670        );
671        assert_eq!(
672            apply_hunks("f", file, &hunks).unwrap(),
673            "fn a() {\n    x\n}\nfn b() {\n    y\n}\n"
674        );
675    }
676
677    #[test]
678    fn an_anchor_names_a_line_by_its_start_and_must_name_one() {
679        let file = "fn a() {\n    x\n}\nfn b() {\n    x\n}\n";
680        let hunks =
681            update("*** Begin Patch\n*** Update File: f\n@@ fn b()\n-    x\n+    y\n*** End Patch");
682        assert_eq!(
683            apply_hunks("f", file, &hunks).unwrap(),
684            "fn a() {\n    x\n}\nfn b() {\n    y\n}\n"
685        );
686        let hunks =
687            update("*** Begin Patch\n*** Update File: f\n@@ fn\n-    x\n+    y\n*** End Patch");
688        let error = apply_hunks("f", file, &hunks).unwrap_err().to_string();
689        assert!(error.contains("occurs 2 times"), "{error}");
690    }
691
692    #[test]
693    fn line_endings_are_kept_per_line() {
694        let hunks =
695            update("*** Begin Patch\n*** Update File: f\n@@\n a\n-b\n+B\n+C\n*** End Patch");
696        assert_eq!(apply_hunks("f", "a\r\nb\r\nc\n", &hunks).unwrap(), "a\r\nB\r\nC\r\nc\n");
697        assert_eq!(apply_hunks("f", "a\nb", &hunks).unwrap(), "a\nB\nC\n");
698    }
699
700    #[test]
701    fn hunks_apply_in_order_and_a_later_failure_names_its_hunk() {
702        let hunks =
703            update("*** Begin Patch\n*** Update File: f\n@@\n-a\n+A\n@@\n-c\n+C\n*** End Patch");
704        assert_eq!(apply_hunks("f", "a\nb\nc\n", &hunks).unwrap(), "A\nb\nC\n");
705        let error = apply_hunks("f", "a\nb\n", &hunks).unwrap_err().to_string();
706        assert!(error.starts_with("hunk 2 of 2 for f"), "{error}");
707    }
708
709    #[test]
710    fn end_of_file_hunks_match_only_at_the_end() {
711        let hunks = update(
712            "*** Begin Patch\n*** Update File: f\n@@\n-x\n+y\n*** End of File\n*** End Patch",
713        );
714        assert_eq!(apply_hunks("f", "x\nmid\nx\n", &hunks).unwrap(), "x\nmid\ny\n");
715    }
716
717    #[test]
718    fn pure_additions_go_after_the_anchor_or_at_the_end() {
719        let at_end = update("*** Begin Patch\n*** Update File: f\n@@\n+z\n*** End Patch");
720        assert_eq!(apply_hunks("f", "a\nb", &at_end).unwrap(), "a\nb\nz\n");
721        let anchored = update("*** Begin Patch\n*** Update File: f\n@@ a\n+z\n*** End Patch");
722        assert_eq!(apply_hunks("f", "a\nb\n", &anchored).unwrap(), "a\nz\nb\n");
723    }
724}