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
/* Created By Angel Uniminin <uniminin@zoho.com> under the terms of MIT */

extern crate colored;
use colored::Colorize;

use std::{env,
          fs::{File},
          io::{Read},
          error::{Error}};

pub struct Config {
    pub pattern: String,
    pub file: String,
}

impl Config {
    pub fn new(mut args: env::Args) -> Result<Config, &'static str> {

        /* Discard the first argument (args[0]), which is the filename along with path. */
        args.next();

        let (file, pattern): (String, String) = (match args.next() {
            Some(arg) => arg,
            None => return Err("Fatal: No file provided!"),
        }, match args.next() {
            Some(arg) => arg.to_lowercase(),
            None => return Err("Fatal: No string pattern provided!"),
        });

        /* var names are same as in the struct, so e dont need explicit key:val initialization style. */
        Ok(Config { file, pattern })
    }

}

/* The lifetime parameters says that: the search results will be valid as long as the contents are valid.
 * Can last even after pattern goes out of scope. */
fn search<'a>(pattern: &str, contents: &'a str) -> Vec<&'a str> {
    let pattern: String = pattern.to_lowercase();

    contents.lines()
        .filter(|line| line.to_lowercase().contains(&pattern))
        .collect()
}

fn summarize(occurrence: usize, line_count: u64) -> String {
    let summary: String;

    if occurrence == 0 {
        summary = format!("{:1} {:1} {:1}", "Found".red(), occurrence.to_string().red(), "occurrence!".red())
    } else {
        let (mut occurrence_word, mut line_word): (String, String) = ("occurrence".parse().unwrap(), "line".parse().unwrap());

        match (occurrence, line_count) {
            (0, _) | (1, _) => {
                line_word.push("s".parse().unwrap());
            }
            (_, 0) | (_, 1) => {
                occurrence_word.push("s".parse().unwrap());
            }
            _ => {
                line_word.push("s".parse().unwrap());
                occurrence_word.push("s".parse().unwrap());
            }
        }

        summary = format!("{:1}\n\
						  {:1} {:1} {:1} {:1} {:1} {:1} {:1}{:1}",
                          "--Summary--".yellow(),"*".green().bold(),
                          "Found".green(), occurrence.to_string().trim().blue().bold(),
                          occurrence_word.green(), "in".green(),
                          line_count.to_string().blue().bold(),
                          line_word.green(), "!".green());
    }
    summary
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {

    println!("\n{:1} {:1} {:1} {:1} {:1} {:1}\n", "->".bright_blue(),
             "Searching for".green(), &config.pattern.bright_cyan().bold(),
             "in".green(), &config.file.bright_cyan().bold(), "<-".bright_blue());

    /* `?` will return the error(ending fn execution)
     * if it encounters an `Err` in the `Result` it follows. */
    let mut file = File::open(config.file)?;

    let mut contents: String = String::new();
    file.read_to_string(&mut contents)?;

    let results: Vec<&str> = search(&config.pattern, &contents);

    let (mut line_count, mut total_occurrence) = (0u64, 0usize);

    for line in results {
        let occurrences: String = format!("{:1}", line.to_lowercase()
            .matches(&config.pattern).count().to_string().yellow().bold());
        line_count += 1;
        total_occurrence += line.to_lowercase().matches(&config.pattern).count();
        println!("{:1}  [ {:1} ]", line.to_string().magenta(), occurrences);
    } println!();

    println!("{}", summarize(total_occurrence, line_count));

    /* `()` is a unit type. It means that we mostly do not care about return type if it goes well.
     * We do, however, care about the errors that might occur, and that's why the result type
     * exists with a dynamic error return type. */
    Ok(())
}

#[cfg(test)]
mod test {
    /* use every fn from above */
    use super::*;

    #[test]
    fn case_sensitive() {
        let pattern: &str = "is";
        let contents: &str = "\
Hello There!
This is just a random text.
There is no errors.";

        assert_eq!(
            vec!["This is just a random text.",
                 "There is no errors."],
            search(pattern, contents)
        );
    }

    #[test]
    fn case_insensitive() {
        let pattern: &str = "tH";
        let contents: &str = "\
Hello There!
This is another random text.
There should be no errors as well.";

        assert_eq!(
            vec!["Hello There!",
                 "This is another random text.",
                 "There should be no errors as well."],
            search(pattern, contents)
        );
    }

    #[test]
    fn summary_characters_one_occurrence() {
        let data: &str = "\u{1b}[33m--Summary--\u{1b}[0m\n\u{1b}[1;32m*\u{1b}[0m \
		\u{1b}[32mFound\u{1b}[0m \u{1b}[1;34m2\u{1b}[0m \u{1b}[32moccurrences\
		\u{1b}[0m \u{1b}[32min\u{1b}[0m \u{1b}[1;34m1\u{1b}[0m \u{1b}[32mline\
		\u{1b}[0m\u{1b}[32m!\u{1b}[0m";
        assert_eq!(
            data,
            summarize(2, 1)
        );
    }

    #[test]
    fn summary_characters_two_occurrence() {
        let data: &str = "\u{1b}[33m--Summary--\u{1b}[0m\n\u{1b}[1;32m*\u{1b}[0m \
		\u{1b}[32mFound\u{1b}[0m \u{1b}[1;34m9\u{1b}[0m \u{1b}[32moccurrences\
		\u{1b}[0m \u{1b}[32min\u{1b}[0m \u{1b}[1;34m11\u{1b}[0m \u{1b}[32mlines\
		\u{1b}[0m\u{1b}[32m!\u{1b}[0m";
        assert_eq!(
            data,
            summarize(9, 11)
        );
    }
}