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("-v") || flag.eq("--version") {
return Err(format!(
"the {flag} flag can only be called by itself."
));
} else if flag.eq("-h") || flag.eq("--help") {
return Err(format!(
"the {flag} flag can only be called 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,
})
}
}
#[cfg(unix)]
pub const HELPTEXT: &str = concat!(
"\n",
env!("CARGO_PKG_NAME"),
" v",
env!("CARGO_PKG_VERSION"),
" by ",
env!("CARGO_PKG_AUTHORS"),
" - ",
env!("CARGO_PKG_LICENSE"),
"\n\n",
env!("CARGO_PKG_DESCRIPTION"),
"\n\n",
"Usage:\n grepme [arguments] query [paths/glob]\n\n",
"Arguments:\n",
" --ignore-case | -i Performs case-insensitive search\n",
" --output-file | -o <file> Writes stdout to file\n",
" --version | -v Shows the version number\n",
" --help | -h Shows this help text\n\n",
"Query:\n can be any plain unquoted string or a quoted regex pattern.\n\n",
"Paths:\n space separated list of files, directories, and/or glob patters.\n",
);
#[cfg(not(unix))]
pub const HELPTEXT: &str = concat!(
"\n",
env!("CARGO_PKG_NAME"),
" v",
env!("CARGO_PKG_VERSION"),
" by ",
env!("CARGO_PKG_AUTHORS"),
" - ",
env!("CARGO_PKG_LICENSE"),
"\n\n",
env!("CARGO_PKG_DESCRIPTION"),
"\n\n",
"Usage:\n grepme [arguments] query [paths]\n\n",
"Arguments:\n",
" --ignore-case | -i Performs case-insensitive search\n",
" --output-file | -o <file> Writes stdout to file\n",
" --version | -v Shows the version number\n",
" --help | -h Shows this help text\n\n",
"Query:\n can be any plain unquoted string or a quoted regex pattern.\n\n",
"Paths:\n space separated list of files and directories.\n",
);