diff options
Diffstat (limited to 'src/tools')
| -rw-r--r-- | src/tools/fs.rs | 258 |
1 files changed, 204 insertions, 54 deletions
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 @@ | |||
| 1 | use std::fs; | 1 | use std::fs; |
| 2 | use std::io::{BufRead, BufReader}; | 2 | use std::io::{BufRead, BufReader}; |
| 3 | use std::path::{Path, PathBuf}; | 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::sync::atomic::{AtomicUsize, Ordering}; | ||
| 4 | 5 | ||
| 5 | use serde_json::Value; | 6 | use serde_json::Value; |
| 6 | 7 | ||
| @@ -23,10 +24,11 @@ const SKIP_DIRS: &[&str] = &[ | |||
| 23 | ]; | 24 | ]; |
| 24 | 25 | ||
| 25 | /// A pending file change. Built and previewed first, applied only after the | 26 | /// A pending file change. Built and previewed first, applied only after the |
| 26 | /// human agrees. | 27 | /// human agrees. The file is re-read at apply time, so an edit made while the |
| 28 | /// approval prompt was open is not silently discarded. | ||
| 27 | pub enum Change { | 29 | pub enum Change { |
| 28 | Write { path: String, content: String }, | 30 | Write { path: String, content: String }, |
| 29 | Edit { path: String, old: String, new: String, text: String }, | 31 | Edit { path: String, old: String, new: String }, |
| 30 | } | 32 | } |
| 31 | 33 | ||
| 32 | impl Change { | 34 | impl Change { |
| @@ -36,21 +38,17 @@ impl Change { | |||
| 36 | } | 38 | } |
| 37 | } | 39 | } |
| 38 | 40 | ||
| 39 | pub fn preview(&self) -> String { | 41 | pub fn preview(&self) -> Result<String, String> { |
| 40 | match self { | 42 | match self { |
| 41 | Change::Write { path, content } => match fs::read_to_string(path) { | 43 | Change::Write { path, content } => Ok(match fs::read_to_string(path) { |
| 42 | Ok(old) if old == *content => format!("{path}: unchanged"), | 44 | Ok(old) if old == *content => format!("{path}: unchanged"), |
| 43 | Ok(old) => diff_preview(&old, content), | 45 | Ok(old) => diff_preview(&old, content), |
| 44 | Err(_) => new_file_preview(path, content), | 46 | Err(_) => new_file_preview(path, content), |
| 45 | }, | 47 | }), |
| 46 | Change::Edit { | 48 | Change::Edit { path, old, new } => { |
| 47 | path, | 49 | let text = fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; |
| 48 | old, | 50 | let span = locate(&text, old)?; |
| 49 | new, | 51 | Ok(edit_preview(path, &text, &span, old, new)) |
| 50 | text, | ||
| 51 | } => { | ||
| 52 | let at = text.find(old.as_str()).unwrap_or(0); | ||
| 53 | edit_preview(path, text, old, new, at) | ||
| 54 | } | 52 | } |
| 55 | } | 53 | } |
| 56 | } | 54 | } |
| @@ -67,31 +65,166 @@ impl Change { | |||
| 67 | )); | 65 | )); |
| 68 | } | 66 | } |
| 69 | } | 67 | } |
| 70 | fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?; | 68 | atomic_write(&path, &content)?; |
| 71 | Ok(format!( | 69 | Ok(format!( |
| 72 | "wrote {} bytes ({} lines) to {path}", | 70 | "wrote {} bytes ({} lines) to {path}", |
| 73 | content.len(), | 71 | content.len(), |
| 74 | content.lines().count() | 72 | content.lines().count() |
| 75 | )) | 73 | )) |
| 76 | } | 74 | } |
| 77 | Change::Edit { | 75 | Change::Edit { path, old, new } => { |
| 78 | path, | 76 | let mut text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; |
| 79 | old, | 77 | let span = locate(&text, &old)?; |
| 80 | new, | 78 | let line = text[..span.start].matches('\n').count() + 1; |
| 81 | mut text, | 79 | // Keep the file's line-ending style. |
| 82 | } => { | 80 | let replacement = if span.crlf { |
| 83 | let at = text | 81 | new.replace("\r\n", "\n").replace('\n', "\r\n") |
| 84 | .find(old.as_str()) | 82 | } else { |
| 85 | .ok_or_else(|| format!("{path}: text to replace disappeared"))?; | 83 | new.clone() |
| 86 | let line = text[..at].matches('\n').count() + 1; | 84 | }; |
| 87 | text.replace_range(at..at + old.len(), &new); | 85 | text.replace_range(span.start..span.end, &replacement); |
| 88 | fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?; | 86 | atomic_write(&path, &text)?; |
| 89 | Ok(format!("edited {path}: 1 replacement at line {line}")) | 87 | Ok(format!("edited {path}: 1 replacement at line {line}")) |
| 90 | } | 88 | } |
| 91 | } | 89 | } |
| 92 | } | 90 | } |
| 93 | } | 91 | } |
| 94 | 92 | ||
| 93 | /// Where the text to replace sits in the file, and whether the file uses CRLF. | ||
| 94 | struct Span { | ||
| 95 | start: usize, | ||
| 96 | end: usize, | ||
| 97 | crlf: bool, | ||
| 98 | } | ||
| 99 | |||
| 100 | fn locate(text: &str, old: &str) -> Result<Span, String> { | ||
| 101 | let exact: Vec<usize> = text.match_indices(old).map(|(index, _)| index).collect(); | ||
| 102 | match exact.len() { | ||
| 103 | 1 => { | ||
| 104 | return Ok(Span { | ||
| 105 | start: exact[0], | ||
| 106 | end: exact[0] + old.len(), | ||
| 107 | crlf: false, | ||
| 108 | }) | ||
| 109 | } | ||
| 110 | 0 => {} | ||
| 111 | many => { | ||
| 112 | return Err(format!( | ||
| 113 | "text to replace appears {many} times (lines {}); include more \ | ||
| 114 | surrounding context so it is unique.", | ||
| 115 | line_list(text, &exact) | ||
| 116 | )) | ||
| 117 | } | ||
| 118 | } | ||
| 119 | |||
| 120 | // A CRLF file shows up in `read` with a trailing carriage return the model | ||
| 121 | // cannot see. Retry with line endings normalised rather than reporting | ||
| 122 | // "not found" for text that is visibly there. | ||
| 123 | if text.contains("\r\n") { | ||
| 124 | let normalized = text.replace("\r\n", "\n"); | ||
| 125 | let wanted = old.replace("\r\n", "\n"); | ||
| 126 | let hits: Vec<usize> = normalized | ||
| 127 | .match_indices(&wanted) | ||
| 128 | .map(|(index, _)| index) | ||
| 129 | .collect(); | ||
| 130 | match hits.len() { | ||
| 131 | 1 => { | ||
| 132 | let start = original_offset(text, hits[0]); | ||
| 133 | if let Some(end) = original_range(text, start, &wanted) { | ||
| 134 | return Ok(Span { | ||
| 135 | start, | ||
| 136 | end, | ||
| 137 | crlf: true, | ||
| 138 | }); | ||
| 139 | } | ||
| 140 | } | ||
| 141 | many if many > 1 => { | ||
| 142 | let lines: Vec<String> = hits | ||
| 143 | .iter() | ||
| 144 | .take(10) | ||
| 145 | .map(|hit| (normalized[..*hit].matches('\n').count() + 1).to_string()) | ||
| 146 | .collect(); | ||
| 147 | return Err(format!( | ||
| 148 | "text to replace appears {many} times in this CRLF file (lines {}); \ | ||
| 149 | include more surrounding context so it is unique.", | ||
| 150 | lines.join(", ") | ||
| 151 | )); | ||
| 152 | } | ||
| 153 | _ => {} | ||
| 154 | } | ||
| 155 | } | ||
| 156 | |||
| 157 | Err("text to replace was not found. Read the file and copy the exact text, \ | ||
| 158 | including indentation." | ||
| 159 | .to_string()) | ||
| 160 | } | ||
| 161 | |||
| 162 | /// Byte offset in the original text for an offset in the CRLF-normalised text. | ||
| 163 | fn original_offset(text: &str, target: usize) -> usize { | ||
| 164 | let bytes = text.as_bytes(); | ||
| 165 | let mut original = 0usize; | ||
| 166 | let mut normalized = 0usize; | ||
| 167 | while original < bytes.len() && normalized < target { | ||
| 168 | if bytes[original] == b'\r' && bytes.get(original + 1) == Some(&b'\n') { | ||
| 169 | original += 2; | ||
| 170 | } else { | ||
| 171 | original += 1; | ||
| 172 | } | ||
| 173 | normalized += 1; | ||
| 174 | } | ||
| 175 | original | ||
| 176 | } | ||
| 177 | |||
| 178 | /// End offset in the original text for a normalised match of `wanted`. | ||
| 179 | fn original_range(text: &str, start: usize, wanted: &str) -> Option<usize> { | ||
| 180 | let bytes = text.as_bytes(); | ||
| 181 | let mut cursor = start; | ||
| 182 | for byte in wanted.bytes() { | ||
| 183 | if byte == b'\n' { | ||
| 184 | if bytes.get(cursor) == Some(&b'\r') && bytes.get(cursor + 1) == Some(&b'\n') { | ||
| 185 | cursor += 2; | ||
| 186 | } else if bytes.get(cursor) == Some(&b'\n') { | ||
| 187 | cursor += 1; | ||
| 188 | } else { | ||
| 189 | return None; | ||
| 190 | } | ||
| 191 | } else { | ||
| 192 | if bytes.get(cursor) != Some(&byte) { | ||
| 193 | return None; | ||
| 194 | } | ||
| 195 | cursor += 1; | ||
| 196 | } | ||
| 197 | } | ||
| 198 | Some(cursor) | ||
| 199 | } | ||
| 200 | |||
| 201 | /// Write via a temporary file and rename, so a crash or a full disk leaves the | ||
| 202 | /// original intact instead of a half-written file. | ||
| 203 | fn atomic_write(path: &str, content: &str) -> Result<(), String> { | ||
| 204 | let target = Path::new(path); | ||
| 205 | let parent = match target.parent() { | ||
| 206 | Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(), | ||
| 207 | _ => PathBuf::from("."), | ||
| 208 | }; | ||
| 209 | let temp = parent.join(format!( | ||
| 210 | ".agent686-{}-{}.tmp", | ||
| 211 | std::process::id(), | ||
| 212 | TEMP_COUNTER.fetch_add(1, Ordering::Relaxed) | ||
| 213 | )); | ||
| 214 | |||
| 215 | fs::write(&temp, content).map_err(|e| format!("{}: {e}", temp.display()))?; | ||
| 216 | if let Ok(meta) = fs::metadata(target) { | ||
| 217 | let _ = fs::set_permissions(&temp, meta.permissions()); | ||
| 218 | } | ||
| 219 | if let Err(error) = fs::rename(&temp, target) { | ||
| 220 | let _ = fs::remove_file(&temp); | ||
| 221 | return Err(format!("{path}: {error}")); | ||
| 222 | } | ||
| 223 | Ok(()) | ||
| 224 | } | ||
| 225 | |||
| 226 | static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0); | ||
| 227 | |||
| 95 | pub fn plan_write(args: &Value) -> Result<Change, String> { | 228 | pub fn plan_write(args: &Value) -> Result<Change, String> { |
| 96 | Ok(Change::Write { | 229 | Ok(Change::Write { |
| 97 | path: req(args, "path")?, | 230 | path: req(args, "path")?, |
| @@ -107,33 +240,16 @@ pub fn plan_edit(args: &Value) -> Result<Change, String> { | |||
| 107 | return Err("`old` must not be empty; use write to create a file".into()); | 240 | return Err("`old` must not be empty; use write to create a file".into()); |
| 108 | } | 241 | } |
| 109 | let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; | 242 | let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; |
| 110 | let hits: Vec<usize> = text.match_indices(&old).map(|(i, _)| i).collect(); | 243 | // Fail before the approval prompt if the match is unusable. |
| 111 | match hits.len() { | 244 | locate(&text, &old)?; |
| 112 | 0 => Err(format!( | 245 | Ok(Change::Edit { path, old, new }) |
| 113 | "text to replace was not found in {path}. Read the file and copy the exact \ | ||
| 114 | text, including indentation." | ||
| 115 | )), | ||
| 116 | 1 => Ok(Change::Edit { | ||
| 117 | path, | ||
| 118 | old, | ||
| 119 | new, | ||
| 120 | text, | ||
| 121 | }), | ||
| 122 | n => Err(format!( | ||
| 123 | "text to replace appears {n} times in {path} (lines {}); include more \ | ||
| 124 | surrounding context so it is unique.", | ||
| 125 | line_list(&text, &hits) | ||
| 126 | )), | ||
| 127 | } | ||
| 128 | } | 246 | } |
| 129 | 247 | ||
| 130 | pub fn read(args: &Value) -> Result<String, String> { | 248 | pub fn read(args: &Value) -> Result<String, String> { |
| 131 | let path = req(args, "path")?; | 249 | let path = req(args, "path")?; |
| 132 | let offset = args | 250 | let offset = args.get("offset").and_then(|v| v.as_u64()).unwrap_or(1).max(1); |
| 133 | .get("offset") | 251 | let offset = usize::try_from(offset) |
| 134 | .and_then(|v| v.as_u64()) | 252 | .map_err(|_| format!("offset {offset} is too large for this build"))?; |
| 135 | .unwrap_or(1) | ||
| 136 | .max(1) as usize; | ||
| 137 | let limit = args | 253 | let limit = args |
| 138 | .get("limit") | 254 | .get("limit") |
| 139 | .and_then(|v| v.as_u64()) | 255 | .and_then(|v| v.as_u64()) |
| @@ -144,6 +260,11 @@ pub fn read(args: &Value) -> Result<String, String> { | |||
| 144 | if meta.is_dir() { | 260 | if meta.is_dir() { |
| 145 | return Err(format!("{path} is a directory; use glob or grep")); | 261 | return Err(format!("{path} is a directory; use glob or grep")); |
| 146 | } | 262 | } |
| 263 | if !meta.is_file() { | ||
| 264 | // A FIFO or a device would block forever, and this process is single | ||
| 265 | // threaded, so nothing could interrupt it. | ||
| 266 | return Err(format!("{path} is not a regular file")); | ||
| 267 | } | ||
| 147 | 268 | ||
| 148 | let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?; | 269 | let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?; |
| 149 | let mut reader = BufReader::with_capacity(64 * 1024, file); | 270 | let mut reader = BufReader::with_capacity(64 * 1024, file); |
| @@ -331,6 +452,9 @@ pub fn grep(args: &Value) -> Result<String, String> { | |||
| 331 | }; | 452 | }; |
| 332 | 453 | ||
| 333 | let root = Path::new(&base); | 454 | let root = Path::new(&base); |
| 455 | if !root.exists() { | ||
| 456 | return Err(format!("{base}: no such file or directory")); | ||
| 457 | } | ||
| 334 | let files = if root.is_file() { | 458 | let files = if root.is_file() { |
| 335 | vec![root.to_path_buf()] | 459 | vec![root.to_path_buf()] |
| 336 | } else { | 460 | } else { |
| @@ -341,19 +465,32 @@ pub fn grep(args: &Value) -> Result<String, String> { | |||
| 341 | 465 | ||
| 342 | let mut out = String::new(); | 466 | let mut out = String::new(); |
| 343 | let mut matches = 0usize; | 467 | let mut matches = 0usize; |
| 468 | let mut skipped = 0usize; | ||
| 344 | for file in files { | 469 | for file in files { |
| 345 | if matches >= MAX_MATCHES { | 470 | if matches >= MAX_MATCHES { |
| 346 | break; | 471 | break; |
| 347 | } | 472 | } |
| 348 | grep_file(&file, &matcher, &mut matches, &mut out); | 473 | grep_file(&file, &matcher, &mut matches, &mut skipped, &mut out); |
| 349 | } | 474 | } |
| 350 | 475 | ||
| 351 | if matches == 0 { | 476 | if matches == 0 { |
| 352 | return Ok(format!("no matches for `{pattern}` under {base}")); | 477 | let mut message = format!("no matches for `{pattern}` under {base}"); |
| 478 | if skipped > 0 { | ||
| 479 | message.push_str(&format!( | ||
| 480 | "\n({skipped} file(s) not searched: larger than 4 MiB or binary)" | ||
| 481 | )); | ||
| 482 | } | ||
| 483 | return Ok(message); | ||
| 353 | } | 484 | } |
| 354 | if matches >= MAX_MATCHES { | 485 | if matches >= MAX_MATCHES { |
| 355 | out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); | 486 | out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); |
| 356 | } | 487 | } |
| 488 | if skipped > 0 { | ||
| 489 | out.push_str(&format!( | ||
| 490 | "({skipped} file(s) not searched: larger than {} or binary)\n", | ||
| 491 | "4 MiB" | ||
| 492 | )); | ||
| 493 | } | ||
| 357 | Ok(out) | 494 | Ok(out) |
| 358 | } | 495 | } |
| 359 | 496 | ||
| @@ -410,12 +547,19 @@ pub fn glob(args: &Value) -> Result<String, String> { | |||
| 410 | Ok(out) | 547 | Ok(out) |
| 411 | } | 548 | } |
| 412 | 549 | ||
| 413 | fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String) { | 550 | fn grep_file( |
| 551 | path: &Path, | ||
| 552 | matcher: &Matcher, | ||
| 553 | count: &mut usize, | ||
| 554 | skipped: &mut usize, | ||
| 555 | out: &mut String, | ||
| 556 | ) { | ||
| 414 | let meta = match fs::metadata(path) { | 557 | let meta = match fs::metadata(path) { |
| 415 | Ok(m) => m, | 558 | Ok(m) => m, |
| 416 | Err(_) => return, | 559 | Err(_) => return, |
| 417 | }; | 560 | }; |
| 418 | if meta.len() > MAX_SCAN_BYTES { | 561 | if meta.len() > MAX_SCAN_BYTES { |
| 562 | *skipped += 1; | ||
| 419 | return; | 563 | return; |
| 420 | } | 564 | } |
| 421 | let bytes = match fs::read(path) { | 565 | let bytes = match fs::read(path) { |
| @@ -423,6 +567,7 @@ fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String | |||
| 423 | Err(_) => return, | 567 | Err(_) => return, |
| 424 | }; | 568 | }; |
| 425 | if bytes.iter().take(8192).any(|&b| b == 0) { | 569 | if bytes.iter().take(8192).any(|&b| b == 0) { |
| 570 | *skipped += 1; | ||
| 426 | return; | 571 | return; |
| 427 | } | 572 | } |
| 428 | let text = String::from_utf8_lossy(&bytes); | 573 | let text = String::from_utf8_lossy(&bytes); |
| @@ -462,6 +607,11 @@ fn walk(dir: &Path, out: &mut Vec<PathBuf>) { | |||
| 462 | walk(&path, out); | 607 | walk(&path, out); |
| 463 | } else if file_type.is_file() { | 608 | } else if file_type.is_file() { |
| 464 | out.push(path); | 609 | out.push(path); |
| 610 | } else if file_type.is_symlink() && fs::metadata(&path).map(|m| m.is_file()).unwrap_or(false) | ||
| 611 | { | ||
| 612 | // Follow file symlinks; symlinked directories are skipped so a loop | ||
| 613 | // cannot walk forever. | ||
| 614 | out.push(path); | ||
| 465 | } | 615 | } |
| 466 | } | 616 | } |
| 467 | } | 617 | } |
| @@ -582,9 +732,9 @@ fn diff_preview(old: &str, new: &str) -> String { | |||
| 582 | out | 732 | out |
| 583 | } | 733 | } |
| 584 | 734 | ||
| 585 | fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String { | 735 | fn edit_preview(path: &str, text: &str, span: &Span, old: &str, new: &str) -> String { |
| 586 | let lines: Vec<&str> = text.lines().collect(); | 736 | let lines: Vec<&str> = text.lines().collect(); |
| 587 | let line_no = text[..at].matches('\n').count() + 1; | 737 | let line_no = text[..span.start].matches('\n').count() + 1; |
| 588 | let old_lines = old.lines().count().max(1); | 738 | let old_lines = old.lines().count().max(1); |
| 589 | 739 | ||
| 590 | let mut out = format!("@@ {path}:{line_no} @@\n"); | 740 | let mut out = format!("@@ {path}:{line_no} @@\n"); |
