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
//! # My Crate
//!
//! `my_crate` is a collection of utilities to make performing certain
//! calculations more convenient.

use std::error::Error;
use std::fs;
use std::env;

pub struct Config{
    pub query: String,
    pub filename:String,
    pub case_sensitive: bool,
}
impl Config {
    pub fn new(mut args: impl Iterator<Item=String>) -> Result<Config,&'static str> {
        
        args.next(); // discard first arg

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Did not get a query string")
        };

        let filename = match args.next() {
            Some(arg) => arg,
            None => return Err("Did not get a filename")
        };

        let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
        println!("case_sensitive: {}", case_sensitive) ;
        
        Ok(Config{
            query, 
            filename,
            case_sensitive,
        })
    }
}


/// Run function
///
/// # Examples
///
/// ```
/// use minigrep_spc::Config;
/// use std::env;
/// use std::process;
///
/// 
/// let arguments: Vec<String> = vec![String::from("one"), String::from("one"), String::from("poem.txt") ];
/// let config = Config::new(arguments.into_iter()).unwrap_or_else( |err| {
///     eprintln!("Problem parsing arguments: {}", err);
///     process::exit(1);
/// });
/// if let Err(e) = minigrep_spc::run(config) {
///    eprintln!("Application error: {}", e);
///    process::exit(1);
/// };
///
/// ```
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.filename)?;   
    let results = if config.case_sensitive{
        search(&config.query, &contents)
    } else {
        search_insensitive(&config.query, &contents)
    };

    for line in results {
        println!("{}", line);
    }
    Ok(())
}

pub fn search<'a>(query:&str, contents:&'a str) 
        -> Vec<&'a str> {
    contents.lines()
    .filter(|line| line.contains(&query)).collect() 
}
pub fn search_insensitive<'a>(query:&str, contents:&'a str) 
        -> Vec<&'a str> {
    contents.lines()
    .filter(|line| line.to_lowercase().contains(&query.to_lowercase()))
    .collect() 
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_case_sensitive() {
        let query = "duct";
        let contents = "\"
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}

#[test]
fn test_case_insensitive() {
    let query = "ruST";
    let contents = "\"
Rust:
safe, fast, productive.
Pick three.
Trust me.";
    assert_eq!(vec!["Rust:", "Trust me."], search_insensitive(query, contents));
}

#[test]
    fn test_config_new_constructor() {
        let args : Vec<String> = vec!("executable".to_string(), "query".to_string(), "file".to_string());
        let config = Config::new(args.into_iter()).unwrap();
        assert_eq!(config.query, "query");      
        assert_eq!(config.filename, "file");      
    }

    #[test]
    #[should_panic(expected="Did not get a filename")]
    fn test_config_new_constructor_bad_args() {
        let args : Vec<String> = vec!("executable".to_string(), "query".to_string());
        let _config = Config::new(args.into_iter()).unwrap();
    }

    #[test]
    fn test_run_fails_if_file_not_exist() {
        //setup test
        let bad_filename="not_exist";
        let args : Vec<String> = vec!("executable".to_string(), 
            "query".to_string(), 
            bad_filename.to_string());
        let config = Config::new(args.into_iter()).unwrap();       
        let result = run(config);
        match result{
            Ok(()) => {
                println!("Result = Ok(())");
                panic!("Test should fail to open file 'not_exist'. Delete the file doesn't exist");
            },
            Err(error) => {
                println!("Result is an Error {:?}", error);
            }
        }
    }
    #[test]
    fn test_run_succeeds_if_file_exist() -> Result<(), Box<dyn Error> > {
        //setup test
        let filename="poem.txt";
        let args : Vec<String> = vec!("executable".to_string(), 
            "query".to_string(), 
            filename.to_string());
        let config = Config::new(args.into_iter()).unwrap();       
        run(config)
    }

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Picl three/";
         assert_eq!(vec!["safe, fast, productive."], search(query, contents));   
    }

}