use std::{env, path::PathBuf};
pub struct Config {
pub query: String,
pub targets: Vec<PathBuf>,
pub ignore_case: bool,
pub output_file: Option<String>,
}
impl Config {
pub fn build(args: &[String]) -> Result<Self, String> {
let mut current_index: usize = 1; if args.len() < current_index + 2 {
return Err("not enough arguments".to_string());
}
let mut ignore_case: bool = match env::var("IGNORE_CASE") {
Ok(val) => val.parse().unwrap_or(false),
Err(_) => false,
}; let mut output_file: Option<String> = None;
while args[current_index].starts_with('-') {
let flag = args[current_index].clone();
if flag.eq("-i") || flag.eq("--ignore-case") {
ignore_case = true;
} else if flag.eq("-o") || flag.eq("--output-file") {
current_index += 1; output_file = Some(args[current_index].clone());
} else if flag.eq("-h") || flag.eq("--help") {
return Err(format!("the {flag} can only be used by itself."));
} else {
return Err(
"unrecogonised flag passed\nRun `grepme --help` to see available flags."
.to_string(),
);
}
current_index += 1;
}
if args.len() < current_index + 2 {
return Err(
"query and file path are required arguments".to_string()
);
}
let query: String = args[current_index].clone();
current_index += 1;
let targets: Vec<PathBuf> =
args[current_index..].iter().map(PathBuf::from).collect();
Ok(Self {
query,
targets,
ignore_case,
output_file,
})
}
}
pub const HELPTEXT: &str = "\
Usage: grepme [arguments] query [paths/glob]
Query can be any plain unquoted string or a quoted regex pattern.
Arguments:
--help / -h\tShows this help text
--ignore-case / -i\tPerforms case-insensitive search
--output-file / -o <filepath>\tWrites stdout to file";