patch_apply/
apply.rs

1use crate::{Line, Patch};
2
3/// Apply patch to the string from the input file source
4pub fn apply(input: String, patch: Patch) -> String {
5    let old_lines = input.lines().collect::<Vec<&str>>();
6    let mut out: Vec<&str> = vec![];
7    let mut old_line = 0;
8    for hunk in patch.hunks {
9        if old_lines.len() > 0 {
10            while old_line + 1 < hunk.old_range.start {
11                out.push(old_lines[old_line as usize]);
12                old_line += 1;
13            }
14        }
15        old_line += hunk.old_range.count;
16        for line in hunk.lines {
17            match line {
18                Line::Add(s) | Line::Context(s) => out.push(s),
19                Line::Remove(_) | Line::EndOfFile(_) => {}
20            }
21        }
22    }
23
24    let mut should_add_empty_line = false;
25
26    while old_line < old_lines.len() as u64 {
27        // TODO: fixme, this is not perfect
28        should_add_empty_line = true;
29        let line = old_lines[old_line as usize];
30        out.push(line);
31
32        old_line += 1;
33    }
34
35    if should_add_empty_line {
36        out.push("");
37    }
38
39    out.join("\n")
40}