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
/*
MIT License

Copyright (c) 2020-2021 Uniminin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#![deny(missing_docs)]

//! Custom simplified implementation of minigrep with additional features.

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

const ARGS_LIMIT: usize = 4;

/// The necessary configurations for initializing nanogrep.
///
pub struct Config {
    /// The file along with the path in which the pattern search will be conducted.
    pub file: String,
    /// The pattern to search for in the contents of the file.
    pub pattern: String,
}

impl Config {
    /// Initializes a new Config.
    ///
    /// Returns error if incorrect option is passed.
    pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
        if args.len() >= ARGS_LIMIT {
            return Err("Expected 2 arguments but more than 2 arguments were provided!");
        }

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

        /* arg0[1] & arg0[2] are file & pattern respectively */
        let (file, pattern): (String, String) = (
            match args.next() {
                Some(arg) => arg,
                None => return Err("No file provided!"),
            },
            match args.next() {
                Some(arg) => arg.to_lowercase(),
                None => return Err("No 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. */
/// Returns the line(s) where the pattern is matched in the contents of the file.
pub fn search<'a>(pattern: &str, content: &'a str) -> Vec<&'a str> {
    content
        .lines()
        .filter(|line: &&str| line.to_lowercase().contains(&pattern.to_ascii_lowercase()))
        .collect()
}

/// Returns summary which includes total matched occurence(s) of the pattern & line respectively.
pub fn summarize(occurrence: usize, line_count: usize) -> String {
    let result_summary: String;

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

        if occurrence > 1 {
            occurrence_word.push('s');
        }

        if line_count > 1 {
            line_word.push('s');
        }

        result_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()
        );
    }

    result_summary
}

/// Runs the library logic.
/// Expects a reference to [`Config`](struct@Config).
///
/// # Errors
///
/// Returns error on the following situations:
///
/// - `file` doesn't exist.
/// - `file` could not be read (unauthorized read permission).
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    /* `?` will return the error(ending fn execution)
     * if it encounters an `Err` in the `Result` it follows. */
    let (mut file, mut data): (File, String) = (File::open(&config.file)?, String::new());

    file.read_to_string(&mut data)?;

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

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

    let mut output: String = String::new();

    for line in result {
        let occurrence: usize = line.to_ascii_lowercase().matches(&config.pattern).count();
        total_occurrence += occurrence;

        let formatted_output: String = format!(
            "{:1}  | {:1} |\n",
            line.magenta(),
            occurrence.to_string().yellow().bold()
        );

        output.push_str(&*formatted_output);
        line_count += 1;
    }

    let input_summary: String = format!(
        "{:1} {:1} {:1} {:1}\n",
        "Search result for".green(),
        &config.pattern.bright_cyan().bold(),
        "in".green(),
        &config.file.bright_cyan().bold(),
    );

    println!(
        "\n{:1}\n{:1}\n{:1}",
        input_summary,
        output,
        summarize(total_occurrence, line_count)
    );

    /* `()` is a unit type.
     * 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 data: &str = "Hello There!\nThis is just a random text.\nThere is no errors.\n";

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

    #[test]
    fn case_insensitive() {
        let pattern: &str = "tH";
        let data: &str =
            "Hello There!\nThis is another random text.\nThere 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, data)
        );
    }
}