use std::borrow::Cow;
use std::fmt::Display;
use crate::format::OutputFormat;
use crate::log_level::LogLevel;
#[derive(Debug)]
pub enum Arg<'a> {
ConfigFilePath(Cow<'a, str>),
LogLevel(LogLevel),
OutputFormat(OutputFormat),
MultiQuery,
Custom(Cow<'a, str>, Option<Cow<'a, str>>),
}
impl<'a> Arg<'a> {
pub(crate) fn as_output_format(&self) -> Option<OutputFormat> {
match self {
Self::OutputFormat(f) => Some(*f),
_ => None,
}
}
}
impl Display for Arg<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ConfigFilePath(v) => write!(f, "--config-file={v}"),
Self::LogLevel(v) => write!(f, "--log-level={}", v.as_str()),
Self::OutputFormat(v) => write!(f, "--output-format={}", v.as_str()),
Self::MultiQuery => write!(f, "-n"),
Self::Custom(k, v) => match v {
None => write!(f, "--{}", k.as_ref()),
Some(v) => write!(f, "--{k}={v}"),
},
}
}
}
pub(crate) fn extract_output_format(args: Option<&[Arg]>, default: OutputFormat) -> OutputFormat {
args.and_then(|args| args.iter().find_map(|a| a.as_output_format()))
.unwrap_or(default)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_arg_display_config_file_path() {
assert_eq!(
Arg::ConfigFilePath(Cow::from("my.xml")).to_string(),
"--config-file=my.xml"
);
}
#[test]
fn test_arg_display_log_level() {
assert_eq!(
Arg::LogLevel(LogLevel::Trace).to_string(),
"--log-level=trace"
);
assert_eq!(
Arg::LogLevel(LogLevel::Debug).to_string(),
"--log-level=debug"
);
assert_eq!(
Arg::LogLevel(LogLevel::Info).to_string(),
"--log-level=information"
);
assert_eq!(
Arg::LogLevel(LogLevel::Warn).to_string(),
"--log-level=warning"
);
assert_eq!(
Arg::LogLevel(LogLevel::Error).to_string(),
"--log-level=error"
);
}
#[test]
fn test_arg_display_output_format() {
assert_eq!(
Arg::OutputFormat(OutputFormat::JSONEachRow).to_string(),
"--output-format=JSONEachRow"
);
}
#[test]
fn test_arg_display_multi_query() {
assert_eq!(Arg::MultiQuery.to_string(), "-n");
}
#[test]
fn test_arg_display_custom_key_only() {
assert_eq!(
Arg::Custom("multiline".into(), None).to_string(),
"--multiline"
);
}
#[test]
fn test_arg_display_custom_key_value() {
assert_eq!(
Arg::Custom("priority".into(), Some("1".into())).to_string(),
"--priority=1"
);
}
}