use std::fs; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use serde_json::Value; const MAX_LINE_CHARS: usize = 400; const MAX_LINE_BYTES: usize = 4096; const MAX_READ_LINES: usize = 2000; const MAX_MATCHES: usize = 200; const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; const PREVIEW_BUDGET: usize = 60; const SKIP_DIRS: &[&str] = &[ ".git", "target", "node_modules", "dist", "build", ".venv", "vendor", ".cache", ]; /// A pending file change. Built and previewed first, applied only after the /// human agrees. pub enum Change { Write { path: String, content: String }, Edit { path: String, old: String, new: String, text: String }, } impl Change { pub fn path(&self) -> &str { match self { Change::Write { path, .. } | Change::Edit { path, .. } => path, } } pub fn preview(&self) -> String { match self { Change::Write { path, content } => 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) } } } pub fn apply(self) -> Result { match self { Change::Write { path, content } => { let parent = Path::new(&path).parent(); if let Some(parent) = parent { if !parent.as_os_str().is_empty() && !parent.is_dir() { return Err(format!( "parent directory does not exist: {} (create it with bash first)", parent.display() )); } } fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?; 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}"))?; Ok(format!("edited {path}: 1 replacement at line {line}")) } } } } pub fn plan_write(args: &Value) -> Result { Ok(Change::Write { path: req(args, "path")?, content: req(args, "content")?, }) } pub fn plan_edit(args: &Value) -> Result { let path = req(args, "path")?; let old = req(args, "old")?; let new = req(args, "new")?; if old.is_empty() { 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) )), } } 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 limit = args .get("limit") .and_then(|v| v.as_u64()) .unwrap_or(MAX_READ_LINES as u64) .clamp(1, MAX_READ_LINES as u64) as usize; let meta = fs::metadata(&path).map_err(|e| format!("{path}: {e}"))?; if meta.is_dir() { return Err(format!("{path} is a directory; use glob or grep")); } let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?; let mut reader = BufReader::with_capacity(64 * 1024, file); if let Ok(head) = reader.fill_buf() { if head.iter().take(8192).any(|&b| b == 0) { return Err(format!( "{path}: looks like a binary file and will not be shown" )); } } // Skip to the first requested line without buffering what is skipped, so a // 500 MB log with offset near the end costs a scan, not a 500 MB allocation. for _ in 1..offset { match skip_line(&mut reader).map_err(|e| format!("{path}: {e}"))? { true => {} false => return Ok(format!("{path} has fewer than {offset} lines")), } } let mut out = String::new(); let mut produced = 0usize; let mut number = offset; while produced < limit { let (bytes, truncated) = match read_line_limited(&mut reader, MAX_LINE_BYTES) .map_err(|e| format!("{path}: {e}"))? { Some(line) => line, None => break, }; let text = String::from_utf8_lossy(&bytes); let text = text.trim_end_matches('\n'); let mut rendered = clip(text, MAX_LINE_CHARS); if truncated { rendered.push_str(" …(line truncated)"); } out.push_str(&format!("{number:>6}\t{rendered}\n")); produced += 1; number += 1; } if produced == 0 { return Ok(if offset == 1 { format!("{path}: empty file") } else { format!("{path} has fewer than {offset} lines") }); } if let Ok(head) = reader.fill_buf() { if !head.is_empty() { out.push_str(&format!("… more lines; continue with offset={number}\n")); } } Ok(out) } /// Consumes one line without keeping it. False at end of file. fn skip_line(reader: &mut R) -> std::io::Result { let mut any = false; loop { let buf = reader.fill_buf()?; if buf.is_empty() { return Ok(any); } any = true; match buf.iter().position(|&b| b == b'\n') { Some(index) => { reader.consume(index + 1); return Ok(true); } None => { let len = buf.len(); reader.consume(len); } } } } /// Reads one line, keeping at most `max` bytes but consuming the whole line. /// Returns `(bytes, truncated)`; `None` at end of file. fn read_line_limited( reader: &mut R, max: usize, ) -> std::io::Result, bool)>> { let mut kept: Vec = Vec::new(); let mut any = false; let mut truncated = false; loop { let buf = reader.fill_buf()?; if buf.is_empty() { return Ok(if any { Some((kept, truncated)) } else { None }); } any = true; let newline = buf.iter().position(|&b| b == b'\n'); let take = match newline { Some(index) => index + 1, None => buf.len(), }; if kept.len() < max { let room = max - kept.len(); let slice = &buf[..take.min(room)]; kept.extend_from_slice(slice); if take > slice.len() { truncated = true; } } else { truncated = true; } reader.consume(take); if newline.is_some() { return Ok(Some((kept, truncated))); } } } enum Matcher { Literal { needle: String, ignore_case: bool }, Regex(regex::Regex), } impl Matcher { fn is_match(&self, line: &str) -> bool { match self { Matcher::Literal { needle, ignore_case, } => { if *ignore_case { line.to_lowercase().contains(needle) } else { line.contains(needle) } } Matcher::Regex(regex) => regex.is_match(line), } } } pub fn grep(args: &Value) -> Result { let pattern = req(args, "pattern")?; if pattern.is_empty() { return Err("pattern must not be empty".into()); } let base = args .get("path") .and_then(|v| v.as_str()) .unwrap_or(".") .to_string(); let ignore_case = args .get("ignore_case") .and_then(|v| v.as_bool()) .unwrap_or(false); let fixed = args.get("fixed").and_then(|v| v.as_bool()).unwrap_or(false); let matcher = if fixed { Matcher::Literal { needle: if ignore_case { pattern.to_lowercase() } else { pattern.clone() }, ignore_case, } } else { Matcher::Regex( regex::RegexBuilder::new(&pattern) .case_insensitive(ignore_case) .build() .map_err(|error| { format!( "invalid regex `{pattern}`: {error}\npass \"fixed\": true to match \ the text literally" ) })?, ) }; let root = Path::new(&base); let files = if root.is_file() { vec![root.to_path_buf()] } else { let mut files = Vec::new(); walk(root, &mut files); files }; let mut out = String::new(); let mut matches = 0usize; for file in files { if matches >= MAX_MATCHES { break; } grep_file(&file, &matcher, &mut matches, &mut out); } if matches == 0 { return Ok(format!("no matches for `{pattern}` under {base}")); } if matches >= MAX_MATCHES { out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); } Ok(out) } pub fn glob(args: &Value) -> Result { let pattern = req(args, "pattern")?; let base = args .get("path") .and_then(|v| v.as_str()) .unwrap_or(".") .to_string(); let root = Path::new(&base); if !root.is_dir() { return Err(format!("not a directory: {base}")); } let mut files = Vec::new(); walk(root, &mut files); // A pattern without a slash is matched against the file name at any depth. let bare = !pattern.contains('/'); let mut hits = Vec::new(); for file in files { let name = file.file_name().and_then(|n| n.to_str()).unwrap_or(""); let hit = if bare { wildcard_match(pattern.as_bytes(), name.as_bytes()) } else { let relative = file .strip_prefix(root) .unwrap_or(&file) .to_string_lossy() .to_string(); glob_match(&pattern, &relative) }; if hit { hits.push(file); if hits.len() >= MAX_MATCHES { break; } } } if hits.is_empty() { return Ok(format!("no files match `{pattern}` under {base}")); } let mut out = String::new(); for hit in &hits { out.push_str(&hit.display().to_string()); out.push('\n'); } if hits.len() >= MAX_MATCHES { out.push_str(&format!("… stopped after {MAX_MATCHES} files\n")); } Ok(out) } fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String) { let meta = match fs::metadata(path) { Ok(m) => m, Err(_) => return, }; if meta.len() > MAX_SCAN_BYTES { return; } let bytes = match fs::read(path) { Ok(b) => b, Err(_) => return, }; if bytes.iter().take(8192).any(|&b| b == 0) { return; } let text = String::from_utf8_lossy(&bytes); for (index, line) in text.lines().enumerate() { if *count >= MAX_MATCHES { return; } if matcher.is_match(line) { *count += 1; out.push_str(&format!( "{}:{}: {}\n", path.display(), index + 1, clip(line.trim_end(), 200) )); } } } fn walk(dir: &Path, out: &mut Vec) { let entries = match fs::read_dir(dir) { Ok(entries) => entries, Err(_) => return, }; for entry in entries.flatten() { let file_type = match entry.file_type() { Ok(t) => t, Err(_) => continue, }; let path = entry.path(); if file_type.is_dir() { let name = entry.file_name(); if SKIP_DIRS.iter().any(|skip| name == *skip) { continue; } walk(&path, out); } else if file_type.is_file() { out.push(path); } } } fn glob_match(pattern: &str, path: &str) -> bool { let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect(); let s: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); match_segments(&p, &s) } fn match_segments(pattern: &[&str], path: &[&str]) -> bool { match pattern.split_first() { None => path.is_empty(), Some((&"**", rest)) => { if match_segments(rest, path) { return true; } for skip in 0..path.len() { if match_segments(rest, &path[skip + 1..]) { return true; } } false } Some((segment, rest)) => match path.split_first() { None => false, Some((name, tail)) => { wildcard_match(segment.as_bytes(), name.as_bytes()) && match_segments(rest, tail) } }, } } fn wildcard_match(pattern: &[u8], text: &[u8]) -> bool { match pattern.split_first() { None => text.is_empty(), Some((&b'*', rest)) => (0..=text.len()).any(|skip| wildcard_match(rest, &text[skip..])), Some((&b'?', rest)) => !text.is_empty() && wildcard_match(rest, &text[1..]), Some((byte, rest)) => match text.split_first() { Some((first, tail)) => first == byte && wildcard_match(rest, tail), None => false, }, } } fn new_file_preview(path: &str, content: &str) -> String { let lines: Vec<&str> = content.lines().collect(); let mut out = format!("@@ new file {path} ({} lines) @@\n", lines.len()); for line in lines.iter().take(PREVIEW_BUDGET) { out.push_str(&format!("+ {}\n", clip(line, 200))); } if lines.len() > PREVIEW_BUDGET { out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET)); } out } fn diff_preview(old: &str, new: &str) -> String { let a: Vec<&str> = old.lines().collect(); let b: Vec<&str> = new.lines().collect(); let mut prefix = 0; while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] { prefix += 1; } let mut suffix = 0; while suffix < a.len().saturating_sub(prefix) && suffix < b.len().saturating_sub(prefix) && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix] { suffix += 1; } let start = prefix.saturating_sub(2); let a_end = a.len() - suffix; let b_end = b.len() - suffix; let mut out = format!( "@@ -{},{} +{},{} @@\n", start + 1, a_end.saturating_sub(start), start + 1, b_end.saturating_sub(start) ); let mut budget = PREVIEW_BUDGET; for line in &a[start..prefix] { if budget == 0 { break; } budget -= 1; out.push_str(&format!(" {}\n", clip(line, 200))); } for line in &a[prefix..a_end] { if budget == 0 { break; } budget -= 1; out.push_str(&format!("- {}\n", clip(line, 200))); } for line in &b[prefix..b_end] { if budget == 0 { break; } budget -= 1; out.push_str(&format!("+ {}\n", clip(line, 200))); } for line in a[a_end..(a_end + 2).min(a.len())].iter() { if budget == 0 { break; } budget -= 1; out.push_str(&format!(" {}\n", clip(line, 200))); } if budget == 0 { out.push_str("… diff truncated\n"); } out } fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String { let lines: Vec<&str> = text.lines().collect(); let line_no = text[..at].matches('\n').count() + 1; let old_lines = old.lines().count().max(1); let mut out = format!("@@ {path}:{line_no} @@\n"); let mut budget = PREVIEW_BUDGET; let before_start = (line_no - 1).saturating_sub(2); for line in &lines[before_start..line_no.saturating_sub(1)] { if budget == 0 { break; } budget -= 1; out.push_str(&format!(" {}\n", clip(line, 200))); } for line in old.lines() { if budget == 0 { break; } budget -= 1; out.push_str(&format!("- {}\n", clip(line, 200))); } for line in new.lines() { if budget == 0 { break; } budget -= 1; out.push_str(&format!("+ {}\n", clip(line, 200))); } let after_start = (line_no - 1 + old_lines).min(lines.len()); for line in &lines[after_start..(after_start + 2).min(lines.len())] { if budget == 0 { break; } budget -= 1; out.push_str(&format!(" {}\n", clip(line, 200))); } if budget == 0 { out.push_str("… diff truncated\n"); } out } fn line_list(text: &str, offsets: &[usize]) -> String { let mut numbers: Vec = offsets .iter() .take(10) .map(|&at| (text[..at].matches('\n').count() + 1).to_string()) .collect(); if offsets.len() > 10 { numbers.push("…".into()); } numbers.join(", ") } fn req(args: &Value, key: &str) -> Result { match args.get(key).and_then(|v| v.as_str()) { Some(value) => Ok(value.to_string()), None => Err(format!("missing required argument `{key}`")), } } fn clip(s: &str, max: usize) -> String { if s.chars().count() <= max { return s.to_string(); } let cut: String = s.chars().take(max).collect(); format!("{cut}…") }