| 1 | //! Search tools: `grep_files` for code search |
| 2 | //! |
| 3 | //! These tools provide powerful code search capabilities within the workspace, |
| 4 | //! similar to ripgrep/grep functionality. |
| 5 | |
| 6 | use super::file::{SEARCH_CONTENT_ALIASES, SEARCH_CONTENT_PARAMS}; |
| 7 | use super::spec::{ |
| 8 | ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, optional_bool, optional_str, |
| 9 | optional_u64, required_str, |
| 10 | }; |
| 11 | use async_trait::async_trait; |
| 12 | use codewhale_tools::param_alias::{PATH_ALIASES, apply_param_aliases}; |
| 13 | use regex::Regex; |
| 14 | use serde::{Deserialize, Serialize}; |
| 15 | use serde_json::{Value, json}; |
| 16 | use std::collections::{HashSet, VecDeque}; |
| 17 | use std::fs; |
| 18 | use std::io::BufRead; |
| 19 | use std::path::{Path, PathBuf}; |
| 20 | use std::time::Duration; |
| 21 | use tokio_util::sync::CancellationToken; |
| 22 | |
| 23 | /// Maximum number of results to return to avoid overwhelming output |
| 24 | const MAX_RESULTS: usize = 100; |
| 25 | const MAX_RESULTS_LIMIT: usize = 1_000; |
| 26 | |
| 27 | /// Maximum file size to search (skip large binaries) |
| 28 | const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024; // 10MB |
| 29 | |
| 30 | /// Hard cap on a single grep_files run. The directory walk plus per-file regex |
| 31 | /// is synchronous blocking work; without this it can run for minutes on a large |
| 32 | /// tree. Mirrors the file_search tool so both blocking searches behave the same. |
| 33 | const GREP_FILES_TIMEOUT: Duration = Duration::from_secs(30); |
| 34 | |
| 35 | const GREP_LINE_MAX_BYTES: usize = 800; |
| 36 | |
| 37 | /// Result of a grep match |
| 38 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 39 | pub struct GrepMatch { |
| 40 | pub file: String, |
| 41 | pub line_number: usize, |
| 42 | pub line: String, |
| 43 | pub context_before: Vec<String>, |
| 44 | pub context_after: Vec<String>, |
| 45 | } |
| 46 | |
| 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 48 | enum GrepMode { |
| 49 | Matches, |
| 50 | FilesOnly, |
| 51 | Count, |
| 52 | } |
| 53 | |
| 54 | #[derive(Debug, Clone, Serialize)] |
| 55 | struct GrepFileCount { |
| 56 | file: String, |
| 57 | count: usize, |
| 58 | } |
| 59 | |
| 60 | fn default_exclude_patterns() -> Vec<String> { |
| 61 | vec![ |
| 62 | "node_modules".to_string(), |
| 63 | "node_modules/*".to_string(), |
| 64 | ".git".to_string(), |
| 65 | ".git/*".to_string(), |
| 66 | "target".to_string(), |
| 67 | "target/*".to_string(), |
| 68 | "*.min.js".to_string(), |
| 69 | "*.min.css".to_string(), |
| 70 | "dist".to_string(), |
| 71 | "dist/*".to_string(), |
| 72 | "build".to_string(), |
| 73 | "build/*".to_string(), |
| 74 | "__pycache__".to_string(), |
| 75 | "__pycache__/*".to_string(), |
| 76 | ".venv".to_string(), |
| 77 | ".venv/*".to_string(), |
| 78 | "venv".to_string(), |
| 79 | "venv/*".to_string(), |
| 80 | ] |
| 81 | } |
| 82 | |
| 83 | fn parse_grep_mode(input: &Value) -> Result<GrepMode, ToolError> { |
| 84 | match optional_str(input, "mode")? { |
| 85 | None | Some("matches") => Ok(GrepMode::Matches), |
| 86 | Some("files_only") => Ok(GrepMode::FilesOnly), |
| 87 | Some("count") => Ok(GrepMode::Count), |
| 88 | Some(other) => Err(ToolError::invalid_input(format!( |
| 89 | "Invalid grep_files mode \"{other}\"; expected one of: \"matches\", \"files_only\", \"count\"" |
| 90 | ))), |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// Tool for searching files using regex patterns |
| 95 | pub struct GrepFilesTool; |
| 96 | |
| 97 | #[async_trait] |
| 98 | impl ToolSpec for GrepFilesTool { |
| 99 | fn name(&self) -> &'static str { |
| 100 | "grep_files" |
| 101 | } |
| 102 | |
| 103 | fn model_visible(&self) -> bool { |
| 104 | true |
| 105 | } |
| 106 | |
| 107 | fn description(&self) -> &'static str { |
| 108 | "Search for a regex pattern in workspace files. The pure-Rust search skips common non-code directories by default (additional exclude globs append unless replace_default_excludes=true). Supports mode=\"matches\" (default, 0 context lines unless context_lines is set), \"files_only\", and \"count\"." |
| 109 | } |
| 110 | |
| 111 | fn input_schema(&self) -> Value { |
| 112 | json!({ |
| 113 | "type": "object", |
| 114 | "properties": { |
| 115 | "pattern": { |
| 116 | "type": "string", |
| 117 | "description": "Regular expression pattern to search for" |
| 118 | }, |
| 119 | "path": { |
| 120 | "type": "string", |
| 121 | "description": "Directory or file to search (relative to workspace, default: .)" |
| 122 | }, |
| 123 | "include": { |
| 124 | "type": "array", |
| 125 | "items": {"type": "string"}, |
| 126 | "description": "Glob patterns for files to include (e.g., ['*.rs', '*.ts'])" |
| 127 | }, |
| 128 | "exclude": { |
| 129 | "type": "array", |
| 130 | "items": {"type": "string"}, |
| 131 | "description": "Extra exclusion globs appended to defaults (unless replace_default_excludes=true)." |
| 132 | }, |
| 133 | "replace_default_excludes": { |
| 134 | "type": "boolean", |
| 135 | "description": "If true, exclude replaces the default non-code directory exclusions instead of appending (default: false)." |
| 136 | }, |
| 137 | "mode": { |
| 138 | "type": "string", |
| 139 | "enum": ["matches", "files_only", "count"], |
| 140 | "description": "Output mode: \"matches\" (default, matching lines), \"files_only\" (unique matching file paths), or \"count\" (per-file match counts)." |
| 141 | }, |
| 142 | "context_lines": { |
| 143 | "type": "integer", |
| 144 | "description": "Context lines before and after each match (default: 0)." |
| 145 | }, |
| 146 | "case_insensitive": { |
| 147 | "type": "boolean", |
| 148 | "description": "Whether to perform case-insensitive matching (default: false)" |
| 149 | }, |
| 150 | "max_results": { |
| 151 | "type": "integer", |
| 152 | "maximum": MAX_RESULTS_LIMIT, |
| 153 | "description": "Max matches (or files in files_only/count) to return (default: 100, max: 1000)." |
| 154 | } |
| 155 | }, |
| 156 | "required": ["pattern"] |
| 157 | }) |
| 158 | } |
| 159 | |
| 160 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 161 | vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable] |
| 162 | } |
| 163 | |
| 164 | fn supports_parallel(&self) -> bool { |
| 165 | true |
| 166 | } |
| 167 | |
| 168 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 169 | let mut input = input; |
| 170 | apply_param_aliases(&mut input, PATH_ALIASES, "File search_content")?; |
| 171 | apply_param_aliases(&mut input, SEARCH_CONTENT_ALIASES, "File search_content")?; |
| 172 | SEARCH_CONTENT_PARAMS.reject_unknown(&input)?; |
| 173 | |
| 174 | let pattern_str = required_str(&input, "pattern")?; |
| 175 | let path_str = optional_str(&input, "path")?.unwrap_or("."); |
| 176 | let context_lines = usize::try_from(optional_u64(&input, "context_lines", 0)?) |
| 177 | .unwrap_or(usize::MAX) |
| 178 | .min(1000); |
| 179 | let case_insensitive = optional_bool(&input, "case_insensitive", false)?; |
| 180 | let replace_default_excludes = optional_bool(&input, "replace_default_excludes", false)?; |
| 181 | let mode = parse_grep_mode(&input)?; |
| 182 | let max_results = usize::try_from(optional_u64(&input, "max_results", MAX_RESULTS as u64)?) |
| 183 | .unwrap_or(MAX_RESULTS) |
| 184 | .min(MAX_RESULTS_LIMIT); |
| 185 | |
| 186 | // Parse include patterns |
| 187 | let include_patterns: Vec<String> = input |
| 188 | .get("include") |
| 189 | .and_then(|v| v.as_array()) |
| 190 | .map(|arr| { |
| 191 | arr.iter() |
| 192 | .filter_map(|v| v.as_str().map(String::from)) |
| 193 | .collect() |
| 194 | }) |
| 195 | .unwrap_or_default(); |
| 196 | |
| 197 | let caller_excludes: Vec<String> = input |
| 198 | .get("exclude") |
| 199 | .and_then(|v| v.as_array()) |
| 200 | .map(|arr| { |
| 201 | arr.iter() |
| 202 | .filter_map(|v| v.as_str().map(String::from)) |
| 203 | .collect() |
| 204 | }) |
| 205 | .unwrap_or_default(); |
| 206 | let exclude_patterns = if replace_default_excludes { |
| 207 | caller_excludes |
| 208 | } else { |
| 209 | let mut patterns = default_exclude_patterns(); |
| 210 | patterns.extend(caller_excludes); |
| 211 | patterns |
| 212 | }; |
| 213 | |
| 214 | // Build regex |
| 215 | let regex_pattern = if case_insensitive { |
| 216 | format!("(?i){pattern_str}") |
| 217 | } else { |
| 218 | pattern_str.to_string() |
| 219 | }; |
| 220 | |
| 221 | // Model-supplied: compile through the bounded cache (length cap, |
| 222 | // program/DFA size limits, invalid patterns remembered). |
| 223 | let regex = codewhale_runtime::regex_cache::compile_user_regex(®ex_pattern) |
| 224 | .map_err(|e| ToolError::invalid_input(format!("Invalid regex pattern: {e}")))?; |
| 225 | |
| 226 | let (search_path, workspace_canonical) = |
| 227 | crate::tools::file::resolve_guarded_search_root(context, path_str, "grep_files", true) |
| 228 | .await?; |
| 229 | |
| 230 | let workspace = context.workspace.clone(); |
| 231 | let cancel_token = context.cancel_token.clone(); |
| 232 | let follow_symlinks = context.follow_symlinks && !context.strict_workspace_confinement; |
| 233 | let boundary = crate::tools::file::OpenedReadBoundary::from_context( |
| 234 | context, |
| 235 | "grep_files", |
| 236 | path_str, |
| 237 | workspace_canonical.clone(), |
| 238 | None, |
| 239 | true, |
| 240 | ) |
| 241 | .await; |
| 242 | |
| 243 | let result = run_blocking_grep( |
| 244 | GREP_FILES_TIMEOUT, |
| 245 | cancel_token, |
| 246 | move |worker_cancel_token| { |
| 247 | let cancel_token = Some(&worker_cancel_token); |
| 248 | let workspace_canonical = Some(workspace_canonical); |
| 249 | |
| 250 | let mut results: Vec<GrepMatch> = Vec::new(); |
| 251 | let mut matched_files: Vec<String> = Vec::new(); |
| 252 | let mut file_counts: Vec<GrepFileCount> = Vec::new(); |
| 253 | let mut files_searched = 0; |
| 254 | let mut total_matches = 0; |
| 255 | let mut truncated = false; |
| 256 | let mut unreadable_files = 0usize; |
| 257 | |
| 258 | let skipped_dirs = visit_files( |
| 259 | &search_path, |
| 260 | &include_patterns, |
| 261 | &exclude_patterns, |
| 262 | cancel_token, |
| 263 | follow_symlinks, |
| 264 | &mut |file_path| { |
| 265 | let budget_reached = match mode { |
| 266 | GrepMode::Matches => results.len() >= max_results, |
| 267 | GrepMode::FilesOnly => matched_files.len() >= max_results, |
| 268 | GrepMode::Count => file_counts.len() >= max_results, |
| 269 | }; |
| 270 | if truncated || budget_reached { |
| 271 | truncated = true; |
| 272 | return Ok(WalkControl::Stop); |
| 273 | } |
| 274 | check_cancelled(cancel_token)?; |
| 275 | |
| 276 | let file = match crate::tools::file::open_verified_search_file( |
| 277 | file_path, |
| 278 | &boundary, |
| 279 | follow_symlinks, |
| 280 | ) { |
| 281 | Ok(file) => file, |
| 282 | Err(_) => { |
| 283 | unreadable_files += 1; |
| 284 | return Ok(WalkControl::Continue); |
| 285 | } |
| 286 | }; |
| 287 | |
| 288 | if file |
| 289 | .metadata() |
| 290 | .is_ok_and(|metadata| metadata.len() > MAX_FILE_SIZE) |
| 291 | { |
| 292 | return Ok(WalkControl::Continue); |
| 293 | } |
| 294 | |
| 295 | let relative_path = file_path |
| 296 | .strip_prefix(&workspace) |
| 297 | .ok() |
| 298 | .or_else(|| { |
| 299 | workspace_canonical |
| 300 | .as_deref() |
| 301 | .and_then(|canonical| file_path.strip_prefix(canonical).ok()) |
| 302 | }) |
| 303 | .unwrap_or(file_path) |
| 304 | .to_string_lossy() |
| 305 | .to_string(); |
| 306 | |
| 307 | match mode { |
| 308 | GrepMode::Matches => { |
| 309 | let budget = max_results.saturating_sub(results.len()); |
| 310 | let (file_matches, overflowed) = match search_file_streaming( |
| 311 | file, |
| 312 | &relative_path, |
| 313 | ®ex, |
| 314 | context_lines, |
| 315 | budget, |
| 316 | cancel_token, |
| 317 | )? { |
| 318 | FileScan::Scanned { |
| 319 | matches, |
| 320 | overflowed, |
| 321 | } => (matches, overflowed), |
| 322 | FileScan::NotText => return Ok(WalkControl::Continue), |
| 323 | FileScan::Unreadable => { |
| 324 | unreadable_files += 1; |
| 325 | return Ok(WalkControl::Continue); |
| 326 | } |
| 327 | }; |
| 328 | |
| 329 | files_searched += 1; |
| 330 | total_matches += file_matches.len(); |
| 331 | results.extend(file_matches); |
| 332 | if overflowed { |
| 333 | truncated = true; |
| 334 | return Ok(WalkControl::Stop); |
| 335 | } |
| 336 | } |
| 337 | GrepMode::FilesOnly => { |
| 338 | let matched = match scan_file_match_count( |
| 339 | file, |
| 340 | ®ex, |
| 341 | true, |
| 342 | cancel_token, |
| 343 | )? { |
| 344 | FileCountScan::Scanned(count) => count > 0, |
| 345 | FileCountScan::NotText => return Ok(WalkControl::Continue), |
| 346 | FileCountScan::Unreadable => { |
| 347 | unreadable_files += 1; |
| 348 | return Ok(WalkControl::Continue); |
| 349 | } |
| 350 | }; |
| 351 | files_searched += 1; |
| 352 | if matched { |
| 353 | matched_files.push(relative_path); |
| 354 | } |
| 355 | } |
| 356 | GrepMode::Count => { |
| 357 | let count = |
| 358 | match scan_file_match_count(file, ®ex, false, cancel_token)? |
| 359 | { |
| 360 | FileCountScan::Scanned(count) => count, |
| 361 | FileCountScan::NotText => return Ok(WalkControl::Continue), |
| 362 | FileCountScan::Unreadable => { |
| 363 | unreadable_files += 1; |
| 364 | return Ok(WalkControl::Continue); |
| 365 | } |
| 366 | }; |
| 367 | files_searched += 1; |
| 368 | if count > 0 { |
| 369 | total_matches += count; |
| 370 | file_counts.push(GrepFileCount { |
| 371 | file: relative_path, |
| 372 | count, |
| 373 | }); |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | Ok(WalkControl::Continue) |
| 378 | }, |
| 379 | )?; |
| 380 | |
| 381 | let mut output = match mode { |
| 382 | GrepMode::Matches => { |
| 383 | let matches_json: Vec<Value> = results |
| 384 | .iter() |
| 385 | .map(|item| grep_match_to_json(item, context_lines)) |
| 386 | .collect(); |
| 387 | json!({ |
| 388 | "matches": matches_json, |
| 389 | "total_matches": total_matches, |
| 390 | "files_searched": files_searched, |
| 391 | "truncated": truncated, |
| 392 | }) |
| 393 | } |
| 394 | GrepMode::FilesOnly => { |
| 395 | matched_files.sort_unstable(); |
| 396 | let total_files = matched_files.len(); |
| 397 | json!({ |
| 398 | "files": matched_files, |
| 399 | "total_files": total_files, |
| 400 | "files_searched": files_searched, |
| 401 | "truncated": truncated, |
| 402 | }) |
| 403 | } |
| 404 | GrepMode::Count => { |
| 405 | file_counts.sort_by(|a, b| { |
| 406 | b.count.cmp(&a.count).then_with(|| a.file.cmp(&b.file)) |
| 407 | }); |
| 408 | let total_files = file_counts.len(); |
| 409 | json!({ |
| 410 | "counts": file_counts, |
| 411 | "total_matches": total_matches, |
| 412 | "total_files": total_files, |
| 413 | "files_searched": files_searched, |
| 414 | "truncated": truncated, |
| 415 | }) |
| 416 | } |
| 417 | }; |
| 418 | if truncated { |
| 419 | output["max_results"] = json!(max_results); |
| 420 | } |
| 421 | // Anything the walk could not read (a directory, a directory |
| 422 | // entry, or a file) is counted so the caller knows coverage was |
| 423 | // incomplete rather than reading silence as "no matches there". |
| 424 | let unreadable = skipped_dirs + unreadable_files; |
| 425 | if unreadable > 0 { |
| 426 | output["unreadable_paths_skipped"] = json!(unreadable); |
| 427 | } |
| 428 | Ok(output) |
| 429 | }, |
| 430 | ) |
| 431 | .await?; |
| 432 | |
| 433 | ToolResult::json(&result).map_err(|e| ToolError::execution_failed(e.to_string())) |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | /// Run the synchronous grep walk on a blocking worker, cancellable via the |
| 438 | /// token and bounded by `timeout`. Mirrors `run_blocking_file_search`. |
| 439 | async fn run_blocking_grep<F>( |
| 440 | timeout: Duration, |
| 441 | cancel_token: Option<CancellationToken>, |
| 442 | search: F, |
| 443 | ) -> Result<Value, ToolError> |
| 444 | where |
| 445 | F: FnOnce(CancellationToken) -> Result<Value, ToolError> + Send + 'static, |
| 446 | { |
| 447 | if cancel_token |
| 448 | .as_ref() |
| 449 | .is_some_and(CancellationToken::is_cancelled) |
| 450 | { |
| 451 | return Err(grep_cancelled()); |
| 452 | } |
| 453 | |
| 454 | let worker_cancel_token = cancel_token |
| 455 | .as_ref() |
| 456 | .map(CancellationToken::child_token) |
| 457 | .unwrap_or_default(); |
| 458 | let _worker_cancel_guard = worker_cancel_token.clone().drop_guard(); |
| 459 | let task = tokio::task::spawn_blocking(move || search(worker_cancel_token)); |
| 460 | let result = match cancel_token { |
| 461 | Some(token) => { |
| 462 | tokio::select! { |
| 463 | biased; |
| 464 | () = token.cancelled() => return Err(grep_cancelled()), |
| 465 | result = tokio::time::timeout(timeout, task) => result, |
| 466 | } |
| 467 | } |
| 468 | None => tokio::time::timeout(timeout, task).await, |
| 469 | }; |
| 470 | |
| 471 | let joined = result.map_err(|_| grep_timeout(timeout))?; |
| 472 | joined.map_err(|err| { |
| 473 | ToolError::execution_failed(format!("grep_files worker failed before completion: {err}")) |
| 474 | })? |
| 475 | } |
| 476 | |
| 477 | fn grep_cancelled() -> ToolError { |
| 478 | ToolError::cancelled("grep_files cancelled before completion") |
| 479 | } |
| 480 | |
| 481 | fn grep_timeout(timeout: Duration) -> ToolError { |
| 482 | ToolError::Timeout { |
| 483 | seconds: timeout.as_secs().max(1), |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | fn floor_char_boundary(text: &str, index: usize) -> usize { |
| 488 | let mut index = index.min(text.len()); |
| 489 | while !text.is_char_boundary(index) { |
| 490 | index -= 1; |
| 491 | } |
| 492 | index |
| 493 | } |
| 494 | |
| 495 | fn clip_grep_line(line: &str, focus: Option<(usize, usize)>) -> String { |
| 496 | if line.len() <= GREP_LINE_MAX_BYTES { |
| 497 | return line.to_string(); |
| 498 | } |
| 499 | let (match_start, match_end) = focus.unwrap_or((0, 0)); |
| 500 | let match_len = match_end.saturating_sub(match_start); |
| 501 | let lead = GREP_LINE_MAX_BYTES.saturating_sub(match_len) / 2; |
| 502 | let start = if match_len >= GREP_LINE_MAX_BYTES { |
| 503 | match_start |
| 504 | } else { |
| 505 | match_start |
| 506 | .saturating_sub(lead) |
| 507 | .min(line.len() - GREP_LINE_MAX_BYTES) |
| 508 | }; |
| 509 | let start = floor_char_boundary(line, start); |
| 510 | let end = floor_char_boundary(line, start + GREP_LINE_MAX_BYTES); |
| 511 | let mut clipped = String::with_capacity(GREP_LINE_MAX_BYTES + 64); |
| 512 | if start > 0 { |
| 513 | clipped.push_str(&format!("[…{start} bytes] ")); |
| 514 | } |
| 515 | clipped.push_str(&line[start..end]); |
| 516 | if end < line.len() { |
| 517 | clipped.push_str(&format!(" […{} bytes]", line.len() - end)); |
| 518 | } |
| 519 | clipped |
| 520 | } |
| 521 | |
| 522 | fn grep_match_to_json(item: &GrepMatch, context_lines: usize) -> Value { |
| 523 | if context_lines == 0 { |
| 524 | json!({ |
| 525 | "file": item.file, |
| 526 | "line_number": item.line_number, |
| 527 | "line": item.line, |
| 528 | }) |
| 529 | } else if context_lines == 1 { |
| 530 | json!({ |
| 531 | "file": item.file, |
| 532 | "line_number": item.line_number, |
| 533 | "line": item.line, |
| 534 | "context_before": item.context_before.first().cloned().unwrap_or_default(), |
| 535 | "context_after": item.context_after.first().cloned().unwrap_or_default(), |
| 536 | }) |
| 537 | } else { |
| 538 | json!(item) |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | enum FileCountScan { |
| 543 | Scanned(usize), |
| 544 | NotText, |
| 545 | Unreadable, |
| 546 | } |
| 547 | |
| 548 | fn scan_file_match_count( |
| 549 | file: fs::File, |
| 550 | regex: &Regex, |
| 551 | stop_after_first: bool, |
| 552 | cancel_token: Option<&CancellationToken>, |
| 553 | ) -> Result<FileCountScan, ToolError> { |
| 554 | let mut reader = std::io::BufReader::new(file); |
| 555 | let mut raw: Vec<u8> = Vec::new(); |
| 556 | let mut count = 0usize; |
| 557 | |
| 558 | loop { |
| 559 | raw.clear(); |
| 560 | let n = match reader.read_until(b'\n', &mut raw) { |
| 561 | Ok(n) => n, |
| 562 | Err(_) => return Ok(FileCountScan::Unreadable), |
| 563 | }; |
| 564 | if n == 0 { |
| 565 | break; |
| 566 | } |
| 567 | check_cancelled(cancel_token)?; |
| 568 | |
| 569 | let mut end = raw.len(); |
| 570 | if raw[..end].ends_with(b"\n") { |
| 571 | end -= 1; |
| 572 | if raw[..end].ends_with(b"\r") { |
| 573 | end -= 1; |
| 574 | } |
| 575 | } |
| 576 | let Ok(line) = std::str::from_utf8(&raw[..end]) else { |
| 577 | return Ok(FileCountScan::NotText); |
| 578 | }; |
| 579 | |
| 580 | if (!stop_after_first || count == 0) && regex.is_match(line) { |
| 581 | count += 1; |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | Ok(FileCountScan::Scanned(count)) |
| 586 | } |
| 587 | |
| 588 | /// Search a single file line-by-line with a small ring buffer for |
| 589 | /// before-context, so file contents are never fully materialized. |
| 590 | /// |
| 591 | /// Returns [`FileScan::NotText`] when the file contains invalid UTF-8 |
| 592 | /// anywhere (the whole file must be valid before contributing any match) and |
| 593 | /// [`FileScan::Unreadable`] when it cannot be opened or read. At most `budget` matches are |
| 594 | /// recorded; the scan still runs to EOF so late invalid bytes disqualify the |
| 595 | /// file and pending after-context is completed. `overflowed` is true when |
| 596 | /// the file held at least one match beyond `budget`. |
| 597 | fn search_file_streaming( |
| 598 | file: fs::File, |
| 599 | relative_path: &str, |
| 600 | regex: &Regex, |
| 601 | context_lines: usize, |
| 602 | budget: usize, |
| 603 | cancel_token: Option<&CancellationToken>, |
| 604 | ) -> Result<FileScan, ToolError> { |
| 605 | let mut reader = std::io::BufReader::new(file); |
| 606 | let mut raw: Vec<u8> = Vec::new(); |
| 607 | let mut before: VecDeque<String> = VecDeque::new(); |
| 608 | let mut matches: Vec<GrepMatch> = Vec::new(); |
| 609 | // Matches still waiting for after-context lines: (index into `matches`, |
| 610 | // lines still needed). Entries complete in FIFO order. |
| 611 | let mut pending: VecDeque<(usize, usize)> = VecDeque::new(); |
| 612 | let mut line_idx = 0usize; |
| 613 | let mut overflowed = false; |
| 614 | |
| 615 | loop { |
| 616 | raw.clear(); |
| 617 | let n = match reader.read_until(b'\n', &mut raw) { |
| 618 | Ok(n) => n, |
| 619 | Err(_) => return Ok(FileScan::Unreadable), |
| 620 | }; |
| 621 | if n == 0 { |
| 622 | break; |
| 623 | } |
| 624 | check_cancelled(cancel_token)?; |
| 625 | |
| 626 | // Mirror `str::lines`: strip the trailing '\n', and a '\r' only when |
| 627 | // it directly precedes that '\n'. |
| 628 | let mut end = raw.len(); |
| 629 | if raw[..end].ends_with(b"\n") { |
| 630 | end -= 1; |
| 631 | if raw[..end].ends_with(b"\r") { |
| 632 | end -= 1; |
| 633 | } |
| 634 | } |
| 635 | let Ok(line) = std::str::from_utf8(&raw[..end]) else { |
| 636 | return Ok(FileScan::NotText); |
| 637 | }; |
| 638 | |
| 639 | for (idx, remaining) in &mut pending { |
| 640 | matches[*idx].context_after.push(clip_grep_line(line, None)); |
| 641 | *remaining -= 1; |
| 642 | } |
| 643 | while pending |
| 644 | .front() |
| 645 | .is_some_and(|(_, remaining)| *remaining == 0) |
| 646 | { |
| 647 | pending.pop_front(); |
| 648 | } |
| 649 | |
| 650 | if matches.len() >= budget { |
| 651 | overflowed = overflowed || regex.is_match(line); |
| 652 | } else if let Some(found) = regex.find(line) { |
| 653 | matches.push(GrepMatch { |
| 654 | file: relative_path.to_string(), |
| 655 | line_number: line_idx + 1, |
| 656 | line: clip_grep_line(line, Some((found.start(), found.end()))), |
| 657 | context_before: before.iter().cloned().collect(), |
| 658 | context_after: Vec::new(), |
| 659 | }); |
| 660 | if context_lines > 0 { |
| 661 | pending.push_back((matches.len() - 1, context_lines)); |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | if context_lines > 0 { |
| 666 | if before.len() == context_lines { |
| 667 | before.pop_front(); |
| 668 | } |
| 669 | before.push_back(clip_grep_line(line, None)); |
| 670 | } |
| 671 | line_idx += 1; |
| 672 | } |
| 673 | |
| 674 | Ok(FileScan::Scanned { |
| 675 | matches, |
| 676 | overflowed, |
| 677 | }) |
| 678 | } |
| 679 | |
| 680 | /// Outcome of scanning one file. |
| 681 | enum FileScan { |
| 682 | Scanned { |
| 683 | matches: Vec<GrepMatch>, |
| 684 | overflowed: bool, |
| 685 | }, |
| 686 | /// Binary or not valid UTF-8: skipped on purpose. |
| 687 | NotText, |
| 688 | /// Could not be opened or read: skipped, and counted as incomplete coverage. |
| 689 | Unreadable, |
| 690 | } |
| 691 | |
| 692 | /// Flow control for the streaming file walk. |
| 693 | enum WalkControl { |
| 694 | Continue, |
| 695 | Stop, |
| 696 | } |
| 697 | |
| 698 | /// Walk files matching the include/exclude patterns, invoking `visit` for |
| 699 | /// each one in traversal order. The walk stops early when `visit` returns |
| 700 | /// [`WalkControl::Stop`]. Returns how many subdirectories (or entries) could |
| 701 | /// not be read and were skipped; only an unreadable `root` fails the walk. |
| 702 | fn visit_files( |
| 703 | root: &Path, |
| 704 | include_patterns: &[String], |
| 705 | exclude_patterns: &[String], |
| 706 | cancel_token: Option<&CancellationToken>, |
| 707 | follow_symlinks: bool, |
| 708 | visit: &mut dyn FnMut(&Path) -> Result<WalkControl, ToolError>, |
| 709 | ) -> Result<usize, ToolError> { |
| 710 | let mut visited_dirs: HashSet<PathBuf> = HashSet::new(); |
| 711 | let mut skipped = 0usize; |
| 712 | check_cancelled(cancel_token)?; |
| 713 | |
| 714 | if root.is_file() { |
| 715 | visit(root)?; |
| 716 | return Ok(0); |
| 717 | } |
| 718 | |
| 719 | if follow_symlinks && let Ok(canonical_root) = root.canonicalize() { |
| 720 | visited_dirs.insert(canonical_root); |
| 721 | } |
| 722 | |
| 723 | visit_files_recursive( |
| 724 | root, |
| 725 | root, |
| 726 | include_patterns, |
| 727 | exclude_patterns, |
| 728 | cancel_token, |
| 729 | &mut visited_dirs, |
| 730 | follow_symlinks, |
| 731 | &mut skipped, |
| 732 | visit, |
| 733 | )?; |
| 734 | Ok(skipped) |
| 735 | } |
| 736 | |
| 737 | #[allow(clippy::too_many_arguments)] |
| 738 | fn visit_files_recursive( |
| 739 | root: &Path, |
| 740 | current: &Path, |
| 741 | include_patterns: &[String], |
| 742 | exclude_patterns: &[String], |
| 743 | cancel_token: Option<&CancellationToken>, |
| 744 | visited_dirs: &mut HashSet<PathBuf>, |
| 745 | follow_symlinks: bool, |
| 746 | skipped: &mut usize, |
| 747 | visit: &mut dyn FnMut(&Path) -> Result<WalkControl, ToolError>, |
| 748 | ) -> Result<WalkControl, ToolError> { |
| 749 | check_cancelled(cancel_token)?; |
| 750 | |
| 751 | // An unreadable subdirectory (permissions, or removed mid-walk) is |
| 752 | // skipped and counted rather than discarding every match found so far. |
| 753 | // The search root itself still fails loudly. |
| 754 | let entries = match fs::read_dir(current) { |
| 755 | Ok(entries) => entries, |
| 756 | Err(e) if current != root => { |
| 757 | tracing::debug!(dir = %current.display(), error = %e, "grep_files skipped an unreadable directory"); |
| 758 | *skipped += 1; |
| 759 | return Ok(WalkControl::Continue); |
| 760 | } |
| 761 | Err(e) => { |
| 762 | return Err(ToolError::execution_failed(format!( |
| 763 | "Failed to read directory {}: {}", |
| 764 | current.display(), |
| 765 | e |
| 766 | ))); |
| 767 | } |
| 768 | }; |
| 769 | |
| 770 | for entry in entries { |
| 771 | check_cancelled(cancel_token)?; |
| 772 | |
| 773 | let Ok(entry) = entry else { |
| 774 | *skipped += 1; |
| 775 | continue; |
| 776 | }; |
| 777 | let path = entry.path(); |
| 778 | let Ok(file_type) = entry.file_type() else { |
| 779 | *skipped += 1; |
| 780 | continue; |
| 781 | }; |
| 782 | if file_type.is_symlink() && !follow_symlinks { |
| 783 | continue; |
| 784 | } |
| 785 | |
| 786 | // Get relative path for pattern matching. Globs use `/`, so a native |
| 787 | // `\` separator is normalized as file_search does; otherwise |
| 788 | // `src/**` could never match `src\a.rs` on Windows. |
| 789 | let relative = path.strip_prefix(root).unwrap_or(&path); |
| 790 | let relative_str = relative.to_string_lossy(); |
| 791 | let relative_str = if std::path::MAIN_SEPARATOR == '/' { |
| 792 | relative_str |
| 793 | } else { |
| 794 | std::borrow::Cow::Owned(relative_str.replace(std::path::MAIN_SEPARATOR, "/")) |
| 795 | }; |
| 796 | |
| 797 | // Check exclusions |
| 798 | if should_exclude(&relative_str, exclude_patterns) { |
| 799 | continue; |
| 800 | } |
| 801 | |
| 802 | // When following symlinks, resolve the target type for directories |
| 803 | // and files so symlinked dirs are traversed and symlinked files are |
| 804 | // included. |
| 805 | let effective_type = if file_type.is_symlink() && follow_symlinks { |
| 806 | match fs::metadata(&path) { |
| 807 | Ok(meta) => meta.file_type(), |
| 808 | Err(_) => continue, |
| 809 | } |
| 810 | } else { |
| 811 | file_type |
| 812 | }; |
| 813 | |
| 814 | if effective_type.is_dir() { |
| 815 | if codewhale_sandbox::read_guard::active() |
| 816 | .check(&path) |
| 817 | .is_err() |
| 818 | || crate::tools::file::is_codewhale_credential_path(&path) |
| 819 | { |
| 820 | continue; |
| 821 | } |
| 822 | if follow_symlinks { |
| 823 | let canonical_dir = match path.canonicalize() { |
| 824 | Ok(canonical) => canonical, |
| 825 | Err(_) => continue, |
| 826 | }; |
| 827 | if codewhale_sandbox::read_guard::active() |
| 828 | .check(&canonical_dir) |
| 829 | .is_err() |
| 830 | || crate::tools::file::is_codewhale_credential_path(&canonical_dir) |
| 831 | { |
| 832 | continue; |
| 833 | } |
| 834 | if !visited_dirs.insert(canonical_dir) { |
| 835 | continue; |
| 836 | } |
| 837 | } |
| 838 | if let WalkControl::Stop = visit_files_recursive( |
| 839 | root, |
| 840 | &path, |
| 841 | include_patterns, |
| 842 | exclude_patterns, |
| 843 | cancel_token, |
| 844 | visited_dirs, |
| 845 | follow_symlinks, |
| 846 | skipped, |
| 847 | visit, |
| 848 | )? { |
| 849 | return Ok(WalkControl::Stop); |
| 850 | } |
| 851 | } else if effective_type.is_file() { |
| 852 | if let Err(denial) = codewhale_sandbox::read_guard::active().check(&path) { |
| 853 | tracing::debug!( |
| 854 | target: "codewhale::sandbox::read_guard", |
| 855 | requested = %denial.requested.display(), |
| 856 | "sandbox read deny-list skipped a file during search" |
| 857 | ); |
| 858 | continue; |
| 859 | } |
| 860 | if crate::tools::file::is_codewhale_credential_path(&path) { |
| 861 | continue; |
| 862 | } |
| 863 | // Check inclusions (if any specified) |
| 864 | if (include_patterns.is_empty() || should_include(&relative_str, include_patterns)) |
| 865 | && let WalkControl::Stop = visit(&path)? |
| 866 | { |
| 867 | return Ok(WalkControl::Stop); |
| 868 | } |
| 869 | } |
| 870 | } |
| 871 | |
| 872 | Ok(WalkControl::Continue) |
| 873 | } |
| 874 | |
| 875 | fn check_cancelled(cancel_token: Option<&CancellationToken>) -> Result<(), ToolError> { |
| 876 | if cancel_token.is_some_and(CancellationToken::is_cancelled) { |
| 877 | return Err(ToolError::cancelled("search cancelled before completion")); |
| 878 | } |
| 879 | Ok(()) |
| 880 | } |
| 881 | |
| 882 | /// Check if a path matches any of the exclude patterns |
| 883 | fn should_exclude(path: &str, patterns: &[String]) -> bool { |
| 884 | for pattern in patterns { |
| 885 | if matches_glob(path, pattern) { |
| 886 | return true; |
| 887 | } |
| 888 | } |
| 889 | false |
| 890 | } |
| 891 | |
| 892 | /// Check if a path matches any of the include patterns |
| 893 | fn should_include(path: &str, patterns: &[String]) -> bool { |
| 894 | for pattern in patterns { |
| 895 | if matches_glob(path, pattern) { |
| 896 | return true; |
| 897 | } |
| 898 | } |
| 899 | false |
| 900 | } |
| 901 | |
| 902 | const MAX_BRACE_COMBINATIONS: usize = 64; |
| 903 | |
| 904 | /// Simple glob pattern matching |
| 905 | /// Supports: * (any chars), ** (any path), ? (single char), {a,b} (either) |
| 906 | pub fn matches_glob(path: &str, pattern: &str) -> bool { |
| 907 | match expand_braces(pattern) { |
| 908 | Some(alternatives) => alternatives |
| 909 | .iter() |
| 910 | .any(|alt| matches_expanded_glob(path, alt)), |
| 911 | None => matches_expanded_glob(path, pattern), |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | fn matches_expanded_glob(path: &str, pattern: &str) -> bool { |
| 916 | if let Some(mut rest) = pattern.strip_prefix("**/") { |
| 917 | while let Some(shorter) = rest.strip_prefix("**/") { |
| 918 | rest = shorter; |
| 919 | } |
| 920 | if rest.contains('/') { |
| 921 | return std::iter::once(path) |
| 922 | .chain(path.match_indices('/').map(|(i, _)| &path[i + 1..])) |
| 923 | .any(|tail| matches_expanded_glob(tail, rest)); |
| 924 | } |
| 925 | if rest.len() + 3 < pattern.len() { |
| 926 | return matches_expanded_glob(path, &format!("**/{rest}")); |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | if let Some((head, tail)) = pattern.split_once("/**/") |
| 931 | && tail.contains('/') |
| 932 | && !head.contains(['*', '?']) |
| 933 | { |
| 934 | return path |
| 935 | .strip_prefix(head) |
| 936 | .and_then(|rest| rest.strip_prefix('/')) |
| 937 | .is_some_and(|rest| matches_expanded_glob(rest, &format!("**/{tail}"))); |
| 938 | } |
| 939 | |
| 940 | // Handle ** for any path |
| 941 | if pattern.contains("**") { |
| 942 | let parts: Vec<&str> = pattern.split("**").collect(); |
| 943 | if parts.len() == 2 { |
| 944 | let prefix = parts[0].trim_end_matches('/'); |
| 945 | let suffix = parts[1].trim_start_matches('/'); |
| 946 | |
| 947 | // A prefix ending in `/` names a directory: `build/**` covers |
| 948 | // `build` and `build/...`, never `build.rs` or `builders/`. A |
| 949 | // prefix without one (`src/test_**`) is a plain string prefix. |
| 950 | let under_prefix = if parts[0].ends_with('/') { |
| 951 | path == prefix |
| 952 | || path |
| 953 | .strip_prefix(prefix) |
| 954 | .is_some_and(|rest| rest.starts_with('/')) |
| 955 | } else { |
| 956 | path.starts_with(prefix) |
| 957 | }; |
| 958 | if !prefix.is_empty() && !under_prefix { |
| 959 | return false; |
| 960 | } |
| 961 | if !suffix.is_empty() { |
| 962 | if suffix.contains(['*', '?']) { |
| 963 | let filename = path.rsplit('/').next().unwrap_or(path); |
| 964 | return matches_simple_glob(filename, suffix); |
| 965 | } |
| 966 | return path.ends_with(suffix) |
| 967 | || path |
| 968 | .split('/') |
| 969 | .any(|part| matches_simple_glob(part, suffix)); |
| 970 | } |
| 971 | return true; |
| 972 | } |
| 973 | } |
| 974 | |
| 975 | // Handle patterns like "*.rs" - match against filename only |
| 976 | if pattern.starts_with('*') && !pattern.contains('/') { |
| 977 | let filename = path.rsplit('/').next().unwrap_or(path); |
| 978 | return matches_simple_glob(filename, pattern); |
| 979 | } |
| 980 | |
| 981 | // Handle patterns with path components |
| 982 | if pattern.contains('/') { |
| 983 | return matches_simple_glob(path, pattern); |
| 984 | } |
| 985 | |
| 986 | // Match against filename |
| 987 | let filename = path.rsplit('/').next().unwrap_or(path); |
| 988 | matches_simple_glob(filename, pattern) |
| 989 | } |
| 990 | |
| 991 | fn expand_braces(pattern: &str) -> Option<Vec<String>> { |
| 992 | if pattern.matches('{').count() > MAX_BRACE_COMBINATIONS { |
| 993 | return None; |
| 994 | } |
| 995 | let mut leaves = Vec::new(); |
| 996 | if !expand_braces_into(pattern, 0, &mut leaves) || leaves.len() < 2 { |
| 997 | return None; |
| 998 | } |
| 999 | Some(leaves) |
| 1000 | } |
| 1001 | |
| 1002 | fn expand_braces_into(pattern: &str, from: usize, leaves: &mut Vec<String>) -> bool { |
| 1003 | let Some((open, bounds, close)) = next_brace_group(pattern, from) else { |
| 1004 | leaves.push(pattern.to_string()); |
| 1005 | return leaves.len() <= MAX_BRACE_COMBINATIONS; |
| 1006 | }; |
| 1007 | bounds.windows(2).all(|pair| { |
| 1008 | let alternative = &pattern[pair[0] + 1..pair[1]]; |
| 1009 | let expanded = format!("{}{alternative}{}", &pattern[..open], &pattern[close + 1..]); |
| 1010 | expand_braces_into(&expanded, open, leaves) |
| 1011 | }) |
| 1012 | } |
| 1013 | |
| 1014 | fn next_brace_group(pattern: &str, from: usize) -> Option<(usize, Vec<usize>, usize)> { |
| 1015 | let mut search = from; |
| 1016 | while let Some(offset) = pattern[search..].find('{') { |
| 1017 | let open = search + offset; |
| 1018 | let mut depth = 0; |
| 1019 | let mut bounds = vec![open]; |
| 1020 | let mut close = None; |
| 1021 | for (i, c) in pattern[open..].char_indices() { |
| 1022 | match c { |
| 1023 | '{' => depth += 1, |
| 1024 | ',' if depth == 1 => bounds.push(open + i), |
| 1025 | '}' => { |
| 1026 | depth -= 1; |
| 1027 | if depth == 0 { |
| 1028 | close = Some(open + i); |
| 1029 | break; |
| 1030 | } |
| 1031 | } |
| 1032 | _ => {} |
| 1033 | } |
| 1034 | } |
| 1035 | let close = close?; |
| 1036 | if bounds.len() > 1 { |
| 1037 | bounds.push(close); |
| 1038 | return Some((open, bounds, close)); |
| 1039 | } |
| 1040 | search = open + 1; |
| 1041 | } |
| 1042 | None |
| 1043 | } |
| 1044 | |
| 1045 | /// Simple glob matching for single path component |
| 1046 | fn matches_simple_glob(text: &str, pattern: &str) -> bool { |
| 1047 | let text: Vec<char> = text.chars().collect(); |
| 1048 | let pattern: Vec<char> = pattern.chars().collect(); |
| 1049 | let (mut t, mut p) = (0, 0); |
| 1050 | let mut star = None; |
| 1051 | while t < text.len() { |
| 1052 | match pattern.get(p) { |
| 1053 | Some('*') => { |
| 1054 | star = Some((p, t)); |
| 1055 | p += 1; |
| 1056 | } |
| 1057 | Some(&c) if c == '?' || c == text[t] => { |
| 1058 | p += 1; |
| 1059 | t += 1; |
| 1060 | } |
| 1061 | _ => { |
| 1062 | let Some((star_p, star_t)) = star else { |
| 1063 | return false; |
| 1064 | }; |
| 1065 | p = star_p + 1; |
| 1066 | t = star_t + 1; |
| 1067 | star = Some((star_p, t)); |
| 1068 | } |
| 1069 | } |
| 1070 | } |
| 1071 | pattern[p..].iter().all(|&c| c == '*') |
| 1072 | } |
| 1073 | |
| 1074 | // === Unit Tests === |
| 1075 | |
| 1076 | #[cfg(test)] |
| 1077 | mod tests; |
| 1078 |