grox 0.10.0

Command-line tool that searches for regex matches in a file tree.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use std::collections::HashSet;
use std::env;
use std::ffi::OsStr;
use std::fs::{read_dir, File, ReadDir};
use std::io::{self, BufRead, BufReader, Lines};
use std::iter::Enumerate;
use std::path::{Path, PathBuf};
use std::slice::Iter;

use colored::Colorize;
use regex::Regex;
use tiny_bail::or_return_quiet;

pub mod history;
pub mod open;

/// Flag specifying that matches should be displayed in color.
pub const USE_COLOR: u32 = 1;
/// Flag specifying that hidden files/directories should be searched.
pub const SEARCH_HIDDEN: u32 = 2;
/// Flag specifying to only retrieve the first match per file.
pub const SINGLE_MATCH: u32 = 4;

const DEFAULT_MATCH_PADDING: usize = 15;

/// The location of a regex match.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Location {
    /// Path to the file.
    pub file: PathBuf,
    /// Line number (1-up) of the match.
    pub line: usize,
    /// Matching text with some surrounding characters (and possibly ellipses).
    pub text: String,
}

/// Builds a [`Searcher`].
///
/// # Examples
///
/// ```
/// let pattern = regex::Regex::new("foo").unwrap();
/// let directory = std::path::PathBuf::from("/not/a/real/directory");
/// let searcher = grox::Builder::new(&pattern, &directory).build();
/// assert!(!searcher.is_ok());
/// ```
///
/// ```
/// let pattern = regex::Regex::new("foo").unwrap();
/// let directory = std::path::PathBuf::from(".");
/// let mut builder = grox::Builder::new(&pattern, &directory);
/// builder.set_depth(0);
/// let searcher = builder.build();
/// assert!(searcher.is_ok());
/// ```
///
/// ```
/// let pattern = regex::Regex::new("foo").unwrap();
/// let directory = std::path::PathBuf::from(".");
/// let mut builder = grox::Builder::new(&pattern, &directory);
/// let file_pattern = regex::Regex::new(r"\.rs$").unwrap();
/// builder.set_file_pattern(&file_pattern);
/// let searcher = builder.build();
/// assert!(searcher.is_ok());
/// ```
pub struct Builder<'a> {
    pattern: &'a Regex,
    directory: &'a Path,
    file_pattern: Option<&'a Regex>,
    excluded_dirs: Vec<String>,
    max_depth: Option<usize>,
    flags: u32,
}

impl<'a> Builder<'a> {
    /// Constructor.
    ///
    /// # Arguments
    ///
    /// * `pattern` - Search pattern.
    /// * `directory` - Starting directory.
    ///
    /// # Returns
    ///
    /// Builder
    pub fn new(pattern: &'a Regex, directory: &'a Path) -> Self {
        Self {
            pattern,
            directory,
            file_pattern: None,
            excluded_dirs: vec![],
            max_depth: None,
            flags: 0,
        }
    }

    /// Sets the file pattern.
    ///
    /// # Arguments
    ///
    /// * `pattern` - Only files whose names match this pattern will be scanned.
    pub fn set_file_pattern(&mut self, pattern: &'a Regex) {
        self.file_pattern = Some(pattern);
    }

    /// Exclude a directory from the search.
    ///
    /// # Arguments
    ///
    /// * `dir` - Directory.  If not absolute, then will be treated as relative to the starting directory.
    pub fn exclude_dir(&mut self, dir: &str) {
        self.excluded_dirs.push(dir.trim_end_matches("/").to_string());
    }

    /// Sets the maximum search depth.
    ///
    /// # Arguments
    ///
    /// * `depth` - Maximum search depth.  A depth of 0, for example, searches only the starting directory.
    pub fn set_depth(&mut self, depth: usize) {
        self.max_depth = Some(depth);
    }

    /// Sets flags.
    ///
    /// # Arguments
    ///
    /// * `flags` - Flags to be added.  Accepted values are [`USE_COLOR`], [`SEARCH_HIDDEN`], and [`SINGLE_MATCH`].
    pub fn set_flags(&mut self, flags: u32) {
        self.flags |= flags;
    }

    /// Attempts to build the searcher.
    ///
    /// # Returns
    ///
    /// Searcher if successful and an error if the starting directory couldn't be accessed.
    pub fn build(self) -> io::Result<Searcher<'a>> {
        Searcher::build(
            self.pattern,
            self.directory,
            self.file_pattern,
            self.excluded_dirs,
            self.max_depth,
            self.flags,
        )
    }
}

/// Iterator (yielding [`Location`] objects) that searches for regex matches within a file tree.
pub struct Searcher<'a> {
    pattern: &'a Regex,
    file_pattern: Option<&'a Regex>,
    excluded_dirs: HashSet<PathBuf>,
    max_depth: Option<usize>,
    flags: u32,
    match_padding: usize,
    readers: Vec<ReadDir>,
    current_scanner: Option<FileScanner<'a>>,
}

impl<'a> Searcher<'a> {
    fn build(
        pattern: &'a Regex,
        directory: &'a Path,
        file_pattern: Option<&'a Regex>,
        excluded_dirs: Vec<String>,
        max_depth: Option<usize>,
        flags: u32,
    ) -> io::Result<Self> {
        let reader = read_dir(directory)?;

        let excluded_dirs = Rebaser::new(directory, &excluded_dirs)
            .filter(|p| match p.as_ref() {
                Ok(_) => true,
                Err(e) => e.kind() != io::ErrorKind::NotFound,
            })
            .collect::<io::Result<HashSet<PathBuf>>>()?;

        Ok(Self {
            pattern,
            file_pattern,
            excluded_dirs,
            max_depth: max_depth.map(|x| x + 1),
            flags,
            match_padding: determine_match_padding().unwrap_or(DEFAULT_MATCH_PADDING),
            readers: vec![reader],
            current_scanner: None,
        })
    }

    fn push_directory(&mut self, directory: PathBuf) {
        if let Some(depth) = self.max_depth {
            if self.readers.len() == depth {
                return;
            }
        }

        let resolved_directory = or_return_quiet!(directory.canonicalize());
        if self.excluded_dirs.contains(&resolved_directory) {
            return;
        }

        if let Ok(reader) = read_dir(directory) {
            self.readers.push(reader);
        }
    }

    fn next_match_from_file(&mut self) -> Option<Location> {
        let location = self.current_scanner.as_mut()?.next();
        if location.is_none() {
            self.current_scanner = None;
        }
        location
    }
}

impl Iterator for Searcher<'_> {
    type Item = Location;

    fn next(&mut self) -> Option<Location> {
        if let Some(location) = self.next_match_from_file() {
            return Some(location);
        }

        while let Some(current_reader) = self.readers.last_mut() {
            let path = match current_reader.next() {
                Some(Ok(ent)) => ent.path(),
                _ => {
                    self.readers.pop();
                    continue;
                }
            };
            if let Some(first_char) = path
                .file_name()
                .and_then(OsStr::to_str)
                .and_then(|name| name.chars().next())
            {
                if first_char == '.' && self.flags & SEARCH_HIDDEN == 0 {
                    continue;
                }
            }

            if path.is_dir() {
                self.push_directory(path);
                continue;
            }

            if let Some(file_pattern) = self.file_pattern {
                if file_pattern
                    .find(path.file_name().unwrap().to_string_lossy().as_ref())
                    .is_none()
                {
                    continue;
                }
            }

            self.current_scanner = FileScanner::build(path, self.pattern, self.flags, self.match_padding);
            if let Some(location) = self.next_match_from_file() {
                return Some(location);
            }
        }

        None
    }
}

struct FileScanner<'a> {
    path: PathBuf,
    pattern: &'a Regex,
    flags: u32,
    match_padding: usize,
    lines: Enumerate<Lines<BufReader<File>>>,
    current_search: Option<LineSearch>,
    found_match: bool,
}

impl<'a> FileScanner<'a> {
    fn build(path: PathBuf, pattern: &'a Regex, flags: u32, match_padding: usize) -> Option<Self> {
        let handle = File::open(&path).ok()?;
        let reader = BufReader::new(handle);
        Some(Self {
            path,
            pattern,
            flags,
            match_padding,
            lines: reader.lines().enumerate(),
            current_search: None,
            found_match: false,
        })
    }

    fn match_from_current_line(&mut self) -> Option<Location> {
        let current_search = self.current_search.as_mut()?;
        let rest_of_line = &current_search.line[current_search.position..];
        let pattern_match = match self.pattern.find(rest_of_line) {
            Some(m) => m,
            None => {
                self.current_search = None;
                return None;
            }
        };

        let start = pattern_match.start();
        let end = pattern_match.end();
        let mut text = rest_of_line[start..end].to_string();
        if self.flags & USE_COLOR != 0 {
            text = text.bright_red().to_string();
        }

        let start_char = get_char_index(rest_of_line, start) + current_search.char_position;
        let end_char = get_char_index(rest_of_line, end) + current_search.char_position;

        let chars: Vec<char> = current_search.line.chars().collect();
        let snippet = LineSnippet::from_match(&chars, start_char, end_char, self.match_padding);

        if snippet.left < start_char {
            let prev_text: String = chars[snippet.left..start_char].iter().collect();
            text = format!("{prev_text}{text}");
            if snippet.more_on_left {
                text = format!("... {text}");
            }
        }
        if snippet.right > end_char {
            let next_text: String = chars[end_char..snippet.right].iter().collect();
            text = format!("{text}{next_text}");
            if snippet.more_on_right {
                text = format!("{text} ...");
            }
        }

        current_search.position += end;
        current_search.char_position = end_char;
        self.found_match = true;

        Some(Location {
            file: self.path.clone(),
            line: current_search.line_no,
            text: text.trim().to_string(),
        })
    }
}

impl Iterator for FileScanner<'_> {
    type Item = Location;

    fn next(&mut self) -> Option<Location> {
        if self.flags & SINGLE_MATCH != 0 && self.found_match {
            return None;
        }

        if let Some(location) = self.match_from_current_line() {
            return Some(location);
        }

        loop {
            let (line_no, line) = match self.lines.next() {
                Some((i, Ok(l))) => (i + 1, l),
                _ => return None,
            };
            self.current_search = Some(LineSearch {
                line_no,
                line,
                position: 0,
                char_position: 0,
            });
            if let Some(location) = self.match_from_current_line() {
                return Some(location);
            }
        }
    }
}

struct LineSearch {
    line_no: usize,
    line: String,
    position: usize,
    char_position: usize,
}

struct LineSnippet {
    left: usize,
    right: usize,
    more_on_left: bool,
    more_on_right: bool,
}

impl LineSnippet {
    fn from_match(chars: &[char], start: usize, end: usize, padding: usize) -> Self {
        let mut left = start;
        let mut right = end;
        let mut more_on_left = false;
        let mut more_on_right = false;

        if start > 0 {
            let mut counter: usize = 0;
            left -= 1;
            while left > 0 {
                if !chars[left].is_whitespace() {
                    counter += 1;
                    if counter == padding {
                        break;
                    }
                }
                left -= 1;
            }

            more_on_left = counter == padding && left > 0;
        }

        if right < chars.len() - 1 {
            let mut counter: usize = 0;
            right += 1;
            while right < chars.len() {
                if !chars[right].is_whitespace() {
                    counter += 1;
                    if counter == padding {
                        break;
                    }
                }
                right += 1;
            }

            more_on_right = counter == padding && right < chars.len();
        }

        Self {
            left,
            right,
            more_on_left,
            more_on_right,
        }
    }
}

/// Rebases and canonicalizes strings on top of a base path.
pub struct Rebaser<'a> {
    base: &'a Path,
    directories: Iter<'a, String>,
}

impl<'a> Rebaser<'a> {
    /// Constructor.
    ///
    /// # Arguments
    ///
    /// * `base` - Base directories.
    /// * `directories` - Directories to rebase.
    ///
    /// # Returns
    ///
    /// Rebaser
    pub fn new(base: &'a Path, directories: &'a [String]) -> Self {
        Self {
            base,
            directories: directories.iter(),
        }
    }
}

impl Iterator for Rebaser<'_> {
    type Item = io::Result<PathBuf>;

    fn next(&mut self) -> Option<io::Result<PathBuf>> {
        let directory = self.directories.next()?;
        let rebased = if directory.starts_with("/") {
            PathBuf::from(directory)
        } else {
            self.base.join(directory)
        };
        Some(rebased.canonicalize())
    }
}

fn determine_match_padding() -> Option<usize> {
    let padding = env::var("GROX_PADDING").ok()?;
    padding.parse::<usize>().ok()
}

fn get_char_index(text: &str, idx: usize) -> usize {
    text[..idx].chars().count()
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use super::*;

    #[test]
    fn find_matches_in_file() {
        let mut file = tempfile::NamedTempFile::new().unwrap();
        write!(file, "Hello world\nI am not a fool\nI'm going to fold my clothes").unwrap();
        file.flush().unwrap();

        let path = file.path().to_path_buf();
        let pattern = Regex::new("fo.").unwrap();
        let scanner = FileScanner::build(path.clone(), &pattern, 0, DEFAULT_MATCH_PADDING);
        assert!(scanner.is_some());

        let locations: Vec<Location> = scanner.unwrap().collect();
        assert_eq!(locations.len(), 2);

        assert_eq!(locations[0].file, path);
        assert_eq!(locations[0].line, 2);
        println!("Match 1: {}", locations[0].text);

        assert_eq!(locations[1].file, path);
        assert_eq!(locations[1].line, 3);
        println!("Match 2: {}", locations[1].text);
        assert!(locations[1].text.contains("fold"));
    }

    #[test]
    fn form_snippet() {
        let chars: Vec<char> = "This is some very long text that says nothing".chars().collect();
        let snippet = LineSnippet::from_match(&chars, 33, 36, DEFAULT_MATCH_PADDING);
        assert_eq!(snippet.left, 14);
        assert_eq!(snippet.right, chars.len());
        assert!(snippet.more_on_left);
        assert!(!snippet.more_on_right);
    }
}