Skip to content

Commit

Permalink
Merge pull request #630 from rben01/format-datetime-error
Browse files Browse the repository at this point in the history
Improved formatting of `format_datetime` errors, including original jiff error
  • Loading branch information
sharkdp authored Nov 3, 2024
2 parents f064611 + b552f5d commit 547451f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
11 changes: 8 additions & 3 deletions numbat/src/ffi/datetime.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use compact_str::CompactString;
use jiff::fmt::strtime::BrokenDownTime;
use jiff::fmt::StdFmtWrite;
use jiff::Span;
use jiff::Timestamp;
use jiff::Zoned;
Expand All @@ -13,8 +15,6 @@ use crate::value::FunctionReference;
use crate::value::Value;
use crate::RuntimeError;

use std::fmt::Write;

pub fn now(_args: Args) -> Result<Value> {
return_datetime!(Zoned::now())
}
Expand All @@ -33,7 +33,12 @@ pub fn format_datetime(mut args: Args) -> Result<Value> {
let dt = datetime_arg!(args);

let mut output = CompactString::with_capacity(format.len());
write!(output, "{}", dt.strftime(&format)).map_err(|_| RuntimeError::DateFormattingError)?;
BrokenDownTime::from(&dt)
// jiff::fmt::StdFmtWrite is a wrapper that turns an arbitrary std::fmt::Write
// into a jiff::fmt::Write, which is necessary to write a formatted datetime
// into it
.format(&format, StdFmtWrite(&mut output))
.map_err(|e| RuntimeError::DateFormattingError(e.to_string()))?;

return_string!(owned = output)
}
Expand Down
4 changes: 2 additions & 2 deletions numbat/src/interpreter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ pub enum RuntimeError {
DurationOutOfRange,
#[error("DateTime out of range")]
DateTimeOutOfRange,
#[error("Error in datetime format. See https://docs.rs/jiff/latest/jiff/fmt/strtime/index.html#conversion-specifications for possible format specifiers.")]
DateFormattingError,
#[error("{0}. See https://docs.rs/jiff/latest/jiff/fmt/strtime/index.html#conversion-specifications for possible format specifiers.")]
DateFormattingError(String),

#[error("Invalid format specifiers: {0}")]
InvalidFormatSpecifiers(String),
Expand Down
8 changes: 6 additions & 2 deletions numbat/tests/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -741,8 +741,12 @@ fn test_datetime_runtime_errors() {
);
expect_failure(
"format_datetime(\"%Y-%m-%dT%H%:M\", now())",
"Error in datetime format",
)
"strftime formatting failed: found unrecognized directive %M following %:.",
);
expect_failure(
"format_datetime(\"%Y %;\", now())",
"strftime formatting failed: found unrecognized specifier directive %;.",
);
}

#[test]
Expand Down

0 comments on commit 547451f

Please sign in to comment.