use std::{env, fs};
use std::error::Error;
pub struct Config {
keyword: String,
file_path: String,
case_insensitive: bool,
}
impl Config {
pub fn new(mut args: env::Args) -> Result<Self, &'static str> {
args.next();
let keyword = match args.next() {
None => return Err("not find 'keyword' arguments"),
Some(keyword) => keyword
};
let file_path = match args.next() {
None => return Err("not find 'file_path' arguments"),
Some(file_path) => file_path
};
Ok(Config {
keyword,
file_path,
case_insensitive: env::var("CASE_INSENSITIVE").is_err(),
})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let content = fs::read_to_string(&config.file_path)?;
let result = if config.case_insensitive {
search_case_insensitive(&config.keyword, &content)
} else {
search(&config.keyword, &content)
};
for line in result {
println!("{}", line);
}
Ok(())
}
pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
content.lines()
.filter(|line| line.contains(query))
.collect()
}
pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
content.lines()
.filter(|line| line.to_lowercase().contains(&query.to_lowercase()))
.collect()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let content = "Rust\nsafe, fast, productive.\nPick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, content));
}
}