From 5563622557ac60b6842f6c09c4c76a5ece9f6d09 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:27:16 +0100 Subject: 0.4.0: grep takes a regular expression, fixed=true for literals Invalid patterns explain themselves and point at fixed, rather than failing with a bare regex error the model cannot act on. --- src/tools/fs.rs | 63 +++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 48 insertions(+), 15 deletions(-) (limited to 'src/tools/fs.rs') diff --git a/src/tools/fs.rs b/src/tools/fs.rs index e543cb6..caa3992 100644 --- a/src/tools/fs.rs +++ b/src/tools/fs.rs @@ -268,6 +268,29 @@ fn read_line_limited( } } +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() { @@ -282,10 +305,29 @@ pub fn grep(args: &Value) -> Result { .get("ignore_case") .and_then(|v| v.as_bool()) .unwrap_or(false); - let needle = if ignore_case { - pattern.to_lowercase() + 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 { - pattern.clone() + 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); @@ -303,7 +345,7 @@ pub fn grep(args: &Value) -> Result { if matches >= MAX_MATCHES { break; } - grep_file(&file, &needle, ignore_case, &mut matches, &mut out); + grep_file(&file, &matcher, &mut matches, &mut out); } if matches == 0 { @@ -368,7 +410,7 @@ pub fn glob(args: &Value) -> Result { Ok(out) } -fn grep_file(path: &Path, needle_lower: &str, ignore_case: bool, count: &mut usize, out: &mut String) { +fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String) { let meta = match fs::metadata(path) { Ok(m) => m, Err(_) => return, @@ -384,21 +426,12 @@ fn grep_file(path: &Path, needle_lower: &str, ignore_case: bool, count: &mut usi return; } let text = String::from_utf8_lossy(&bytes); - let mut needle = needle_lower.to_string(); - if !ignore_case { - needle = needle.to_string(); - } for (index, line) in text.lines().enumerate() { if *count >= MAX_MATCHES { return; } - let hit = if ignore_case { - line.to_lowercase().contains(&needle) - } else { - line.contains(&needle) - }; - if hit { + if matcher.is_match(line) { *count += 1; out.push_str(&format!( "{}:{}: {}\n", -- cgit v1.2.3