1use crate::tools::{replace_file, str_arg, Tool, ToolError, WriteFile};
27use async_trait::async_trait;
28use serde_json::{json, Value};
29
30pub(crate) const MAX_BYTES: usize = 4 * 1024 * 1024;
33
34const CONTEXT: usize = 2;
36
37const MAX_HUNKS: usize = 3;
39
40pub struct Patch {
41 files: WriteFile,
43}
44
45impl Patch {
46 pub fn new(files: WriteFile) -> Self {
47 Self { files }
48 }
49}
50
51pub(crate) struct Hit {
53 pub(crate) start: usize,
54 pub(crate) end: usize,
55 pub(crate) line: usize,
57 pub(crate) relaxed: bool,
59}
60
61pub(crate) fn line_count(text: &str) -> usize {
63 if text.is_empty() {
64 0
65 } else {
66 text.split_inclusive('\n').count()
67 }
68}
69
70fn exact_occurrences(hay: &str, needle: &str) -> Vec<Hit> {
72 hay.match_indices(needle)
73 .map(|(start, _)| Hit {
74 start,
75 end: start + needle.len(),
76 line: hay[..start].matches('\n').count() + 1,
77 relaxed: false,
78 })
79 .collect()
80}
81
82fn relaxed_occurrences(hay: &str, needle: &str) -> Vec<Hit> {
87 let lines: Vec<&str> = hay.split_inclusive('\n').collect();
88 let wanted: Vec<&str> = needle.split_inclusive('\n').collect();
89 if wanted.is_empty() || lines.len() < wanted.len() {
90 return Vec::new();
91 }
92 let mut starts = Vec::with_capacity(lines.len() + 1);
94 let mut at = 0;
95 for line in &lines {
96 starts.push(at);
97 at += line.len();
98 }
99 starts.push(at);
100
101 let mut hits = Vec::new();
102 for i in 0..=(lines.len() - wanted.len()) {
103 if !lines[i..i + wanted.len()]
104 .iter()
105 .zip(&wanted)
106 .all(|(a, b)| a.trim() == b.trim())
107 {
108 continue;
109 }
110 let start = starts[i];
111 if hits.last().is_some_and(|last: &Hit| start < last.end) {
118 continue;
119 }
120 let mut end = starts[i + wanted.len()];
121 if !needle.ends_with('\n') && end > start && hay.as_bytes()[end - 1] == b'\n' {
122 end -= 1;
123 }
124 hits.push(Hit {
125 start,
126 end,
127 line: i + 1,
128 relaxed: true,
129 });
130 }
131 hits
132}
133
134pub(crate) fn hits(hay: &str, needle: &str) -> Vec<Hit> {
137 let exact = exact_occurrences(hay, needle);
138 if exact.is_empty() {
139 relaxed_occurrences(hay, needle)
140 } else {
141 exact
142 }
143}
144
145pub(crate) fn splice(before: &str, hits: &[Hit], replacement: &str) -> String {
148 let mut out = String::with_capacity(before.len() + replacement.len() * hits.len());
149 let mut cursor = 0;
150 for hit in hits {
151 debug_assert!(
152 hit.start >= cursor,
153 "an edit at {} begins inside the one before it (cursor {}) — `#367`",
154 hit.start,
155 cursor
156 );
157 out.push_str(&before[cursor..hit.start]);
158 out.push_str(replacement);
159 cursor = hit.end;
160 }
161 out.push_str(&before[cursor..]);
162 out
163}
164
165fn with_newline(line: &str) -> String {
166 if line.ends_with('\n') {
167 line.to_string()
168 } else {
169 format!("{line}\n")
170 }
171}
172
173fn render_diff(before: &str, hits: &[Hit], replacement: &str) -> String {
179 let lines: Vec<&str> = before.split_inclusive('\n').collect();
180 let shown = hits.len().min(MAX_HUNKS);
181 let mut out = String::new();
182
183 for hit in &hits[..shown] {
184 let old = &before[hit.start..hit.end];
185 let old_n = line_count(old).max(1);
186 let new_n = line_count(replacement);
187 let head = (hit.line - 1).saturating_sub(CONTEXT);
188 let tail = (hit.line - 1 + old_n + CONTEXT).min(lines.len());
189
190 out.push_str(&format!(
191 "@@ -{},{} +{},{} @@\n",
192 head + 1,
193 tail - head,
194 head + 1,
195 (tail - head) - old_n + new_n
196 ));
197 for line in &lines[head..hit.line - 1] {
198 out.push(' ');
199 out.push_str(&with_newline(line));
200 }
201 for line in old.split_inclusive('\n') {
202 out.push('-');
203 out.push_str(&with_newline(line));
204 }
205 for line in replacement.split_inclusive('\n') {
206 out.push('+');
207 out.push_str(&with_newline(line));
208 }
209 for line in &lines[(hit.line - 1 + old_n).min(lines.len())..tail] {
210 out.push(' ');
211 out.push_str(&with_newline(line));
212 }
213 }
214 if hits.len() > shown {
215 out.push_str(&format!("… {} more edit(s)\n", hits.len() - shown));
216 }
217 out
218}
219
220#[async_trait]
221impl Tool for Patch {
222 fn name(&self) -> &str {
223 "patch"
224 }
225
226 fn description(&self) -> &str {
227 "Replace one piece of a text file in place. `old_string` must occur exactly once — pass \
228 enough of the surrounding lines to be unique — or set `replace_all`. Returns a small \
229 unified diff. Indentation and trailing spaces are forgiven when nothing matches \
230 verbatim, and the result says so when that happens. The file must already exist: use \
231 `write_file` to create one."
232 }
233
234 fn parameters(&self) -> Value {
235 json!({"type":"object","properties":{
236 "path":{"type":"string","description":"Path relative to the workspace, or an absolute path inside the scripts directory"},
237 "old_string":{"type":"string","description":"The text to replace, copied exactly. Long enough to be unique."},
238 "new_string":{"type":"string","description":"What to put there instead. Empty deletes the text."},
239 "replace_all":{"type":"boolean","description":"Replace every occurrence instead of requiring exactly one. Default false."}
240 },"required":["path","old_string","new_string"]})
241 }
242
243 fn describe_call(&self, args: &Value) -> String {
244 let path = args["path"].as_str().unwrap_or("?");
245 let old = args["old_string"].as_str().unwrap_or("");
246 let new = args["new_string"].as_str().unwrap_or("");
247 format!(
248 "patch {path}: {} line(s) → {} line(s){}",
249 line_count(old).max(1),
250 line_count(new),
251 if args["replace_all"].as_bool().unwrap_or(false) {
252 ", every occurrence"
253 } else {
254 ""
255 }
256 )
257 }
258
259 async fn call(&self, args: Value) -> Result<String, ToolError> {
260 let path_arg = str_arg(&args, "path")?;
261 let old = str_arg(&args, "old_string")?;
262 let new = str_arg(&args, "new_string")?;
263 let replace_all = args["replace_all"].as_bool().unwrap_or(false);
264
265 if old.is_empty() {
266 return Err(ToolError::InvalidArgs(
267 "`old_string` is empty; there is nothing to find".into(),
268 ));
269 }
270 if old == new {
271 return Err(ToolError::InvalidArgs(
272 "`old_string` and `new_string` are the same; the file would not change".into(),
273 ));
274 }
275
276 let path = self.files.resolve(path_arg)?;
277 let bytes = tokio::fs::read(&path).await.map_err(|e| match e.kind() {
278 std::io::ErrorKind::NotFound => ToolError::Failed(format!(
279 "{}: no such file. `patch` edits a file that exists; use `write_file` to create one",
280 path.display()
281 )),
282 _ => ToolError::Failed(format!("{}: {e}", path.display())),
283 })?;
284 if bytes.len() > MAX_BYTES {
285 return Err(ToolError::Failed(format!(
286 "{}: {} bytes, over the {MAX_BYTES}-byte limit for `patch`",
287 path.display(),
288 bytes.len()
289 )));
290 }
291 let before = String::from_utf8(bytes)
292 .map_err(|_| ToolError::Failed(format!("{}: not valid UTF-8", path.display())))?;
293
294 let found = hits(&before, old);
295 if found.is_empty() {
296 let first = old.lines().next().unwrap_or("").trim().to_string();
299 let near: Vec<String> = before
300 .lines()
301 .enumerate()
302 .filter(|(_, line)| !first.is_empty() && line.trim() == first)
303 .map(|(i, _)| (i + 1).to_string())
304 .take(5)
305 .collect();
306 let hint = if near.is_empty() {
307 String::new()
308 } else {
309 format!(
310 " Its first line is at line {} — the rest of `old_string` differs from what \
311 is there.",
312 near.join(", ")
313 )
314 };
315 return Err(ToolError::Failed(format!(
316 "`old_string` not found in {}. Read the file and copy the text exactly.{hint}",
317 path.display()
318 )));
319 }
320 if found.len() > 1 && !replace_all {
321 let where_: Vec<String> = found.iter().map(|h| h.line.to_string()).collect();
322 return Err(ToolError::Failed(format!(
323 "`old_string` appears {} times in {} (lines {}). Include more of the surrounding \
324 text to say which one, or pass `replace_all` to change all of them.",
325 found.len(),
326 path.display(),
327 where_.join(", ")
328 )));
329 }
330
331 let after = splice(&before, &found, new);
332 replace_file(&path, &after)?;
333
334 let relaxed = found.iter().any(|h| h.relaxed);
335 Ok(format!(
336 "patched {} — {} edit(s), {} line(s) → {} line(s) each{}.\n{}",
337 path.display(),
338 found.len(),
339 line_count(old).max(1),
340 line_count(new),
341 if relaxed {
342 ", matched ignoring indentation and trailing spaces"
343 } else {
344 ""
345 },
346 render_diff(&before, &found, new)
347 ))
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 fn tool(dir: &std::path::Path) -> Patch {
356 Patch::new(WriteFile::new(dir.to_path_buf(), Some(dir.join("scripts"))))
357 }
358
359 async fn write(dir: &std::path::Path, name: &str, text: &str) -> std::path::PathBuf {
360 let path = dir.join(name);
361 tokio::fs::write(&path, text).await.unwrap();
362 path
363 }
364
365 async fn contents(dir: &std::path::Path, name: &str) -> String {
366 tokio::fs::read_to_string(dir.join(name)).await.unwrap()
367 }
368
369 #[tokio::test]
370 async fn a_unique_patch_replaces_just_that_text() {
371 let dir = tempfile::tempdir().unwrap();
372 write(dir.path(), "a.txt", "one\ntwo\nthree\n").await;
373 let out = tool(dir.path())
374 .call(json!({"path": "a.txt", "old_string": "two", "new_string": "2"}))
375 .await
376 .unwrap();
377 assert!(out.contains("1 edit"), "{out}");
378 assert_eq!(contents(dir.path(), "a.txt").await, "one\n2\nthree\n");
379 }
380
381 #[tokio::test]
382 async fn an_ambiguous_patch_changes_nothing_and_names_the_lines() {
383 let dir = tempfile::tempdir().unwrap();
384 let before = "x = 1\ny = 2\nx = 1\n";
385 write(dir.path(), "a.txt", before).await;
386 let err = tool(dir.path())
387 .call(json!({"path": "a.txt", "old_string": "x = 1", "new_string": "x = 9"}))
388 .await
389 .unwrap_err();
390 assert!(err.to_string().contains("appears 2 times"), "{err}");
391 assert!(err.to_string().contains("lines 1, 3"), "{err}");
392 assert_eq!(
393 contents(dir.path(), "a.txt").await,
394 before,
395 "an ambiguous patch is not a guess"
396 );
397 }
398
399 #[tokio::test]
400 async fn replace_all_changes_every_occurrence() {
401 let dir = tempfile::tempdir().unwrap();
402 write(dir.path(), "a.txt", "x = 1\ny = 2\nx = 1\n").await;
403 let out = tool(dir.path())
404 .call(
405 json!({"path": "a.txt", "old_string": "x = 1", "new_string": "x = 9",
406 "replace_all": true}),
407 )
408 .await
409 .unwrap();
410 assert!(out.contains("2 edit(s)"), "{out}");
411 assert_eq!(contents(dir.path(), "a.txt").await, "x = 9\ny = 2\nx = 9\n");
412 }
413
414 #[tokio::test]
418 async fn replace_all_does_not_slice_inside_its_own_last_match() {
419 let dir = tempfile::tempdir().unwrap();
420 write(dir.path(), "a.txt", " x\n x\n x\n").await;
421 let out = tool(dir.path())
422 .call(
423 json!({"path": "a.txt", "old_string": "x\nx\n", "new_string": "y\n",
424 "replace_all": true}),
425 )
426 .await
427 .expect("a repeated needle is a match, not a panic");
428 assert!(out.contains("1 edit(s)"), "{out}");
429 assert_eq!(
430 contents(dir.path(), "a.txt").await,
431 "y\n x\n",
432 "the two lines it matched, and the third left alone"
433 );
434 }
435
436 #[tokio::test]
437 async fn text_that_is_not_there_is_an_error_and_leaves_the_file_alone() {
438 let dir = tempfile::tempdir().unwrap();
439 let before = "fn main() {\n println!(\"hi\");\n}\n";
440 write(dir.path(), "a.txt", before).await;
441 let err = tool(dir.path())
442 .call(json!({"path": "a.txt", "old_string": "println!(\"bye\")", "new_string": "x"}))
443 .await
444 .unwrap_err();
445 assert!(err.to_string().contains("not found"), "{err}");
446 assert!(
447 !err.to_string().contains("Its first line"),
448 "no hint when the first line is not there either: {err}"
449 );
450 assert_eq!(contents(dir.path(), "a.txt").await, before);
451 }
452
453 #[tokio::test]
454 async fn a_near_miss_points_at_the_line_its_first_line_is_on() {
455 let dir = tempfile::tempdir().unwrap();
456 write(dir.path(), "a.txt", "a\nb\nc\n").await;
457 let err = tool(dir.path())
458 .call(json!({"path": "a.txt", "old_string": "b\nc\nzzz", "new_string": "x"}))
459 .await
460 .unwrap_err();
461 assert!(err.to_string().contains("first line is at line 2"), "{err}");
462 }
463
464 #[tokio::test]
465 async fn different_indentation_is_forgiven_and_the_result_says_so() {
466 let dir = tempfile::tempdir().unwrap();
467 write(dir.path(), "a.txt", "fn f() {\n let x = 1;\n}\n").await;
468 let out = tool(dir.path())
470 .call(json!({"path": "a.txt",
471 "old_string": "\tlet x = 1;\n}",
472 "new_string": " let x = 2;\n}"}))
473 .await
474 .unwrap();
475 assert!(out.contains("ignoring indentation"), "{out}");
476 assert_eq!(
477 contents(dir.path(), "a.txt").await,
478 "fn f() {\n let x = 2;\n}\n"
479 );
480 }
481
482 #[tokio::test]
483 async fn a_relaxed_match_does_not_swallow_the_line_ending() {
484 let dir = tempfile::tempdir().unwrap();
487 write(dir.path(), "a.txt", "first\nsecond\n").await;
488 tool(dir.path())
489 .call(json!({"path": "a.txt", "old_string": " second ", "new_string": "SECOND"}))
490 .await
491 .unwrap();
492 assert_eq!(contents(dir.path(), "a.txt").await, "first\nSECOND\n");
493 }
494
495 #[tokio::test]
496 async fn an_empty_new_string_deletes_the_text() {
497 let dir = tempfile::tempdir().unwrap();
498 write(dir.path(), "a.txt", "keep\ndrop\nkeep2\n").await;
499 tool(dir.path())
500 .call(json!({"path": "a.txt", "old_string": "drop\n", "new_string": ""}))
501 .await
502 .unwrap();
503 assert_eq!(contents(dir.path(), "a.txt").await, "keep\nkeep2\n");
504 }
505
506 #[tokio::test]
507 async fn a_missing_file_says_to_use_write_file() {
508 let dir = tempfile::tempdir().unwrap();
509 let err = tool(dir.path())
510 .call(json!({"path": "nope.txt", "old_string": "a", "new_string": "b"}))
511 .await
512 .unwrap_err();
513 assert!(err.to_string().contains("write_file"), "{err}");
514 }
515
516 #[tokio::test]
517 async fn a_patch_cannot_reach_outside_the_workspace() {
518 let dir = tempfile::tempdir().unwrap();
519 let err = tool(dir.path())
520 .call(json!({"path": "../../etc/passwd", "old_string": "a", "new_string": "b"}))
521 .await
522 .unwrap_err();
523 assert!(err.to_string().contains("outside the workspace"), "{err}");
524 }
525
526 #[tokio::test]
527 async fn a_patch_to_a_script_in_the_scripts_directory_is_allowed() {
528 let dir = tempfile::tempdir().unwrap();
529 tokio::fs::create_dir_all(dir.path().join("scripts"))
530 .await
531 .unwrap();
532 write(&dir.path().join("scripts"), "run.sh", "echo one\n").await;
533 let path = dir.path().join("scripts/run.sh");
534 tool(dir.path())
535 .call(json!({"path": path.to_str().unwrap(), "old_string": "one", "new_string": "two"}))
536 .await
537 .unwrap();
538 assert_eq!(
539 contents(&dir.path().join("scripts"), "run.sh").await,
540 "echo two\n"
541 );
542 }
543
544 #[tokio::test]
545 async fn an_empty_or_unchanged_edit_is_refused_before_the_file_is_read() {
546 let dir = tempfile::tempdir().unwrap();
547 let t = tool(dir.path());
548 let empty = t
549 .call(json!({"path": "a.txt", "old_string": "", "new_string": "x"}))
550 .await
551 .unwrap_err();
552 assert!(empty.to_string().contains("nothing to find"), "{empty}");
553 let same = t
554 .call(json!({"path": "a.txt", "old_string": "x", "new_string": "x"}))
555 .await
556 .unwrap_err();
557 assert!(same.to_string().contains("would not change"), "{same}");
558 }
559
560 #[test]
561 fn the_diff_shows_the_old_line_under_a_minus_and_the_new_under_a_plus() {
562 let before = "a\nb\nc\nd\n";
563 let found = hits(before, "c\n");
564 let diff = render_diff(before, &found, "C\n");
565 assert!(diff.contains("@@ -1,4 +1,4 @@"), "{diff}");
566 assert!(diff.contains("-c\n"), "{diff}");
567 assert!(diff.contains("+C\n"), "{diff}");
568 assert!(diff.contains(" b\n"), "{diff}");
569 assert!(diff.contains(" d\n"), "{diff}");
570 }
571
572 #[test]
573 fn an_edit_in_the_middle_of_a_line_is_shown_as_that_partial_line() {
574 let before = "let x = 1;\n";
575 let found = hits(before, "1");
576 let diff = render_diff(before, &found, "2");
577 assert!(diff.contains("-1\n"), "{diff}");
578 assert!(diff.contains("+2\n"), "{diff}");
579 assert!(!diff.contains("let x"), "{diff}");
581 }
582}