1use crate::error::{Result, SearchError};
2use grep_regex::RegexMatcherBuilder;
3use grep_searcher::sinks::UTF8;
4use grep_searcher::SearcherBuilder;
5use ignore::WalkBuilder;
6use std::path::PathBuf;
7use std::sync::{Arc, Mutex};
8
9#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct Match {
12 pub file: PathBuf,
14 pub line: usize,
16 pub content: String,
18}
19
20pub struct TextSearcher {
22 respect_gitignore: bool,
24 case_sensitive: bool,
26 base_dir: PathBuf,
28}
29
30impl TextSearcher {
31 pub fn new(base_dir: PathBuf) -> Self {
33 Self {
34 respect_gitignore: true,
35 case_sensitive: false,
36 base_dir,
37 }
38 }
39
40 pub fn respect_gitignore(mut self, value: bool) -> Self {
42 self.respect_gitignore = value;
43 self
44 }
45
46 pub fn case_sensitive(mut self, value: bool) -> Self {
48 self.case_sensitive = value;
49 self
50 }
51
52 pub fn search(&self, text: &str) -> Result<Vec<Match>> {
60 let matcher = RegexMatcherBuilder::new()
62 .case_insensitive(!self.case_sensitive)
63 .fixed_strings(true) .build(text)
65 .map_err(|e| SearchError::Generic(format!("Failed to build matcher: {}", e)))?;
66
67 let walker = WalkBuilder::new(&self.base_dir)
69 .git_ignore(self.respect_gitignore)
70 .git_global(self.respect_gitignore)
71 .git_exclude(self.respect_gitignore)
72 .hidden(false) .build();
74
75 let matches = Arc::new(Mutex::new(Vec::new()));
77
78 for entry in walker {
80 let entry = match entry {
81 Ok(e) => e,
82 Err(_) => continue, };
84
85 if entry.file_type().map_or(true, |ft| ft.is_dir()) {
87 continue;
88 }
89
90 let path = entry.path();
91
92 let matches_clone = Arc::clone(&matches);
94 let path_buf = path.to_path_buf();
95
96 let mut searcher = SearcherBuilder::new()
98 .line_number(true)
99 .build();
100
101 let result = searcher.search_path(
103 &matcher,
104 path,
105 UTF8(|line_num, line_content| {
106 let mut matches = matches_clone.lock().unwrap();
108 matches.push(Match {
109 file: path_buf.clone(),
110 line: line_num as usize,
111 content: line_content.trim_end().to_string(),
112 });
113 Ok(true) }),
115 );
116
117 if let Err(_) = result {
119 continue;
120 }
121 }
122
123 let matches = match Arc::try_unwrap(matches) {
125 Ok(mutex) => mutex.into_inner().unwrap(),
126 Err(arc) => arc.lock().unwrap().clone(),
127 };
128
129 Ok(matches)
130 }
131}
132
133impl Default for TextSearcher {
134 fn default() -> Self {
135 Self::new(std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142 use std::fs;
143 use tempfile::TempDir;
144
145 #[test]
146 fn test_basic_search() {
147 let temp_dir = TempDir::new().unwrap();
148 fs::write(temp_dir.path().join("test.txt"), "hello world\nfoo bar\nhello again").unwrap();
149
150 let searcher = TextSearcher::new(temp_dir.path().to_path_buf());
151 let matches = searcher.search("hello").unwrap();
152
153 assert_eq!(matches.len(), 2);
154 assert_eq!(matches[0].line, 1);
155 assert_eq!(matches[0].content, "hello world");
156 assert_eq!(matches[1].line, 3);
157 assert_eq!(matches[1].content, "hello again");
158 }
159
160 #[test]
161 fn test_case_insensitive_default() {
162 let temp_dir = TempDir::new().unwrap();
163 fs::write(temp_dir.path().join("test.txt"), "Hello World\nHELLO\nhello").unwrap();
164
165 let searcher = TextSearcher::new(temp_dir.path().to_path_buf());
166 let matches = searcher.search("hello").unwrap();
167
168 assert_eq!(matches.len(), 3); }
170
171 #[test]
172 fn test_case_sensitive() {
173 let temp_dir = TempDir::new().unwrap();
174 fs::write(temp_dir.path().join("test.txt"), "Hello World\nHELLO\nhello").unwrap();
175
176 let searcher = TextSearcher::new(temp_dir.path().to_path_buf())
177 .case_sensitive(true);
178 let matches = searcher.search("hello").unwrap();
179
180 assert_eq!(matches.len(), 1); assert_eq!(matches[0].content, "hello");
182 }
183
184 #[test]
185 fn test_no_matches() {
186 let temp_dir = TempDir::new().unwrap();
187 fs::write(temp_dir.path().join("test.txt"), "foo bar baz").unwrap();
188
189 let searcher = TextSearcher::new(temp_dir.path().to_path_buf());
190 let matches = searcher.search("notfound").unwrap();
191
192 assert_eq!(matches.len(), 0);
193 }
194
195 #[test]
196 fn test_multiple_files() {
197 let temp_dir = TempDir::new().unwrap();
198 fs::write(temp_dir.path().join("file1.txt"), "target line 1").unwrap();
199 fs::write(temp_dir.path().join("file2.txt"), "target line 2").unwrap();
200 fs::write(temp_dir.path().join("file3.txt"), "other content").unwrap();
201
202 let searcher = TextSearcher::new(temp_dir.path().to_path_buf());
203 let matches = searcher.search("target").unwrap();
204
205 assert_eq!(matches.len(), 2);
206 }
207
208 #[test]
209 fn test_gitignore_respected() {
210 let temp_dir = TempDir::new().unwrap();
211
212 fs::create_dir(temp_dir.path().join(".git")).unwrap();
214
215 fs::write(temp_dir.path().join(".gitignore"), "ignored.txt\n").unwrap();
217
218 fs::write(temp_dir.path().join("ignored.txt"), "target content").unwrap();
220 fs::write(temp_dir.path().join("tracked.txt"), "target content").unwrap();
221
222 let searcher = TextSearcher::new(temp_dir.path().to_path_buf())
223 .respect_gitignore(true);
224 let matches = searcher.search("target").unwrap();
225
226 assert_eq!(matches.len(), 1);
228 assert!(matches[0].file.ends_with("tracked.txt"));
229 }
230
231 #[test]
232 fn test_gitignore_disabled() {
233 let temp_dir = TempDir::new().unwrap();
234
235 fs::create_dir(temp_dir.path().join(".git")).unwrap();
237
238 fs::write(temp_dir.path().join(".gitignore"), "ignored.txt\n").unwrap();
240
241 fs::write(temp_dir.path().join("ignored.txt"), "target content").unwrap();
243 fs::write(temp_dir.path().join("tracked.txt"), "target content").unwrap();
244
245 let searcher = TextSearcher::new(temp_dir.path().to_path_buf())
246 .respect_gitignore(false);
247 let matches = searcher.search("target").unwrap();
248
249 assert_eq!(matches.len(), 2);
251 }
252
253 #[test]
254 fn test_builder_pattern() {
255 let searcher = TextSearcher::new(std::env::current_dir().unwrap())
256 .case_sensitive(true)
257 .respect_gitignore(false);
258
259 assert_eq!(searcher.case_sensitive, true);
260 assert_eq!(searcher.respect_gitignore, false);
261 }
262
263 #[test]
264 fn test_default() {
265 let searcher = TextSearcher::default();
266
267 assert_eq!(searcher.case_sensitive, false);
268 assert_eq!(searcher.respect_gitignore, true);
269 }
270
271 #[test]
272 fn test_special_characters() {
273 let temp_dir = TempDir::new().unwrap();
274 fs::write(temp_dir.path().join("test.txt"), "price: $19.99\nurl: http://example.com").unwrap();
275
276 let searcher = TextSearcher::new(temp_dir.path().to_path_buf());
277
278 let matches = searcher.search("$19.99").unwrap();
280 assert_eq!(matches.len(), 1);
281
282 let matches = searcher.search("http://").unwrap();
283 assert_eq!(matches.len(), 1);
284 }
285
286 #[test]
287 fn test_line_numbers_accurate() {
288 let temp_dir = TempDir::new().unwrap();
289 let content = "line 1\nline 2\ntarget line 3\nline 4\ntarget line 5\nline 6";
290 fs::write(temp_dir.path().join("test.txt"), content).unwrap();
291
292 let searcher = TextSearcher::new(temp_dir.path().to_path_buf());
293 let matches = searcher.search("target").unwrap();
294
295 assert_eq!(matches.len(), 2);
296 assert_eq!(matches[0].line, 3);
297 assert_eq!(matches[1].line, 5);
298 }
299}