libgrep_rs/
searcher.rs

1//! Contains structs used for searching through text
2use crate::options::Options;
3use regex::Regex;
4use std::process::exit;
5///Searches through text for the given pattern
6#[derive(Clone)]
7pub struct Searcher {
8    pub pattern: String,
9    pub search_text: String,
10    pub options: Options,
11    pub deliminator: String
12}
13impl Searcher {
14    pub fn new(p: String, t: String, o: Options, d: Option<String>) -> Searcher {
15        let mut pattern = p.clone();
16        let mut search_text = t.clone();
17        let mut delim = String::from("\n");
18        if o.case_insensitive == true {
19            pattern = p.to_lowercase();
20            search_text = t.to_lowercase();
21        }
22        if d.is_some() {
23            delim = d.unwrap();
24        }
25        Searcher {
26            pattern,
27            search_text,
28            options: o,
29            deliminator: delim,
30        }
31    }
32    pub fn search(&self) -> String {
33        let mut found: bool = false;
34
35        let list: Vec<&str> = self.search_text.split(self.deliminator.as_str()).collect();
36        
37        let mut return_string = String::new();
38        let mut len = 0;
39        for i in list.clone() {
40            if self.options.regex == true {
41                
42                let regex = Regex::new(self.pattern.as_str());
43                if regex.is_err() {
44                    eprintln!("Invalid Regex");
45                    exit(1);
46                } else if regex.unwrap().is_match(i) {
47                    return_string.push_str(i);
48                    return_string.push_str("\n");
49                }
50            }
51            if i.contains(self.pattern.as_str()) {
52
53                if self.options.exclude == false {
54                    if self.options.show_line == true {
55                        return_string.push_str(format!("found at line: {}\n", len).as_str());
56
57                    }
58                    return_string.push_str(i);
59                    return_string.push_str("\n");
60                }
61                found = true;
62            } else if self.options.exclude == true {
63                    return_string.push_str(i);
64                    return_string.push_str("\n");
65                
66                
67            } else if self.options.include_before == true {
68                if found == false {
69                    return_string.push_str(i);
70                    return_string.push_str("\n");
71                }
72            } else if self.options.include_after == true {
73                if found == true {
74                    return_string.push_str(i);
75                    return_string.push_str("\n");
76                }
77            } else {
78                len += 1;
79            }
80        }
81 
82        return_string
83    }
84}