cs/search/
text_search.rs

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/// Represents a single match from a text search
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct Match {
12    /// File path where the match was found
13    pub file: PathBuf,
14    /// Line number (1-indexed)
15    pub line: usize,
16    /// Content of the matching line
17    pub content: String,
18}
19
20/// Text searcher that uses ripgrep as a library for fast text searching
21pub struct TextSearcher {
22    /// Whether to respect .gitignore files
23    respect_gitignore: bool,
24    /// Whether search is case-sensitive
25    case_sensitive: bool,
26    /// The base directory to search in
27    base_dir: PathBuf,
28}
29
30impl TextSearcher {
31    /// Create a new TextSearcher with default settings
32    pub fn new(base_dir: PathBuf) -> Self {
33        Self {
34            respect_gitignore: true,
35            case_sensitive: false,
36            base_dir,
37        }
38    }
39
40    /// Set whether to respect .gitignore files (default: true)
41    pub fn respect_gitignore(mut self, value: bool) -> Self {
42        self.respect_gitignore = value;
43        self
44    }
45
46    /// Set whether search is case-sensitive (default: false)
47    pub fn case_sensitive(mut self, value: bool) -> Self {
48        self.case_sensitive = value;
49        self
50    }
51
52    /// Search for text and return all matches
53    ///
54    /// # Arguments
55    /// * `text` - The text to search for
56    ///
57    /// # Returns
58    /// A vector of Match structs containing file path, line number, and content
59    pub fn search(&self, text: &str) -> Result<Vec<Match>> {
60        // Build the regex matcher with fixed string (literal) matching
61        let matcher = RegexMatcherBuilder::new()
62            .case_insensitive(!self.case_sensitive)
63            .fixed_strings(true) // Literal string matching, not regex
64            .build(text)
65            .map_err(|e| SearchError::Generic(format!("Failed to build matcher: {}", e)))?;
66
67        // Build the file walker with .gitignore support
68        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) // Don't skip hidden files by default
73            .build();
74
75        // Shared vector to collect matches from all threads
76        let matches = Arc::new(Mutex::new(Vec::new()));
77
78        // Search each file
79        for entry in walker {
80            let entry = match entry {
81                Ok(e) => e,
82                Err(_) => continue, // Skip entries we can't read
83            };
84
85            // Skip directories
86            if entry.file_type().map_or(true, |ft| ft.is_dir()) {
87                continue;
88            }
89
90            let path = entry.path();
91
92            // Clone Arc for the closure
93            let matches_clone = Arc::clone(&matches);
94            let path_buf = path.to_path_buf();
95
96            // Build searcher
97            let mut searcher = SearcherBuilder::new()
98                .line_number(true)
99                .build();
100
101            // Search the file
102            let result = searcher.search_path(
103                &matcher,
104                path,
105                UTF8(|line_num, line_content| {
106                    // Collect the match
107                    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) // Continue searching
114                }),
115            );
116
117            // Ignore search errors for individual files
118            if let Err(_) = result {
119                continue;
120            }
121        }
122
123        // Extract matches from Arc<Mutex<Vec>>
124        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); // Should match all variations
169    }
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); // Should only match exact case
181        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        // Initialize git repository (required for .gitignore to work)
213        fs::create_dir(temp_dir.path().join(".git")).unwrap();
214
215        // Create .gitignore
216        fs::write(temp_dir.path().join(".gitignore"), "ignored.txt\n").unwrap();
217
218        // Create files
219        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        // Should only find in tracked.txt
227        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        // Initialize git repository
236        fs::create_dir(temp_dir.path().join(".git")).unwrap();
237
238        // Create .gitignore
239        fs::write(temp_dir.path().join(".gitignore"), "ignored.txt\n").unwrap();
240
241        // Create files
242        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        // Should find in both files
250        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        // Test with special regex characters (should be treated as literals)
279        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}