use clap::{command, Arg};
use fundu::TimeUnit::*;
use fundu::{CustomDurationParser, CustomTimeUnit, Multiplier};
const CUSTOM_TIME_UNITS: [CustomTimeUnit; 11] = [
CustomTimeUnit::with_default(NanoSecond, &["ns", "nano", "nanos"]),
CustomTimeUnit::with_default(MicroSecond, &["µs", "Ms", "micro", "micros"]),
CustomTimeUnit::with_default(MilliSecond, &["ms", "milli", "millis"]),
CustomTimeUnit::with_default(Second, &["s", "sec", "secs", "second", "seconds"]),
CustomTimeUnit::with_default(Minute, &["m", "min", "mins", "minutes"]),
CustomTimeUnit::with_default(Hour, &["h", "hr", "hrs", "hour", "hours"]),
CustomTimeUnit::with_default(Day, &["d", "day", "days"]),
CustomTimeUnit::with_default(Week, &["w", "week", "weeks"]),
CustomTimeUnit::new(
Week,
&["f", "fortnight", "fortnights"],
Some(Multiplier(2, 0)),
),
CustomTimeUnit::new(
Second,
&["M", "mon", "month", "months"],
Some(Multiplier(236_059_151, -2)),
),
CustomTimeUnit::new(
Second,
&["y", "yr", "year", "years"],
Some(Multiplier(3_155_814_976, -2)),
),
];
fn main() {
let matches = command!()
.allow_negative_numbers(true)
.arg(Arg::new("DURATION").action(clap::ArgAction::Append))
.get_matches();
let parser = CustomDurationParser::builder()
.time_units(&CUSTOM_TIME_UNITS)
.default_unit(NanoSecond)
.disable_exponent()
.allow_time_unit_delimiter()
.inner_delimiter(|byte| matches!(byte, b'\t' | b'\n' | b'\r' | b' '))
.build();
println!(
"A simple calculator to calculate the input duration to seconds (Default time unit is the \
nano second):\n"
);
println!("{:>20}|{:>31}", "Input", "Result in seconds");
println!("{}|{}", "-".repeat(20), "-".repeat(31));
for input in matches
.get_many("DURATION")
.expect("At least one argument must be present")
.cloned()
.collect::<Vec<String>>()
{
match parser.parse(input.trim()) {
Ok(duration) => {
let duration: std::time::Duration = duration.try_into().unwrap();
println!(
"{:>20}|{:21}.{:09}",
&input,
duration.as_secs(),
duration.subsec_nanos()
)
}
Err(error) => eprintln!("Error parsing '{}': {}", &input, error),
}
}
}