use std::{fs::File, io::Read};
use crate::{cli_pretty_printing::panic_failure_both_input_and_fail_provided, config::Config};
use clap::Parser;
use lemmeknow::Identifier;
use log::trace;
#[derive(Parser)]
#[command(author = "Bee <bee@skerritt.blog>", about, long_about = None)]
pub struct Opts {
#[arg(short, long)]
text: Option<String>,
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
#[arg(short, long)]
disable_human_checker: bool,
#[arg(short, long)]
cracking_timeout: Option<u32>,
#[arg(short, long)]
api_mode: Option<bool>,
#[arg(short, long)]
file: Option<String>,
#[arg(short, long)]
regex: Option<String>,
}
pub fn parse_cli_args() -> (String, Config) {
let mut opts: Opts = Opts::parse();
let min_log_level = match opts.verbose {
0 => "Warn",
1 => "Info",
2 => "Debug",
_ => "Trace",
};
env_logger::init_from_env(
env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, min_log_level),
);
if opts.file.is_some() && opts.text.is_some() {
panic_failure_both_input_and_fail_provided();
}
let input_text: String = if opts.file.is_some() {
read_and_parse_file(opts.file.unwrap())
} else {
opts.text
.expect("Error. No input was provided. Please use ares --help")
};
opts.text = None;
opts.file = None;
trace!("Program was called with CLI 😉");
trace!("Parsed the arguments");
trace!("The inputted text is {}", &input_text);
cli_args_into_config_struct(opts, input_text)
}
pub fn read_and_parse_file(file_path: String) -> String {
let mut file = File::open(file_path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
if contents.ends_with(['\n', '\r']) {
contents.strip_suffix(['\n', '\r']).unwrap().to_owned()
} else {
contents
}
}
fn cli_args_into_config_struct(opts: Opts, text: String) -> (String, Config) {
(
text,
Config {
verbose: opts.verbose,
lemmeknow_config: Identifier::default(),
human_checker_on: !opts.disable_human_checker,
timeout: if opts.cracking_timeout.is_none() {
30
} else {
opts.cracking_timeout.unwrap()
},
api_mode: opts.api_mode.is_some(),
regex: opts.regex,
},
)
}