From a39ea052deff856ff9d27cdebecbbea1837d5a69 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:40:13 +0100 Subject: 0.4.4: file-tool correctness - read: regular files only, checked offset conversion on 32-bit - write/edit: atomic rename, re-read before apply, preserve mode - edit: CRLF files match and keep their line endings - grep: missing path is an error, skipped files are reported - glob: follows file symlinks --- src/tools/fs.rs | 258 ++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 204 insertions(+), 54 deletions(-) (limited to 'src/tools/fs.rs') diff --git a/src/tools/fs.rs b/src/tools/fs.rs index caa3992..947649f 100644 --- a/src/tools/fs.rs +++ b/src/tools/fs.rs @@ -1,6 +1,7 @@ use std::fs; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; use serde_json::Value; @@ -23,10 +24,11 @@ const SKIP_DIRS: &[&str] = &[ ]; /// A pending file change. Built and previewed first, applied only after the -/// human agrees. +/// human agrees. The file is re-read at apply time, so an edit made while the +/// approval prompt was open is not silently discarded. pub enum Change { Write { path: String, content: String }, - Edit { path: String, old: String, new: String, text: String }, + Edit { path: String, old: String, new: String }, } impl Change { @@ -36,21 +38,17 @@ impl Change { } } - pub fn preview(&self) -> String { + pub fn preview(&self) -> Result { match self { - Change::Write { path, content } => match fs::read_to_string(path) { + Change::Write { path, content } => Ok(match fs::read_to_string(path) { Ok(old) if old == *content => format!("{path}: unchanged"), Ok(old) => diff_preview(&old, content), Err(_) => new_file_preview(path, content), - }, - Change::Edit { - path, - old, - new, - text, - } => { - let at = text.find(old.as_str()).unwrap_or(0); - edit_preview(path, text, old, new, at) + }), + Change::Edit { path, old, new } => { + let text = fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; + let span = locate(&text, old)?; + Ok(edit_preview(path, &text, &span, old, new)) } } } @@ -67,31 +65,166 @@ impl Change { )); } } - fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?; + atomic_write(&path, &content)?; Ok(format!( "wrote {} bytes ({} lines) to {path}", content.len(), content.lines().count() )) } - Change::Edit { - path, - old, - new, - mut text, - } => { - let at = text - .find(old.as_str()) - .ok_or_else(|| format!("{path}: text to replace disappeared"))?; - let line = text[..at].matches('\n').count() + 1; - text.replace_range(at..at + old.len(), &new); - fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?; + Change::Edit { path, old, new } => { + let mut text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; + let span = locate(&text, &old)?; + let line = text[..span.start].matches('\n').count() + 1; + // Keep the file's line-ending style. + let replacement = if span.crlf { + new.replace("\r\n", "\n").replace('\n', "\r\n") + } else { + new.clone() + }; + text.replace_range(span.start..span.end, &replacement); + atomic_write(&path, &text)?; Ok(format!("edited {path}: 1 replacement at line {line}")) } } } } +/// Where the text to replace sits in the file, and whether the file uses CRLF. +struct Span { + start: usize, + end: usize, + crlf: bool, +} + +fn locate(text: &str, old: &str) -> Result { + let exact: Vec = text.match_indices(old).map(|(index, _)| index).collect(); + match exact.len() { + 1 => { + return Ok(Span { + start: exact[0], + end: exact[0] + old.len(), + crlf: false, + }) + } + 0 => {} + many => { + return Err(format!( + "text to replace appears {many} times (lines {}); include more \ + surrounding context so it is unique.", + line_list(text, &exact) + )) + } + } + + // A CRLF file shows up in `read` with a trailing carriage return the model + // cannot see. Retry with line endings normalised rather than reporting + // "not found" for text that is visibly there. + if text.contains("\r\n") { + let normalized = text.replace("\r\n", "\n"); + let wanted = old.replace("\r\n", "\n"); + let hits: Vec = normalized + .match_indices(&wanted) + .map(|(index, _)| index) + .collect(); + match hits.len() { + 1 => { + let start = original_offset(text, hits[0]); + if let Some(end) = original_range(text, start, &wanted) { + return Ok(Span { + start, + end, + crlf: true, + }); + } + } + many if many > 1 => { + let lines: Vec = hits + .iter() + .take(10) + .map(|hit| (normalized[..*hit].matches('\n').count() + 1).to_string()) + .collect(); + return Err(format!( + "text to replace appears {many} times in this CRLF file (lines {}); \ + include more surrounding context so it is unique.", + lines.join(", ") + )); + } + _ => {} + } + } + + Err("text to replace was not found. Read the file and copy the exact text, \ + including indentation." + .to_string()) +} + +/// Byte offset in the original text for an offset in the CRLF-normalised text. +fn original_offset(text: &str, target: usize) -> usize { + let bytes = text.as_bytes(); + let mut original = 0usize; + let mut normalized = 0usize; + while original < bytes.len() && normalized < target { + if bytes[original] == b'\r' && bytes.get(original + 1) == Some(&b'\n') { + original += 2; + } else { + original += 1; + } + normalized += 1; + } + original +} + +/// End offset in the original text for a normalised match of `wanted`. +fn original_range(text: &str, start: usize, wanted: &str) -> Option { + let bytes = text.as_bytes(); + let mut cursor = start; + for byte in wanted.bytes() { + if byte == b'\n' { + if bytes.get(cursor) == Some(&b'\r') && bytes.get(cursor + 1) == Some(&b'\n') { + cursor += 2; + } else if bytes.get(cursor) == Some(&b'\n') { + cursor += 1; + } else { + return None; + } + } else { + if bytes.get(cursor) != Some(&byte) { + return None; + } + cursor += 1; + } + } + Some(cursor) +} + +/// Write via a temporary file and rename, so a crash or a full disk leaves the +/// original intact instead of a half-written file. +fn atomic_write(path: &str, content: &str) -> Result<(), String> { + let target = Path::new(path); + let parent = match target.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(), + _ => PathBuf::from("."), + }; + let temp = parent.join(format!( + ".agent686-{}-{}.tmp", + std::process::id(), + TEMP_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + + fs::write(&temp, content).map_err(|e| format!("{}: {e}", temp.display()))?; + if let Ok(meta) = fs::metadata(target) { + let _ = fs::set_permissions(&temp, meta.permissions()); + } + if let Err(error) = fs::rename(&temp, target) { + let _ = fs::remove_file(&temp); + return Err(format!("{path}: {error}")); + } + Ok(()) +} + +static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0); + pub fn plan_write(args: &Value) -> Result { Ok(Change::Write { path: req(args, "path")?, @@ -107,33 +240,16 @@ pub fn plan_edit(args: &Value) -> Result { return Err("`old` must not be empty; use write to create a file".into()); } let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; - let hits: Vec = text.match_indices(&old).map(|(i, _)| i).collect(); - match hits.len() { - 0 => Err(format!( - "text to replace was not found in {path}. Read the file and copy the exact \ - text, including indentation." - )), - 1 => Ok(Change::Edit { - path, - old, - new, - text, - }), - n => Err(format!( - "text to replace appears {n} times in {path} (lines {}); include more \ - surrounding context so it is unique.", - line_list(&text, &hits) - )), - } + // Fail before the approval prompt if the match is unusable. + locate(&text, &old)?; + Ok(Change::Edit { path, old, new }) } pub fn read(args: &Value) -> Result { let path = req(args, "path")?; - let offset = args - .get("offset") - .and_then(|v| v.as_u64()) - .unwrap_or(1) - .max(1) as usize; + let offset = args.get("offset").and_then(|v| v.as_u64()).unwrap_or(1).max(1); + let offset = usize::try_from(offset) + .map_err(|_| format!("offset {offset} is too large for this build"))?; let limit = args .get("limit") .and_then(|v| v.as_u64()) @@ -144,6 +260,11 @@ pub fn read(args: &Value) -> Result { if meta.is_dir() { return Err(format!("{path} is a directory; use glob or grep")); } + if !meta.is_file() { + // A FIFO or a device would block forever, and this process is single + // threaded, so nothing could interrupt it. + return Err(format!("{path} is not a regular file")); + } let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?; let mut reader = BufReader::with_capacity(64 * 1024, file); @@ -331,6 +452,9 @@ pub fn grep(args: &Value) -> Result { }; let root = Path::new(&base); + if !root.exists() { + return Err(format!("{base}: no such file or directory")); + } let files = if root.is_file() { vec![root.to_path_buf()] } else { @@ -341,19 +465,32 @@ pub fn grep(args: &Value) -> Result { let mut out = String::new(); let mut matches = 0usize; + let mut skipped = 0usize; for file in files { if matches >= MAX_MATCHES { break; } - grep_file(&file, &matcher, &mut matches, &mut out); + grep_file(&file, &matcher, &mut matches, &mut skipped, &mut out); } if matches == 0 { - return Ok(format!("no matches for `{pattern}` under {base}")); + let mut message = format!("no matches for `{pattern}` under {base}"); + if skipped > 0 { + message.push_str(&format!( + "\n({skipped} file(s) not searched: larger than 4 MiB or binary)" + )); + } + return Ok(message); } if matches >= MAX_MATCHES { out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); } + if skipped > 0 { + out.push_str(&format!( + "({skipped} file(s) not searched: larger than {} or binary)\n", + "4 MiB" + )); + } Ok(out) } @@ -410,12 +547,19 @@ pub fn glob(args: &Value) -> Result { Ok(out) } -fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String) { +fn grep_file( + path: &Path, + matcher: &Matcher, + count: &mut usize, + skipped: &mut usize, + out: &mut String, +) { let meta = match fs::metadata(path) { Ok(m) => m, Err(_) => return, }; if meta.len() > MAX_SCAN_BYTES { + *skipped += 1; return; } let bytes = match fs::read(path) { @@ -423,6 +567,7 @@ fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String Err(_) => return, }; if bytes.iter().take(8192).any(|&b| b == 0) { + *skipped += 1; return; } let text = String::from_utf8_lossy(&bytes); @@ -462,6 +607,11 @@ fn walk(dir: &Path, out: &mut Vec) { walk(&path, out); } else if file_type.is_file() { out.push(path); + } else if file_type.is_symlink() && fs::metadata(&path).map(|m| m.is_file()).unwrap_or(false) + { + // Follow file symlinks; symlinked directories are skipped so a loop + // cannot walk forever. + out.push(path); } } } @@ -582,9 +732,9 @@ fn diff_preview(old: &str, new: &str) -> String { out } -fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String { +fn edit_preview(path: &str, text: &str, span: &Span, old: &str, new: &str) -> String { let lines: Vec<&str> = text.lines().collect(); - let line_no = text[..at].matches('\n').count() + 1; + let line_no = text[..span.start].matches('\n').count() + 1; let old_lines = old.lines().count().max(1); let mut out = format!("@@ {path}:{line_no} @@\n"); -- cgit v1.2.3