|
| 1 | +//! "Search in files": finds text or a regex in every file of a working |
| 2 | +//! tree, using ripgrep's own search crates and its `.gitignore`-aware |
| 3 | +//! parallel walker. |
| 4 | +
|
| 5 | +use anyhow::{Context, Result}; |
| 6 | +use grep_matcher::Matcher; |
| 7 | +use grep_regex::{RegexMatcher, RegexMatcherBuilder}; |
| 8 | +use grep_searcher::{sinks::UTF8, BinaryDetection, SearcherBuilder}; |
| 9 | +use ignore::{WalkBuilder, WalkState}; |
| 10 | +use serde::Serialize; |
| 11 | +use std::path::Path; |
| 12 | +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 13 | +use std::sync::{Arc, Mutex}; |
| 14 | + |
| 15 | +/// Files larger than this are skipped (minified bundles, data dumps). |
| 16 | +const MAX_FILE_SIZE: u64 = 4 * 1024 * 1024; |
| 17 | + |
| 18 | +/// Lines longer than this are shown as a window around the first match. |
| 19 | +const MAX_PREVIEW_CHARS: usize = 300; |
| 20 | + |
| 21 | +#[derive(Debug, Clone, Default)] |
| 22 | +pub struct ContentSearchOptions { |
| 23 | + pub regex: bool, |
| 24 | + pub case_sensitive: bool, |
| 25 | + pub whole_word: bool, |
| 26 | + pub max_matches: usize, |
| 27 | +} |
| 28 | + |
| 29 | +#[derive(Debug, Clone, Serialize, PartialEq)] |
| 30 | +pub struct ContentMatch { |
| 31 | + /// Path relative to the searched root, with `/` separators. |
| 32 | + pub path: String, |
| 33 | + /// 1-based line number. |
| 34 | + pub line: u64, |
| 35 | + /// 0-based character column of the first match in the full line. |
| 36 | + pub column: usize, |
| 37 | + /// The line (or a window of a long line), leading whitespace trimmed. |
| 38 | + pub text: String, |
| 39 | + /// `[start, end)` character ranges of the matches within `text`. |
| 40 | + pub ranges: Vec<(usize, usize)>, |
| 41 | +} |
| 42 | + |
| 43 | +#[derive(Debug, Clone, Serialize, PartialEq)] |
| 44 | +pub struct ContentSearchResult { |
| 45 | + pub matches: Vec<ContentMatch>, |
| 46 | + /// True when the search stopped at `max_matches`. |
| 47 | + pub truncated: bool, |
| 48 | +} |
| 49 | + |
| 50 | +fn build_matcher(query: &str, options: &ContentSearchOptions) -> Result<RegexMatcher> { |
| 51 | + let mut builder = RegexMatcherBuilder::new(); |
| 52 | + builder |
| 53 | + .case_insensitive(!options.case_sensitive) |
| 54 | + .word(options.whole_word) |
| 55 | + .fixed_strings(!options.regex) |
| 56 | + .line_terminator(Some(b'\n')); |
| 57 | + builder |
| 58 | + .build(query) |
| 59 | + .with_context(|| format!("invalid search pattern: {query}")) |
| 60 | +} |
| 61 | + |
| 62 | +/// Searches every non-ignored text file under `root` for `query`. |
| 63 | +pub fn search_content( |
| 64 | + root: &str, |
| 65 | + query: &str, |
| 66 | + options: &ContentSearchOptions, |
| 67 | +) -> Result<ContentSearchResult> { |
| 68 | + if query.is_empty() { |
| 69 | + return Ok(ContentSearchResult { |
| 70 | + matches: Vec::new(), |
| 71 | + truncated: false, |
| 72 | + }); |
| 73 | + } |
| 74 | + if !Path::new(root).is_dir() { |
| 75 | + anyhow::bail!("{root} is not a folder"); |
| 76 | + } |
| 77 | + let matcher = build_matcher(query, options)?; |
| 78 | + let max = options.max_matches.max(1); |
| 79 | + let root_path = Path::new(root).to_path_buf(); |
| 80 | + let found = Arc::new(Mutex::new(Vec::<ContentMatch>::new())); |
| 81 | + let count = Arc::new(AtomicUsize::new(0)); |
| 82 | + let truncated = Arc::new(AtomicBool::new(false)); |
| 83 | + |
| 84 | + WalkBuilder::new(&root_path) |
| 85 | + .hidden(false) |
| 86 | + .git_ignore(true) |
| 87 | + .git_global(true) |
| 88 | + .git_exclude(true) |
| 89 | + .require_git(false) |
| 90 | + .max_filesize(Some(MAX_FILE_SIZE)) |
| 91 | + .filter_entry(|entry| entry.file_name() != ".git") |
| 92 | + .build_parallel() |
| 93 | + .run(|| { |
| 94 | + let matcher = matcher.clone(); |
| 95 | + let root_path = root_path.clone(); |
| 96 | + let found = Arc::clone(&found); |
| 97 | + let count = Arc::clone(&count); |
| 98 | + let truncated = Arc::clone(&truncated); |
| 99 | + let mut searcher = SearcherBuilder::new() |
| 100 | + .binary_detection(BinaryDetection::quit(b'\x00')) |
| 101 | + .line_number(true) |
| 102 | + .build(); |
| 103 | + Box::new(move |entry| { |
| 104 | + if truncated.load(Ordering::Relaxed) { |
| 105 | + return WalkState::Quit; |
| 106 | + } |
| 107 | + let Ok(entry) = entry else { |
| 108 | + return WalkState::Continue; |
| 109 | + }; |
| 110 | + if !entry.file_type().is_some_and(|t| t.is_file()) { |
| 111 | + return WalkState::Continue; |
| 112 | + } |
| 113 | + let Ok(rel) = entry.path().strip_prefix(&root_path) else { |
| 114 | + return WalkState::Continue; |
| 115 | + }; |
| 116 | + let rel = rel.to_string_lossy().replace('\\', "/"); |
| 117 | + let mut local = Vec::new(); |
| 118 | + // Unreadable or non-UTF-8 files are just skipped. |
| 119 | + let _ = searcher.search_path( |
| 120 | + &matcher, |
| 121 | + entry.path(), |
| 122 | + UTF8(|line_number, line| { |
| 123 | + if count.fetch_add(1, Ordering::Relaxed) >= max { |
| 124 | + truncated.store(true, Ordering::Relaxed); |
| 125 | + return Ok(false); |
| 126 | + } |
| 127 | + if let Some(m) = make_match(&matcher, &rel, line_number, line) { |
| 128 | + local.push(m); |
| 129 | + } |
| 130 | + Ok(true) |
| 131 | + }), |
| 132 | + ); |
| 133 | + if !local.is_empty() { |
| 134 | + found.lock().unwrap().append(&mut local); |
| 135 | + } |
| 136 | + if truncated.load(Ordering::Relaxed) { |
| 137 | + WalkState::Quit |
| 138 | + } else { |
| 139 | + WalkState::Continue |
| 140 | + } |
| 141 | + }) |
| 142 | + }); |
| 143 | + |
| 144 | + let mut matches = std::mem::take(&mut *found.lock().unwrap()); |
| 145 | + matches.sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line))); |
| 146 | + matches.truncate(max); |
| 147 | + Ok(ContentSearchResult { |
| 148 | + matches, |
| 149 | + truncated: truncated.load(Ordering::Relaxed), |
| 150 | + }) |
| 151 | +} |
| 152 | + |
| 153 | +/// Builds the preview for one matching line: match ranges in characters, |
| 154 | +/// leading whitespace trimmed, and long lines cut down around the match. |
| 155 | +fn make_match( |
| 156 | + matcher: &RegexMatcher, |
| 157 | + path: &str, |
| 158 | + line_number: u64, |
| 159 | + line: &str, |
| 160 | +) -> Option<ContentMatch> { |
| 161 | + let line = line.trim_end_matches(['\n', '\r']); |
| 162 | + let mut byte_ranges = Vec::new(); |
| 163 | + let _ = matcher.find_iter(line.as_bytes(), |m| { |
| 164 | + if m.start() < m.end() { |
| 165 | + byte_ranges.push((m.start(), m.end())); |
| 166 | + } |
| 167 | + true |
| 168 | + }); |
| 169 | + let first = *byte_ranges.first()?; |
| 170 | + |
| 171 | + let to_char = |byte: usize| line[..byte].chars().count(); |
| 172 | + let column = to_char(first.0); |
| 173 | + let mut ranges: Vec<(usize, usize)> = byte_ranges |
| 174 | + .iter() |
| 175 | + .map(|&(s, e)| (to_char(s), to_char(e))) |
| 176 | + .collect(); |
| 177 | + let chars: Vec<char> = line.chars().collect(); |
| 178 | + |
| 179 | + // Trim leading whitespace, or cut a long line to a window that starts a |
| 180 | + // little before the first match. |
| 181 | + let indent = chars.iter().take_while(|c| c.is_whitespace()).count(); |
| 182 | + let (start, prefix) = if chars.len() - indent > MAX_PREVIEW_CHARS { |
| 183 | + let start = column.saturating_sub(40).max(indent); |
| 184 | + (start, if start > indent { "…" } else { "" }) |
| 185 | + } else { |
| 186 | + (indent, "") |
| 187 | + }; |
| 188 | + let end = (start + MAX_PREVIEW_CHARS).min(chars.len()); |
| 189 | + let suffix = if end < chars.len() { "…" } else { "" }; |
| 190 | + let shift = prefix.chars().count(); |
| 191 | + let text = format!( |
| 192 | + "{prefix}{}{suffix}", |
| 193 | + chars[start..end].iter().collect::<String>() |
| 194 | + ); |
| 195 | + ranges = ranges |
| 196 | + .into_iter() |
| 197 | + .filter(|&(s, _)| s >= start && s < end) |
| 198 | + .map(|(s, e)| (s - start + shift, e.min(end) - start + shift)) |
| 199 | + .collect(); |
| 200 | + |
| 201 | + Some(ContentMatch { |
| 202 | + path: path.to_string(), |
| 203 | + line: line_number, |
| 204 | + column, |
| 205 | + text, |
| 206 | + ranges, |
| 207 | + }) |
| 208 | +} |
| 209 | + |
| 210 | +#[cfg(test)] |
| 211 | +mod tests { |
| 212 | + use super::*; |
| 213 | + use std::fs; |
| 214 | + |
| 215 | + fn opts() -> ContentSearchOptions { |
| 216 | + ContentSearchOptions { |
| 217 | + max_matches: 100, |
| 218 | + ..Default::default() |
| 219 | + } |
| 220 | + } |
| 221 | + |
| 222 | + fn tree() -> tempfile::TempDir { |
| 223 | + let dir = tempfile::tempdir().unwrap(); |
| 224 | + let root = dir.path(); |
| 225 | + fs::create_dir_all(root.join("src")).unwrap(); |
| 226 | + fs::create_dir_all(root.join("vendor")).unwrap(); |
| 227 | + fs::write(root.join(".gitignore"), "vendor/\n").unwrap(); |
| 228 | + fs::write( |
| 229 | + root.join("src/a.php"), |
| 230 | + "<?php\n $user = new User();\n// user\n", |
| 231 | + ) |
| 232 | + .unwrap(); |
| 233 | + fs::write(root.join("src/b.txt"), "nothing here\nUSER upper\n").unwrap(); |
| 234 | + fs::write(root.join("vendor/c.php"), "User\n").unwrap(); |
| 235 | + fs::write(root.join("bin.dat"), b"User\x00\x01\x02").unwrap(); |
| 236 | + dir |
| 237 | + } |
| 238 | + |
| 239 | + #[test] |
| 240 | + fn finds_case_insensitive_and_skips_ignored_and_binary() { |
| 241 | + let dir = tree(); |
| 242 | + let r = search_content(dir.path().to_str().unwrap(), "user", &opts()).unwrap(); |
| 243 | + let hits: Vec<_> = r |
| 244 | + .matches |
| 245 | + .iter() |
| 246 | + .map(|m| (m.path.as_str(), m.line)) |
| 247 | + .collect(); |
| 248 | + assert_eq!( |
| 249 | + hits, |
| 250 | + vec![("src/a.php", 2), ("src/a.php", 3), ("src/b.txt", 2)] |
| 251 | + ); |
| 252 | + let first = &r.matches[0]; |
| 253 | + assert_eq!(first.text, "$user = new User();"); |
| 254 | + assert_eq!(first.ranges, vec![(1, 5), (12, 16)]); |
| 255 | + assert_eq!(first.column, 5); |
| 256 | + assert!(!r.truncated); |
| 257 | + } |
| 258 | + |
| 259 | + #[test] |
| 260 | + fn case_sensitive_whole_word_and_regex() { |
| 261 | + let dir = tree(); |
| 262 | + let root = dir.path().to_str().unwrap(); |
| 263 | + let mut o = opts(); |
| 264 | + o.case_sensitive = true; |
| 265 | + let r = search_content(root, "User", &o).unwrap(); |
| 266 | + assert_eq!(r.matches.len(), 1); |
| 267 | + |
| 268 | + let mut o = opts(); |
| 269 | + o.regex = true; |
| 270 | + let r = search_content(root, r"new \w+\(", &o).unwrap(); |
| 271 | + assert_eq!(r.matches.len(), 1); |
| 272 | + assert_eq!(r.matches[0].ranges, vec![(8, 17)]); |
| 273 | + |
| 274 | + assert!(search_content(root, "(", &o).is_err()); |
| 275 | + } |
| 276 | + |
| 277 | + #[test] |
| 278 | + fn stops_at_max_matches() { |
| 279 | + let dir = tree(); |
| 280 | + let mut o = opts(); |
| 281 | + o.max_matches = 2; |
| 282 | + let r = search_content(dir.path().to_str().unwrap(), "user", &o).unwrap(); |
| 283 | + assert_eq!(r.matches.len(), 2); |
| 284 | + assert!(r.truncated); |
| 285 | + } |
| 286 | + |
| 287 | + #[test] |
| 288 | + fn long_lines_are_windowed_around_the_match() { |
| 289 | + let dir = tempfile::tempdir().unwrap(); |
| 290 | + let line = format!("{}needle{}", "a".repeat(1000), "b".repeat(1000)); |
| 291 | + fs::write(dir.path().join("min.js"), &line).unwrap(); |
| 292 | + let r = search_content(dir.path().to_str().unwrap(), "needle", &opts()).unwrap(); |
| 293 | + let m = &r.matches[0]; |
| 294 | + assert!(m.text.starts_with('…') && m.text.ends_with('…')); |
| 295 | + let (s, e) = m.ranges[0]; |
| 296 | + let chars: Vec<char> = m.text.chars().collect(); |
| 297 | + assert_eq!(chars[s..e].iter().collect::<String>(), "needle"); |
| 298 | + assert_eq!(m.column, 1000); |
| 299 | + } |
| 300 | +} |
0 commit comments