Skip to main content

vtcode_core/tools/editing/patch/
mod.rs

1use std::path::Path;
2
3use anyhow::anyhow;
4
5mod applicator;
6mod semantic;
7pub(crate) use applicator::inspect_and_render_patch_update;
8mod error;
9mod matcher;
10mod parser;
11mod path;
12
13#[doc(hidden)]
14pub use error::PatchError;
15
16/// Represents a single diff line inside a patch hunk.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum PatchLine {
19    Context(String),
20    Addition(String),
21    Removal(String),
22}
23
24impl PatchLine {
25    pub fn as_str(&self) -> &str {
26        match self {
27            PatchLine::Context(text) | PatchLine::Addition(text) | PatchLine::Removal(text) => text,
28        }
29    }
30}
31
32/// Represents a chunk of changes within an update operation.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct PatchChunk {
35    pub change_context: Option<String>,
36    pub lines: Vec<PatchLine>,
37    pub is_end_of_file: bool,
38}
39
40impl PatchChunk {
41    pub fn lines(&self) -> &[PatchLine] {
42        &self.lines
43    }
44
45    pub fn change_context(&self) -> Option<&str> {
46        self.change_context.as_deref()
47    }
48
49    pub fn is_end_of_file(&self) -> bool {
50        self.is_end_of_file
51    }
52
53    fn to_segments(&self) -> (Vec<String>, Vec<String>) {
54        let cap = self.lines.len();
55        let mut old_lines = Vec::with_capacity(cap);
56        let mut new_lines = Vec::with_capacity(cap);
57
58        for line in &self.lines {
59            match line {
60                PatchLine::Context(text) => {
61                    old_lines.push(text.clone());
62                    new_lines.push(text.clone());
63                }
64                PatchLine::Addition(text) => {
65                    new_lines.push(text.clone());
66                }
67                PatchLine::Removal(text) => {
68                    old_lines.push(text.clone());
69                }
70            }
71        }
72
73        (old_lines, new_lines)
74    }
75
76    fn has_old_lines(&self) -> bool {
77        self.lines
78            .iter()
79            .any(|line| matches!(line, PatchLine::Context(_) | PatchLine::Removal(_)))
80    }
81
82    pub fn parse_line_number(&self) -> Option<usize> {
83        let ctx = self.change_context()?;
84        // Format is typically: -old_start,old_count +new_start,new_count @@
85        let parts: Vec<&str> = ctx.split_whitespace().collect();
86        let old_part = if !parts.is_empty() && parts[0].starts_with('-') {
87            Some(parts[0])
88        } else if parts.len() >= 2 && parts[1].starts_with('-') {
89            Some(parts[1])
90        } else {
91            None
92        }?;
93
94        let range_str = old_part.strip_prefix('-')?;
95        let range_parts: Vec<&str> = range_str.split(',').collect();
96        let start_str = range_parts.first()?;
97        start_str.parse::<usize>().ok()
98    }
99}
100
101pub type PatchHunk = PatchChunk;
102
103/// Represents a patch operation.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum PatchOperation {
106    AddFile {
107        path: String,
108        content: String,
109    },
110    DeleteFile {
111        path: String,
112    },
113    UpdateFile {
114        path: String,
115        new_path: Option<String>,
116        chunks: Vec<PatchChunk>,
117    },
118}
119
120/// Represents a complete patch comprised of multiple operations.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct Patch {
123    operations: Vec<PatchOperation>,
124}
125
126impl Patch {
127    pub fn parse(input: &str) -> anyhow::Result<Self> {
128        let operations = parser::parse(input).map_err(|err| anyhow!(err))?;
129        Ok(Self { operations })
130    }
131
132    pub fn operations(&self) -> &[PatchOperation] {
133        &self.operations
134    }
135
136    pub fn is_empty(&self) -> bool {
137        self.operations.is_empty()
138    }
139
140    pub fn into_operations(self) -> Vec<PatchOperation> {
141        self.operations
142    }
143
144    pub async fn apply(&self, root: &Path) -> anyhow::Result<Vec<String>> {
145        applicator::apply(root, &self.operations).await.map_err(|err| anyhow!(err))
146    }
147}
148
149pub async fn render_patch_update_content(
150    source_path: &Path,
151    content: &str,
152    chunks: &[PatchChunk],
153    path: &str,
154) -> anyhow::Result<String> {
155    applicator::render_updated_content(source_path, content, chunks, path)
156        .await
157        .map_err(|err| anyhow!(err))
158}
159
160// ---------------------------------------------------------------------------
161// Shape detection primitives — single source of truth for "is this a VTE
162// patch?" / "is this a unified diff?" Used by tool routing, source-field
163// selection, and parse-error guidance. Replaces the previously duplicated
164// private `looks_like_patch_text` closures in `tool_intent` and `file_ops`.
165// ---------------------------------------------------------------------------
166
167/// Cheap shape check: does this text begin with the VT Code patch envelope
168/// (`*** Begin Patch`) or a bare file-operation header (`*** Update File:`,
169/// `*** Add File:`, `*** Delete File:`)? Used by tool routing and
170/// source-field selection to distinguish a real patch from raw file contents
171/// or a unified diff. Intentionally cheap (prefix-only) — it does **not**
172/// validate the full patch.
173#[must_use]
174pub fn looks_like_vte_patch(text: &str) -> bool {
175    let trimmed = text.trim_start();
176    trimmed.starts_with("*** Begin Patch")
177        || trimmed.starts_with("*** Update File:")
178        || trimmed.starts_with("*** Add File:")
179        || trimmed.starts_with("*** Delete File:")
180}
181
182/// Cheap shape check: does this text look like a standard unified diff
183/// (`diff --git` header, or a paired `--- `/`+++ ` file-header block)?
184/// Used to produce actionable error guidance when a model submits a
185/// git-style diff to `apply_patch` (which requires the `*** Begin Patch`
186/// envelope). VT Code patch format never uses `--- `/`+++ ` markers, so
187/// this will not false-positive on valid VTE patches.
188#[must_use]
189pub fn looks_like_unified_diff(text: &str) -> bool {
190    let trimmed = text.trim_start();
191    if trimmed.starts_with("diff --git") {
192        return true;
193    }
194    // Unified diffs always have a paired `--- ` / `+++ ` file-header block.
195    // Scan the first dozen lines; the pair usually appears within the first 2-3.
196    let mut saw_old = false;
197    for line in trimmed.lines().take(12) {
198        let lt = line.trim_start();
199        if lt.starts_with("--- ") {
200            saw_old = true;
201        } else if saw_old && lt.starts_with("+++ ") {
202            return true;
203        }
204    }
205    false
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use tempfile::TempDir;
212
213    #[test]
214    fn parse_add_file() {
215        let patch = Patch::parse("*** Begin Patch\n*** Add File: hello.txt\n+hello\n*** End Patch").unwrap();
216        assert_eq!(patch.operations().len(), 1);
217        matches!(patch.operations()[0], PatchOperation::AddFile { .. });
218    }
219
220    #[tokio::test]
221    async fn apply_add_file() {
222        let temp_dir = TempDir::new().unwrap();
223        let patch = Patch::parse("*** Begin Patch\n*** Add File: file.txt\n+content\n*** End Patch").unwrap();
224
225        let result = patch.apply(temp_dir.path()).await.unwrap();
226        assert_eq!(result, vec!["[1/1] Added file: file.txt (8 bytes)".to_string()]);
227        let written = tokio::fs::read_to_string(temp_dir.path().join("file.txt")).await.unwrap();
228        assert_eq!(written, "content\n");
229    }
230
231    #[tokio::test]
232    async fn blank_line_removal_without_a_blank_line_fails_loud() {
233        let patch = Patch::parse("*** Begin Patch\n*** Update File: f.txt\n@@ a\n-\n+X\n*** End Patch\n")
234            .expect("patch parses");
235        let chunks = match &patch.operations()[0] {
236            PatchOperation::UpdateFile { chunks, .. } => chunks.clone(),
237            other => panic!("expected update, got {other:?}"),
238        };
239        // No blank line exists after the "a" anchor: this must fail with a
240        // segment error, never silently insert "X" at the anchor.
241        let error = render_patch_update_content(Path::new("f.txt"), "a\nb\n", &chunks, "f.txt")
242            .await
243            .expect_err("missing blank line must fail, not silently insert");
244        assert!(error.to_string().contains("failed to locate expected lines"), "{error}");
245    }
246
247    #[tokio::test]
248    async fn blank_line_removal_still_matches_a_real_blank_line() {
249        let patch =
250            Patch::parse("*** Begin Patch\n*** Update File: f.txt\n@@\n-\n+X\n*** End Patch\n").expect("patch parses");
251        let chunks = match &patch.operations()[0] {
252            PatchOperation::UpdateFile { chunks, .. } => chunks.clone(),
253            other => panic!("expected update, got {other:?}"),
254        };
255        let rendered = render_patch_update_content(Path::new("f.txt"), "a\n\nb\n", &chunks, "f.txt")
256            .await
257            .expect("blank line exists and must match");
258        assert_eq!(rendered, "a\nX\nb\n");
259    }
260
261    #[tokio::test]
262    async fn blank_line_document_keeps_every_trailing_newline() {
263        let patch =
264            Patch::parse("*** Begin Patch\n*** Update File: f.txt\n@@\n-\n+X\n*** End Patch\n").expect("patch parses");
265        let chunks = match &patch.operations()[0] {
266            PatchOperation::UpdateFile { chunks, .. } => chunks.clone(),
267            other => panic!("expected update, got {other:?}"),
268        };
269        // "\n\n" splits into two blank lines; changing the first must not make
270        // the second one disappear with it.
271        let rendered = render_patch_update_content(Path::new("f.txt"), "\n\n", &chunks, "f.txt")
272            .await
273            .expect("blank line exists and must match");
274        assert_eq!(rendered, "X\n\n");
275    }
276
277    #[tokio::test]
278    async fn adding_a_blank_line_at_eof_is_not_swallowed_by_the_trailing_newline() {
279        let patch =
280            Patch::parse("*** Begin Patch\n*** Update File: f.txt\n@@\n a\n+\n*** End Patch\n").expect("patch parses");
281        let chunks = match &patch.operations()[0] {
282            PatchOperation::UpdateFile { chunks, .. } => chunks.clone(),
283            other => panic!("expected update, got {other:?}"),
284        };
285        let rendered = render_patch_update_content(Path::new("f.txt"), "a\n", &chunks, "f.txt")
286            .await
287            .expect("context line must match");
288        assert_eq!(rendered, "a\n\n");
289    }
290
291    #[tokio::test]
292    async fn overlapping_chunk_matches_are_rejected() {
293        let patch = Patch::parse(
294            "*** Begin Patch\n*** Update File: f.txt\n@@ -1,2\n-a\n-b\n+X\n@@ -1,2\n-a\n-b\n+Y\n*** End Patch\n",
295        )
296        .expect("patch parses");
297        let chunks = match &patch.operations()[0] {
298            PatchOperation::UpdateFile { chunks, .. } => chunks.clone(),
299            other => panic!("expected update, got {other:?}"),
300        };
301        // Both chunks match lines 0..2: applying both would silently garble
302        // the file, so the render must fail instead.
303        let error = render_patch_update_content(Path::new("f.txt"), "a\nb\n", &chunks, "f.txt")
304            .await
305            .expect_err("overlapping replacements must fail, not double-apply");
306        assert!(error.to_string().contains("overlapping"), "{error}");
307    }
308
309    // -----------------------------------------------------------------------
310    // Shape-detection primitives
311    // -----------------------------------------------------------------------
312
313    #[test]
314    fn looks_like_vte_patch_detects_envelope_and_bare_headers() {
315        assert!(looks_like_vte_patch("*** Begin Patch\n*** End Patch"));
316        assert!(looks_like_vte_patch("*** Update File: src/main.rs\n@@\n+new\n"));
317        assert!(looks_like_vte_patch("*** Add File: new.txt\n+content\n"));
318        assert!(looks_like_vte_patch("*** Delete File: old.txt"));
319        // Leading whitespace is tolerated.
320        assert!(looks_like_vte_patch("  \n*** Begin Patch\n*** End Patch"));
321    }
322
323    #[test]
324    fn looks_like_vte_patch_rejects_non_patch_shapes() {
325        assert!(!looks_like_vte_patch("diff --git a/f b/f\n"));
326        assert!(!looks_like_vte_patch("--- a/f\n+++ b/f\n"));
327        assert!(!looks_like_vte_patch("fn main() { println!(\"hi\"); }"));
328        assert!(!looks_like_vte_patch(""));
329    }
330
331    #[test]
332    fn looks_like_unified_diff_detects_git_diff_header() {
333        assert!(looks_like_unified_diff("diff --git a/src/main.rs b/src/main.rs\nindex abc..def 100644\n"));
334    }
335
336    #[test]
337    fn looks_like_unified_diff_detects_paired_file_headers() {
338        assert!(looks_like_unified_diff("--- a/src/main.rs\n+++ b/src/main.rs\n@@ -1,3 +1,3 @@\n-old\n+new\n"));
339    }
340
341    #[test]
342    fn looks_like_unified_diff_rejects_vte_patch() {
343        // A valid VTE patch must never be mistaken for a unified diff.
344        assert!(!looks_like_unified_diff("*** Begin Patch\n*** Update File: f.rs\n@@\n-old\n+new\n*** End Patch"));
345        assert!(!looks_like_unified_diff(""));
346        assert!(!looks_like_unified_diff("fn main() {}"));
347    }
348}