use std::error::Error;
pub(crate) fn get_app_name() -> String {
std::env::current_exe()
.unwrap_or_default()
.file_name()
.unwrap_or_default()
.to_str()
.unwrap_or_default()
.to_string()
}
pub fn invalid_arg(sub: &str, other: &str) -> Box<dyn Error> {
let c = get_app_name();
let context = if sub.is_empty() {
c.clone()
} else {
format!("{c}: {sub}")
};
format!("{context}: invalid argument '{other}'\nUse '{c} --help' to see available options.")
.into()
}
pub fn missing_arg(sub: &str, essential: bool) -> Box<dyn Error> {
let c = get_app_name();
let msg = if essential {
"no essential parameter specified"
} else {
"no parameter specified"
};
format!("{c}: {sub}: {msg}\nUse '{c} --help' to see available options.").into()
}
pub fn parse_value(
sub: &str,
val_name: &str,
arg: &str,
next: Option<&str>,
) -> Result<String, String> {
let extracted: Option<String> = if let Some(pos) = arg.find('=') {
let val = &arg[pos + 1..];
if val.is_empty() {
None
} else {
Some(val.to_string())
}
} else {
next.and_then(|n| {
if n.is_empty() || n.starts_with('-') {
None
} else {
Some(n.to_string())
}
})
};
match extracted {
Some(value) => Ok(value),
None => {
let c = get_app_name();
let key = arg.split('=').next().unwrap_or(arg);
let sp = if arg.contains('=') { "=" } else { " " };
Err(format!(
"{}: {}: {} requires a <{}>.\nUsage: {} {} {}{}<{}>",
c, sub, key, val_name, c, sub, key, sp, val_name
))
}
}
}