use std::env;
use std::error::Error;
use std::fs;
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_name)?;
let results = if config.case_sensitive {
search(&config.query, &contents)
} else {
search_case_insensitive(&config.query, &contents)
};
for line in results {
println!("{}", line);
}
Ok(())
}
pub struct Config {
pub query: String,
pub file_name: String,
pub case_sensitive: bool,
}
impl Config {
pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a query string")
};
let file_name = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a file name")
};
let case_sensitive = env::var("CASE_SENSITIVE")
.map(|x| {
return x == "true";
})
.unwrap_or(false);
Ok(Config {
query,
file_name,
case_sensitive,
})
}
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents.lines().filter(|line| line.contains(query)).collect()
}
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query.to_lowercase()) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "don't";
let contents = "\
I don't know how to make songs like that
I don't know what words to use
Let me know when it occurs to you
While I'm rippin' any one of these verses
";
assert_eq!(
vec![
"I don't know how to make songs like that",
"I don't know what words to use"
],
search(query, contents)
);
}
#[test]
fn case_insensitive() {
let query = "dOn";
let contents = "\
I don't know how to make songs like that
I doN't know what words to use
Let me know when it occurs to you
While I'm rippin' any one of these verses
";
assert_eq!(
vec![
"I don't know how to make songs like that",
"I doN't know what words to use"
],
search_case_insensitive(query, contents)
);
}
}