Skip to main content

griz_core/
patch.rs

1//! Parses Codex patch text into operations.
2//!
3//! The format agents already write fluently:
4//!
5//! ```text
6//! *** Begin Patch
7//! *** Add File: path
8//! +line
9//! *** Delete File: path
10//! *** Update File: path
11//! *** Move to: new/path
12//! @@ optional line that precedes the hunk
13//!  context
14//! -removed
15//! +added
16//! *** End Patch
17//! ```
18//!
19//! Each hunk becomes a whole-line anchored replacement, so it inherits the
20//! matching ladder, uniqueness rule, and nearest-text reporting of every other
21//! operation. Several blocks for one file simply plan in sequence.
22
23use crate::{Anchor, Occurrence, Op};
24use std::path::{Path, PathBuf};
25
26/// Why patch text could not be parsed.
27#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
28#[error("patch line {line}: {message}")]
29pub struct PatchError {
30    /// 1-based line in the patch text.
31    pub line: usize,
32    /// What is wrong.
33    pub message: String,
34}
35
36#[derive(Default)]
37struct Hunk {
38    header: Option<String>,
39    old: Vec<String>,
40    new: Vec<String>,
41}
42
43enum Block {
44    Add {
45        path: PathBuf,
46        lines: Vec<String>,
47    },
48    Delete {
49        path: PathBuf,
50    },
51    Update {
52        path: PathBuf,
53        to: Option<PathBuf>,
54        hunks: Vec<Hunk>,
55    },
56}
57
58/// Parses patch text into operations, resolving each path with `resolve`.
59///
60/// Several patch documents may follow one another, each its own
61/// `*** Begin Patch` … `*** End Patch` pair, so a program can concatenate
62/// what it built separately.
63///
64/// # Errors
65/// Returns the first line that does not fit the format.
66pub fn parse_patch(text: &str, resolve: &dyn Fn(&str) -> PathBuf) -> Result<Vec<Op>, PatchError> {
67    let mut lines = text.lines().enumerate().peekable();
68    let begins = lines
69        .next()
70        .is_some_and(|(_, line)| line.trim() == "*** Begin Patch");
71    if !begins {
72        return Err(error(0, "patch must start with `*** Begin Patch`"));
73    }
74    let mut blocks = Vec::new();
75    while let Some((at, line)) = lines.next() {
76        let line = line.trim_end();
77        if line == "*** End Patch" && !another_document(&mut lines)? {
78            return Ok(blocks.into_iter().flat_map(to_ops).collect());
79        }
80        if line == "*** End Patch" {
81            continue;
82        }
83        let block = if let Some(path) = line.strip_prefix("*** Add File: ") {
84            Block::Add {
85                path: resolve(path.trim()),
86                lines: Vec::new(),
87            }
88        } else if let Some(path) = line.strip_prefix("*** Delete File: ") {
89            Block::Delete {
90                path: resolve(path.trim()),
91            }
92        } else if let Some(path) = line.strip_prefix("*** Update File: ") {
93            Block::Update {
94                path: resolve(path.trim()),
95                to: None,
96                hunks: Vec::new(),
97            }
98        } else {
99            return Err(error(at, &format!("unexpected line `{line}`")));
100        };
101        blocks.push(block);
102        let block = blocks.last_mut().ok_or_else(|| error(at, "no block"))?;
103        while let Some((at, body)) = lines.next_if(|(_, next)| {
104            !next.starts_with("*** ")
105                || next.starts_with("*** Move to: ")
106                || next.starts_with("*** End of File")
107        }) {
108            body_line(block, at, body, resolve)?;
109        }
110    }
111    Err(error(
112        text.lines().count(),
113        "patch must end with `*** End Patch`",
114    ))
115}
116
117/// Whether another patch document follows, consuming its `*** Begin Patch`
118/// and any blank lines before it. Anything else after a document ends is an
119/// error, so stray text is never silently dropped.
120fn another_document<'a, I>(lines: &mut std::iter::Peekable<I>) -> Result<bool, PatchError>
121where
122    I: Iterator<Item = (usize, &'a str)>,
123{
124    while let Some(&(at, line)) = lines.peek() {
125        let line = line.trim();
126        if line.is_empty() {
127            lines.next();
128            continue;
129        }
130        if line == "*** Begin Patch" {
131            lines.next();
132            return Ok(true);
133        }
134        return Err(error(at, "text after `*** End Patch`"));
135    }
136    Ok(false)
137}
138
139fn body_line(
140    block: &mut Block,
141    at: usize,
142    body: &str,
143    resolve: &dyn Fn(&str) -> PathBuf,
144) -> Result<(), PatchError> {
145    match block {
146        Block::Add { lines, .. } => {
147            let line = body
148                .strip_prefix('+')
149                .ok_or_else(|| error(at, "added file lines must start with `+`"))?;
150            lines.push(line.to_string());
151            Ok(())
152        }
153        Block::Delete { .. } => Err(error(at, "a deleted file has no body")),
154        Block::Update { to, hunks, .. } => update_line(to, hunks, (at, body), resolve),
155    }
156}
157
158fn update_line(
159    to: &mut Option<PathBuf>,
160    hunks: &mut Vec<Hunk>,
161    (at, body): (usize, &str),
162    resolve: &dyn Fn(&str) -> PathBuf,
163) -> Result<(), PatchError> {
164    if let Some(path) = body.strip_prefix("*** Move to: ") {
165        *to = Some(resolve(path.trim()));
166        return Ok(());
167    }
168    if body.starts_with("*** End of File") {
169        return Ok(());
170    }
171    if let Some(header) = body.strip_prefix("@@") {
172        let header = header.trim();
173        hunks.push(Hunk {
174            header: (!header.is_empty()).then(|| header.to_string()),
175            ..Hunk::default()
176        });
177        return Ok(());
178    }
179    if hunks.is_empty() {
180        hunks.push(Hunk::default());
181    }
182    let hunk = hunks.last_mut().ok_or_else(|| error(at, "no hunk"))?;
183    match body.chars().next() {
184        Some('+') => hunk.new.push(body[1..].to_string()),
185        Some('-') => hunk.old.push(body[1..].to_string()),
186        Some(' ') => {
187            hunk.old.push(body[1..].to_string());
188            hunk.new.push(body[1..].to_string());
189        }
190        None => {
191            hunk.old.push(String::new());
192            hunk.new.push(String::new());
193        }
194        Some(_) => {
195            return Err(error(
196                at,
197                &format!("hunk line must start with ` `, `+`, or `-`: `{body}`"),
198            ));
199        }
200    }
201    Ok(())
202}
203
204fn to_ops(block: Block) -> Vec<Op> {
205    match block {
206        Block::Add { path, lines } => vec![Op::Create {
207            path,
208            text: joined(&lines),
209            overwrite: false,
210            expect_hash: None,
211        }],
212        Block::Delete { path } => vec![Op::Delete {
213            path,
214            expect_hash: None,
215        }],
216        Block::Update { path, to, hunks } => {
217            let mut ops: Vec<Op> = hunks
218                .into_iter()
219                .filter(|hunk| hunk.old != hunk.new)
220                .map(|hunk| hunk_op(&path, hunk))
221                .collect();
222            if let Some(to) = to {
223                ops.push(Op::Move {
224                    path,
225                    to,
226                    expect_hash: None,
227                });
228            }
229            ops
230        }
231    }
232}
233
234fn hunk_op(path: &Path, hunk: Hunk) -> Op {
235    if hunk.old.is_empty() {
236        // Pure additions: after the header line, or at the end of the file.
237        let (anchor, text) = match hunk.header {
238            Some(header) => (header, format!("\n{}", hunk.new.join("\n"))),
239            None => (String::new(), joined(&hunk.new)),
240        };
241        return Op::Insert {
242            path: path.to_path_buf(),
243            anchor: Anchor {
244                text: anchor,
245                after: None,
246                whole_lines: true,
247            },
248            after: true,
249            text,
250            expect_hash: None,
251        };
252    }
253    Op::Replace {
254        path: path.to_path_buf(),
255        find: Some(Anchor {
256            text: hunk.old.join("\n"),
257            after: hunk.header,
258            whole_lines: true,
259        }),
260        range: None,
261        pattern: None,
262        replace: hunk.new.join("\n"),
263        occurrence: Occurrence::Unique,
264        target: None,
265        expect_hash: None,
266    }
267}
268
269fn joined(lines: &[String]) -> String {
270    let mut text = lines.join("\n");
271    text.push('\n');
272    text
273}
274
275fn error(line: usize, message: &str) -> PatchError {
276    PatchError {
277        line: line + 1,
278        message: message.to_string(),
279    }
280}