use crate::tools::{replace_file, str_arg, Tool, ToolError, WriteFile};
use async_trait::async_trait;
use serde_json::{json, Value};
pub(crate) const MAX_BYTES: usize = 4 * 1024 * 1024;
const CONTEXT: usize = 2;
const MAX_HUNKS: usize = 3;
pub struct Patch {
files: WriteFile,
}
impl Patch {
pub fn new(files: WriteFile) -> Self {
Self { files }
}
}
pub(crate) struct Hit {
pub(crate) start: usize,
pub(crate) end: usize,
pub(crate) line: usize,
pub(crate) relaxed: bool,
}
pub(crate) fn line_count(text: &str) -> usize {
if text.is_empty() {
0
} else {
text.split_inclusive('\n').count()
}
}
fn exact_occurrences(hay: &str, needle: &str) -> Vec<Hit> {
hay.match_indices(needle)
.map(|(start, _)| Hit {
start,
end: start + needle.len(),
line: hay[..start].matches('\n').count() + 1,
relaxed: false,
})
.collect()
}
fn relaxed_occurrences(hay: &str, needle: &str) -> Vec<Hit> {
let lines: Vec<&str> = hay.split_inclusive('\n').collect();
let wanted: Vec<&str> = needle.split_inclusive('\n').collect();
if wanted.is_empty() || lines.len() < wanted.len() {
return Vec::new();
}
let mut starts = Vec::with_capacity(lines.len() + 1);
let mut at = 0;
for line in &lines {
starts.push(at);
at += line.len();
}
starts.push(at);
let mut hits = Vec::new();
for i in 0..=(lines.len() - wanted.len()) {
if !lines[i..i + wanted.len()]
.iter()
.zip(&wanted)
.all(|(a, b)| a.trim() == b.trim())
{
continue;
}
let start = starts[i];
if hits.last().is_some_and(|last: &Hit| start < last.end) {
continue;
}
let mut end = starts[i + wanted.len()];
if !needle.ends_with('\n') && end > start && hay.as_bytes()[end - 1] == b'\n' {
end -= 1;
}
hits.push(Hit {
start,
end,
line: i + 1,
relaxed: true,
});
}
hits
}
pub(crate) fn hits(hay: &str, needle: &str) -> Vec<Hit> {
let exact = exact_occurrences(hay, needle);
if exact.is_empty() {
relaxed_occurrences(hay, needle)
} else {
exact
}
}
pub(crate) fn splice(before: &str, hits: &[Hit], replacement: &str) -> String {
let mut out = String::with_capacity(before.len() + replacement.len() * hits.len());
let mut cursor = 0;
for hit in hits {
debug_assert!(
hit.start >= cursor,
"an edit at {} begins inside the one before it (cursor {}) — `#367`",
hit.start,
cursor
);
out.push_str(&before[cursor..hit.start]);
out.push_str(replacement);
cursor = hit.end;
}
out.push_str(&before[cursor..]);
out
}
fn with_newline(line: &str) -> String {
if line.ends_with('\n') {
line.to_string()
} else {
format!("{line}\n")
}
}
fn render_diff(before: &str, hits: &[Hit], replacement: &str) -> String {
let lines: Vec<&str> = before.split_inclusive('\n').collect();
let shown = hits.len().min(MAX_HUNKS);
let mut out = String::new();
for hit in &hits[..shown] {
let old = &before[hit.start..hit.end];
let old_n = line_count(old).max(1);
let new_n = line_count(replacement);
let head = (hit.line - 1).saturating_sub(CONTEXT);
let tail = (hit.line - 1 + old_n + CONTEXT).min(lines.len());
out.push_str(&format!(
"@@ -{},{} +{},{} @@\n",
head + 1,
tail - head,
head + 1,
(tail - head) - old_n + new_n
));
for line in &lines[head..hit.line - 1] {
out.push(' ');
out.push_str(&with_newline(line));
}
for line in old.split_inclusive('\n') {
out.push('-');
out.push_str(&with_newline(line));
}
for line in replacement.split_inclusive('\n') {
out.push('+');
out.push_str(&with_newline(line));
}
for line in &lines[(hit.line - 1 + old_n).min(lines.len())..tail] {
out.push(' ');
out.push_str(&with_newline(line));
}
}
if hits.len() > shown {
out.push_str(&format!("… {} more edit(s)\n", hits.len() - shown));
}
out
}
#[async_trait]
impl Tool for Patch {
fn name(&self) -> &str {
"patch"
}
fn description(&self) -> &str {
"Replace one piece of a text file in place. `old_string` must occur exactly once — pass \
enough of the surrounding lines to be unique — or set `replace_all`. Returns a small \
unified diff. Indentation and trailing spaces are forgiven when nothing matches \
verbatim, and the result says so when that happens. The file must already exist: use \
`write_file` to create one."
}
fn parameters(&self) -> Value {
json!({"type":"object","properties":{
"path":{"type":"string","description":"Path relative to the workspace, or an absolute path inside the scripts directory"},
"old_string":{"type":"string","description":"The text to replace, copied exactly. Long enough to be unique."},
"new_string":{"type":"string","description":"What to put there instead. Empty deletes the text."},
"replace_all":{"type":"boolean","description":"Replace every occurrence instead of requiring exactly one. Default false."}
},"required":["path","old_string","new_string"]})
}
fn describe_call(&self, args: &Value) -> String {
let path = args["path"].as_str().unwrap_or("?");
let old = args["old_string"].as_str().unwrap_or("");
let new = args["new_string"].as_str().unwrap_or("");
format!(
"patch {path}: {} line(s) → {} line(s){}",
line_count(old).max(1),
line_count(new),
if args["replace_all"].as_bool().unwrap_or(false) {
", every occurrence"
} else {
""
}
)
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let path_arg = str_arg(&args, "path")?;
let old = str_arg(&args, "old_string")?;
let new = str_arg(&args, "new_string")?;
let replace_all = args["replace_all"].as_bool().unwrap_or(false);
if old.is_empty() {
return Err(ToolError::InvalidArgs(
"`old_string` is empty; there is nothing to find".into(),
));
}
if old == new {
return Err(ToolError::InvalidArgs(
"`old_string` and `new_string` are the same; the file would not change".into(),
));
}
let path = self.files.resolve(path_arg)?;
let bytes = tokio::fs::read(&path).await.map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => ToolError::Failed(format!(
"{}: no such file. `patch` edits a file that exists; use `write_file` to create one",
path.display()
)),
_ => ToolError::Failed(format!("{}: {e}", path.display())),
})?;
if bytes.len() > MAX_BYTES {
return Err(ToolError::Failed(format!(
"{}: {} bytes, over the {MAX_BYTES}-byte limit for `patch`",
path.display(),
bytes.len()
)));
}
let before = String::from_utf8(bytes)
.map_err(|_| ToolError::Failed(format!("{}: not valid UTF-8", path.display())))?;
let found = hits(&before, old);
if found.is_empty() {
let first = old.lines().next().unwrap_or("").trim().to_string();
let near: Vec<String> = before
.lines()
.enumerate()
.filter(|(_, line)| !first.is_empty() && line.trim() == first)
.map(|(i, _)| (i + 1).to_string())
.take(5)
.collect();
let hint = if near.is_empty() {
String::new()
} else {
format!(
" Its first line is at line {} — the rest of `old_string` differs from what \
is there.",
near.join(", ")
)
};
return Err(ToolError::Failed(format!(
"`old_string` not found in {}. Read the file and copy the text exactly.{hint}",
path.display()
)));
}
if found.len() > 1 && !replace_all {
let where_: Vec<String> = found.iter().map(|h| h.line.to_string()).collect();
return Err(ToolError::Failed(format!(
"`old_string` appears {} times in {} (lines {}). Include more of the surrounding \
text to say which one, or pass `replace_all` to change all of them.",
found.len(),
path.display(),
where_.join(", ")
)));
}
let after = splice(&before, &found, new);
replace_file(&path, &after)?;
let relaxed = found.iter().any(|h| h.relaxed);
Ok(format!(
"patched {} — {} edit(s), {} line(s) → {} line(s) each{}.\n{}",
path.display(),
found.len(),
line_count(old).max(1),
line_count(new),
if relaxed {
", matched ignoring indentation and trailing spaces"
} else {
""
},
render_diff(&before, &found, new)
))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tool(dir: &std::path::Path) -> Patch {
Patch::new(WriteFile::new(dir.to_path_buf(), Some(dir.join("scripts"))))
}
async fn write(dir: &std::path::Path, name: &str, text: &str) -> std::path::PathBuf {
let path = dir.join(name);
tokio::fs::write(&path, text).await.unwrap();
path
}
async fn contents(dir: &std::path::Path, name: &str) -> String {
tokio::fs::read_to_string(dir.join(name)).await.unwrap()
}
#[tokio::test]
async fn a_unique_patch_replaces_just_that_text() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", "one\ntwo\nthree\n").await;
let out = tool(dir.path())
.call(json!({"path": "a.txt", "old_string": "two", "new_string": "2"}))
.await
.unwrap();
assert!(out.contains("1 edit"), "{out}");
assert_eq!(contents(dir.path(), "a.txt").await, "one\n2\nthree\n");
}
#[tokio::test]
async fn an_ambiguous_patch_changes_nothing_and_names_the_lines() {
let dir = tempfile::tempdir().unwrap();
let before = "x = 1\ny = 2\nx = 1\n";
write(dir.path(), "a.txt", before).await;
let err = tool(dir.path())
.call(json!({"path": "a.txt", "old_string": "x = 1", "new_string": "x = 9"}))
.await
.unwrap_err();
assert!(err.to_string().contains("appears 2 times"), "{err}");
assert!(err.to_string().contains("lines 1, 3"), "{err}");
assert_eq!(
contents(dir.path(), "a.txt").await,
before,
"an ambiguous patch is not a guess"
);
}
#[tokio::test]
async fn replace_all_changes_every_occurrence() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", "x = 1\ny = 2\nx = 1\n").await;
let out = tool(dir.path())
.call(
json!({"path": "a.txt", "old_string": "x = 1", "new_string": "x = 9",
"replace_all": true}),
)
.await
.unwrap();
assert!(out.contains("2 edit(s)"), "{out}");
assert_eq!(contents(dir.path(), "a.txt").await, "x = 9\ny = 2\nx = 9\n");
}
#[tokio::test]
async fn replace_all_does_not_slice_inside_its_own_last_match() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", " x\n x\n x\n").await;
let out = tool(dir.path())
.call(
json!({"path": "a.txt", "old_string": "x\nx\n", "new_string": "y\n",
"replace_all": true}),
)
.await
.expect("a repeated needle is a match, not a panic");
assert!(out.contains("1 edit(s)"), "{out}");
assert_eq!(
contents(dir.path(), "a.txt").await,
"y\n x\n",
"the two lines it matched, and the third left alone"
);
}
#[tokio::test]
async fn text_that_is_not_there_is_an_error_and_leaves_the_file_alone() {
let dir = tempfile::tempdir().unwrap();
let before = "fn main() {\n println!(\"hi\");\n}\n";
write(dir.path(), "a.txt", before).await;
let err = tool(dir.path())
.call(json!({"path": "a.txt", "old_string": "println!(\"bye\")", "new_string": "x"}))
.await
.unwrap_err();
assert!(err.to_string().contains("not found"), "{err}");
assert!(
!err.to_string().contains("Its first line"),
"no hint when the first line is not there either: {err}"
);
assert_eq!(contents(dir.path(), "a.txt").await, before);
}
#[tokio::test]
async fn a_near_miss_points_at_the_line_its_first_line_is_on() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", "a\nb\nc\n").await;
let err = tool(dir.path())
.call(json!({"path": "a.txt", "old_string": "b\nc\nzzz", "new_string": "x"}))
.await
.unwrap_err();
assert!(err.to_string().contains("first line is at line 2"), "{err}");
}
#[tokio::test]
async fn different_indentation_is_forgiven_and_the_result_says_so() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", "fn f() {\n let x = 1;\n}\n").await;
let out = tool(dir.path())
.call(json!({"path": "a.txt",
"old_string": "\tlet x = 1;\n}",
"new_string": " let x = 2;\n}"}))
.await
.unwrap();
assert!(out.contains("ignoring indentation"), "{out}");
assert_eq!(
contents(dir.path(), "a.txt").await,
"fn f() {\n let x = 2;\n}\n"
);
}
#[tokio::test]
async fn a_relaxed_match_does_not_swallow_the_line_ending() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", "first\nsecond\n").await;
tool(dir.path())
.call(json!({"path": "a.txt", "old_string": " second ", "new_string": "SECOND"}))
.await
.unwrap();
assert_eq!(contents(dir.path(), "a.txt").await, "first\nSECOND\n");
}
#[tokio::test]
async fn an_empty_new_string_deletes_the_text() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", "keep\ndrop\nkeep2\n").await;
tool(dir.path())
.call(json!({"path": "a.txt", "old_string": "drop\n", "new_string": ""}))
.await
.unwrap();
assert_eq!(contents(dir.path(), "a.txt").await, "keep\nkeep2\n");
}
#[tokio::test]
async fn a_missing_file_says_to_use_write_file() {
let dir = tempfile::tempdir().unwrap();
let err = tool(dir.path())
.call(json!({"path": "nope.txt", "old_string": "a", "new_string": "b"}))
.await
.unwrap_err();
assert!(err.to_string().contains("write_file"), "{err}");
}
#[tokio::test]
async fn a_patch_cannot_reach_outside_the_workspace() {
let dir = tempfile::tempdir().unwrap();
let err = tool(dir.path())
.call(json!({"path": "../../etc/passwd", "old_string": "a", "new_string": "b"}))
.await
.unwrap_err();
assert!(err.to_string().contains("outside the workspace"), "{err}");
}
#[tokio::test]
async fn a_patch_to_a_script_in_the_scripts_directory_is_allowed() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::create_dir_all(dir.path().join("scripts"))
.await
.unwrap();
write(&dir.path().join("scripts"), "run.sh", "echo one\n").await;
let path = dir.path().join("scripts/run.sh");
tool(dir.path())
.call(json!({"path": path.to_str().unwrap(), "old_string": "one", "new_string": "two"}))
.await
.unwrap();
assert_eq!(
contents(&dir.path().join("scripts"), "run.sh").await,
"echo two\n"
);
}
#[tokio::test]
async fn an_empty_or_unchanged_edit_is_refused_before_the_file_is_read() {
let dir = tempfile::tempdir().unwrap();
let t = tool(dir.path());
let empty = t
.call(json!({"path": "a.txt", "old_string": "", "new_string": "x"}))
.await
.unwrap_err();
assert!(empty.to_string().contains("nothing to find"), "{empty}");
let same = t
.call(json!({"path": "a.txt", "old_string": "x", "new_string": "x"}))
.await
.unwrap_err();
assert!(same.to_string().contains("would not change"), "{same}");
}
#[test]
fn the_diff_shows_the_old_line_under_a_minus_and_the_new_under_a_plus() {
let before = "a\nb\nc\nd\n";
let found = hits(before, "c\n");
let diff = render_diff(before, &found, "C\n");
assert!(diff.contains("@@ -1,4 +1,4 @@"), "{diff}");
assert!(diff.contains("-c\n"), "{diff}");
assert!(diff.contains("+C\n"), "{diff}");
assert!(diff.contains(" b\n"), "{diff}");
assert!(diff.contains(" d\n"), "{diff}");
}
#[test]
fn an_edit_in_the_middle_of_a_line_is_shown_as_that_partial_line() {
let before = "let x = 1;\n";
let found = hits(before, "1");
let diff = render_diff(before, &found, "2");
assert!(diff.contains("-1\n"), "{diff}");
assert!(diff.contains("+2\n"), "{diff}");
assert!(!diff.contains("let x"), "{diff}");
}
}