make duration pretty print clearer (#2150)

* make duration pretty print clearer

* fix typo and tests

* fix typo and tests
This commit is contained in:
Jonathan Turner 2020-07-10 14:06:52 -07:00 committed by GitHub
parent f32ab696d3
commit 6820d70e7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 40 additions and 28 deletions

2
Cargo.lock generated
View File

@ -2643,6 +2643,7 @@ dependencies = [
"nu-errors",
"nu-source",
"num-bigint",
"num-integer",
"num-traits 0.2.12",
"query_interface",
"serde 1.0.114",
@ -2820,6 +2821,7 @@ dependencies = [
"nu-plugin",
"nu-protocol",
"nu-source",
"num-bigint",
]
[[package]]

View File

@ -168,7 +168,7 @@ fn duration_math() {
"#
));
assert_eq!(actual.out, "8:00:00:00.0");
assert_eq!(actual.out, "8d");
}
#[test]
@ -180,7 +180,7 @@ fn duration_math_with_nanoseconds() {
"#
));
assert_eq!(actual.out, "7:00:00:00.00000001");
assert_eq!(actual.out, "7d 10ns");
}
#[test]
@ -192,7 +192,7 @@ fn duration_math_with_negative() {
"#
));
assert_eq!(actual.out, "-6:00:00:00.0");
assert_eq!(actual.out, "-6d");
}
#[test]

View File

@ -368,32 +368,42 @@ pub fn format_duration(duration: &BigInt) -> String {
let (mins, secs): (BigInt, BigInt) = secs.div_rem(&big_int_60);
let (hours, mins): (BigInt, BigInt) = mins.div_rem(&big_int_60);
let (days, hours): (BigInt, BigInt) = hours.div_rem(&big_int_24);
let decimals = if millis.is_zero() && micros.is_zero() && nanos.is_zero() {
String::from("0")
} else {
format!("{:03}{:03}{:03}", millis, micros, nanos)
.trim_end_matches('0')
.to_string()
};
match (
days.is_zero(),
hours.is_zero(),
mins.is_zero(),
secs.is_zero(),
) {
(true, true, true, true) => format!("{}.{}", if sign == 1 { "0" } else { "-0" }, decimals),
(true, true, true, _) => format!("{}.{}", sign * secs, decimals),
(true, true, _, _) => format!("{}:{:02}.{}", sign * mins, secs, decimals),
(true, _, _, _) => format!("{}:{:02}:{:02}.{}", sign * hours, mins, secs, decimals),
_ => format!(
"{}:{:02}:{:02}:{:02}.{}",
sign * days,
hours,
mins,
secs,
decimals
),
let mut output_prep = vec![];
if !days.is_zero() {
output_prep.push(format!("{}d", days));
}
if !hours.is_zero() {
output_prep.push(format!("{}h", hours));
}
if !mins.is_zero() {
output_prep.push(format!("{}m", mins));
}
if !secs.is_zero() {
output_prep.push(format!("{}s", secs));
}
if !millis.is_zero() {
output_prep.push(format!("{}ms", millis));
}
if !micros.is_zero() {
output_prep.push(format!("{}us", micros));
}
if !nanos.is_zero() {
output_prep.push(format!("{}ns", nanos));
}
format!(
"{}{}",
if sign == -1 { "-" } else { "" },
output_prep.join(" ")
)
}
#[allow(clippy::cognitive_complexity)]