use std::{env, process};
pub struct Config {
query: String,
file_paths: Vec<String>,
case_sensitive: bool,
show_file: bool,
}
impl Config {
pub fn parse(args: &[String]) -> Result<Self,&'static str> {
if args.len() < 1 {
return Err("Not enough arguments");
}
let query = String::new();
let file_paths = vec![];
let case_sensitive = env::var("IGNORE_CASE").is_err();
let mut conf = Self {
query,
file_paths,
case_sensitive,
show_file:false,
};
let mut show_file = None;
for arg in &args[1..] {
match arg.as_str() {
"-i" => conf.case_sensitive = false,
"-v" => show_file = Some(true),
"-q" => show_file = Some(false),
"-h" => help(),
_ => {
if conf.query.is_empty() {
conf.query = arg.clone();
} else {
conf.file_paths.push(arg.clone());
}
} ,
}
}
if conf.query.is_empty() {
return Err("Empty query");
}
conf.show_file = show_file.unwrap_or(conf.file_paths.len() > 1);
Ok(conf)
}
pub fn query(&self) -> &str { &self.query }
pub fn file_paths(&self) -> &[String] { &self.file_paths }
pub fn case_sensitive(&self) -> bool { self.case_sensitive }
pub fn show_file(&self) -> bool { self.show_file }
}
fn help() {
println!("\
Usage: minigrep <pattern> <file1>..<fileN> [-qvi]
Options:
-i : Match pattern case-insensitive
-v : Show file that matched (by default when multiple files)
-q : Never show the files that matched");
process::exit(0);
}