Files
Darren Schroeder aa8bb3fd81 Move dates from chrono to jiff (#19626)
## Description

chrono is unmaintained, so this PR moves nushell's dates to jiff 1.0.
`Value::Date` now holds `nu_protocol::DateTime`, which stores Unix
seconds, nanoseconds and a jiff `Offset`. It is 16 bytes and `Copy`,
like chrono's type, so `Value` stays at 48 bytes. jiff does the
calendar, time zones, parsing and `strftime`. Its range, years -9999 to
9999, is now nushell's.

Output only changes where the release notes say so. `Display`, `Debug`,
RFC 3339, RFC 2822, serde and `format date` print what chrono printed,
localized names included. Input goes through jiff. Date literals, `from
nuon`, `FromStr` and serde use its RFC 3339 reader. `into datetime
--format`, `seq date --input-format` and `from kdl` use its strptime,
plus a small table that keeps chrono's meaning for `%c %x %X %r %v %+
%Z`, nushell's `%J` and `%Q`, and offsets with or without colons. `date
from-human` reads GNU `date` syntax through parse_datetime, after a few
rewrites such as `in 3 days` and `overmorrow`.

chrono-tz, chrono-humanize and human-date-parser leave the dependency
tree, along with the chrono features of rusqlite and calamine. chrono
stays in `Cargo.lock` because rmcp and polars use it. The
chrono-humanize wording and chrono's UTC offset readers are ported under
the MIT license, and each file keeps its notice.

## Before and after

main is 3d8a9cc6e. Both ran with `TZ=America/New_York` on 2026-11-21 at
13:38. Error cells are cut to the reason.

| Command | main | branch |
|---|---|---|
| `2025-04-18T16:04:32.02649+05:30 \| format date '%N'` | `× invalid
format` | `026490000` |
| `'9999-12-31' \| into datetime \| to nuon` |
`9999-12-31T00:00:00-05:00` | `× datetime parsing failed` |
| `2001-02-03T04:05Z \| to nuon` | `× Command 2001-02-03T04:05Z not
found` | `2001-02-03T04:05:00+00:00` |
| `2016-12-31T23:59:60.5Z \| to nuon` | `2016-12-31T23:59:60.500+00:00`
| `2016-12-31T23:59:59.500+00:00` |
| `'Today at 6pm' \| date from-human \| format date '%H:%M'` | `13:38` |
`18:00` |
| `'today at 6pm blah' \| date from-human \| format date '%H:%M'` |
`13:38` | `× Cannot parse as humanized date` |
| `'next hour' \| date from-human \| format date '%H:%M'` | `× Main
thread panicked.` | `14:38` |
| `'6pm tomorrow' \| date from-human \| format date '%a %H:%M'` | `×
Cannot parse as humanized date` | `Sun 18:00` |
| `'TZ="Europe/Paris" 2025-04-18 04:04' \| date from-human \| to nuon` |
`× Cannot parse as humanized date` | `2025-04-18T04:04:00+02:00` |
| `'2025-03-09 02:00' \| into datetime \| to nuon` |
`2025-03-09T02:00:00-05:00` | `2025-03-09T03:00:00-04:00` |
| `'2025-03-09 02:30' \| into datetime --format '%F %H:%M' \| to nuon` |
`× datetime parsing failed` | `2025-03-09T03:30:00-04:00` |
| `2026-07-01T16:00:00Z \| date to-timezone local \| to nuon` |
`2026-07-01T11:00:00-05:00` | `2026-07-01T12:00:00-04:00` |
| `'2021-02-30 10:00' \| into datetime --format '%F %H:%M' \| to nuon` |
`2026-11-21T10:00:00-05:00` | `× … parameter 'day' for 2021-02 is
invalid, must be in range 1..=28 …` |
| `'-5' \| into datetime --format '%s' \| to nuon` | `× can't convert
input contains invalid characters …` | `1969-12-31T23:59:55+00:00` |
| `'07/20/69' \| into datetime --format '%D' \| to nuon` |
`2069-07-20T00:00:00-04:00` | `1969-07-20T00:00:00-04:00` |
| `'Jan 05 2024' \| into datetime --format '%B %d %Y' \| to nuon` |
`2024-01-05T00:00:00-05:00` | `× … %B failed: unrecognized month name …`
|
| `'2021-03-04 10:00 PST' \| into datetime --format '%F %H:%M %Z' \| to
nuon` | `2021-03-04T10:00:00-05:00` | `× can't convert input contains
invalid characters …` |
| `'2021-03-04 10:00:00 -0800 GMT' \| into datetime --format '%F %T %z
%Z' \| to nuon` | `2021-03-04T10:00:00-08:00` | `× can't convert no
possible date and time matching input …` |
| `2100-07-01T12:00:00Z \| date to-timezone America/New_York \| format
date '%:z'` | `-05:00` | `-04:00` |

## Release notes

- Dates run from year -9999 to 9999, where main reached 262142.
9999-12-31 at UTC is past jiff's last instant, so `'9999-12-31' | into
datetime` is an error, and `from toml` and `from msgpack` keep such a
date as text.
- Date literals and `from nuon` read `2001-02-03T04:05Z`,
`[2024-01-15T10:00]` and offsets like `+0530` and `-08` as dates.
`2024-01-15T1030` is still a string, and a fraction longer than 9 digits
no longer reads.
- Second 60 reads as second 59 everywhere.
- `into datetime --format`, `seq date --input-format` and `from kdl`
follow jiff's strptime. A date that doesn't exist or a weekday that
doesn't match is an error, where main gave today at that time. `%B` and
`%A` take only full names, and `%b` and `%a` only abbreviations.
Two-digit years run from 1969 to 2068. `%s` can be negative, and it wins
over a date in the same text.
- `%Z` reads `UTC`, `GMT` and offsets. Other names such as `PST` are an
error, unless `%z` gives the offset, so `+0900 JST` reads. `UTC` or
`GMT` next to a different offset, as in `-0800 GMT`, is an error.
- `format date` and `$env.config.datetime_format` accept `%N`, `%#z` and
the `^` flag, and `datetime_format` drops `%E` and `%O` the way `format
date` does. `seq date --output-format` prints `+0000` for `%z` instead
of failing.
- `date from-human` reads GNU `date` syntax: `6pm tomorrow`, `today
1430`, `@1744972472`, and a leading `TZ="Europe/Paris"`. `next month`,
`next hour` and `today at 6pm` give the right date, where main misread
them or panicked. Text after a date is an error.
- A local time in a DST gap moves forward by the jump, with or without
`--format`. Wall-clock times get the offset of their own date, not
today's, in records, `date to-timezone local`, `date from-human`, `from
xlsx` and `from ods`.
- Time zones come from the system's tzdata, with a bundled 2026f copy as
the fallback, instead of chrono-tz's 2025b. 13 zones have a different
offset today than on main, and DST rules continue past 2099.
- RFC 3339, RFC 2822 and TOML text round a local mean time offset to the
minute and move the clock with it, so the text names the same instant. A
record's `timezone` keeps its seconds.
- polars rejects a date outside 1677-09-21 to 2262-04-11, where main
stored 1970-01-01 or null. A record `year` too large for 32 bits is an
error, and `to plist` rejects years before 0 instead of crashing.
- For plugin authors, `Value::date` and `Value::as_date` take
`nu_protocol::DateTime`. nu-protocol's `chrono` feature converts to and
from `chrono::DateTime<FixedOffset>`. Older plugins keep working, since
dates cross the wire as the same text.
2026-11-23 08:26:13 -06:00

227 lines
7.6 KiB
Rust

use std::{collections::HashMap, fmt::Debug, path::PathBuf, sync::LazyLock};
use nu_protocol::DateTime;
use nu_test_support::prelude::*;
use pretty_assertions::assert_eq;
use rstest::{Context, rstest};
static GENERATE: LazyLock<PathBuf> =
LazyLock::new(|| FIXTURES.join("formats").join("msgpack").join("generate.nu"));
fn msgpack_test<T: FromValue>(playground: Playground, fixture_name: impl AsRef<str>) -> Result<T> {
msgpack_test_with_opts(playground, fixture_name, "")
}
fn msgpack_test_with_opts<T: FromValue>(
playground: Playground,
fixture_name: impl AsRef<str>,
opts: impl AsRef<str>,
) -> Result<T> {
let fixture_name = fixture_name.as_ref().replace('_', "-");
let opts = opts.as_ref();
let mut tester = test().cwd(playground.path());
let generate = format!("use {}; generate main {fixture_name}", GENERATE.display());
let _: Value = tester
.run(generate)
.expect("could not generate msgpack fixture");
let open = format!("open {fixture_name}.msgpack --raw | from msgpack {opts}");
tester.run(open)
}
#[rstest]
#[nu_test_support::test]
fn sample(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let values: Vec<Value> = msgpack_test(playground, ctx.name)?;
let mut values = values.into_iter();
let values = &mut values;
fn assert_next<T: FromValue + Debug + PartialEq>(
values: &mut impl Iterator<Item = Value>,
comparison: T,
) -> Result {
let expect_msg = format!("expected next value to compare against {comparison:?}");
let value = T::from_value(values.next().expect(&expect_msg))?;
assert_eq!(value, comparison);
Ok(())
}
assert_next(values, ())?;
assert_next(values, false)?;
assert_next(values, true)?;
assert_next(values, 17i8)?;
assert_next(values, -2i8)?;
assert_next(values, 34u16)?; // FromValue is not implemented for u8
assert_next(values, 1u16)?;
assert_next(values, 1u32)?;
assert_next(values, 1u64)?;
assert_next(values, -2i8)?;
assert_next(values, -2i16)?;
assert_next(values, -2i32)?;
assert_next(values, -2i64)?;
assert_next(values, -1024.125f32)?;
assert_next(values, -1024.125f64)?;
assert_next(values, String::from(""))?;
assert_next(values, String::from("foo"))?;
assert_next(values, String::from("hello"))?;
assert_next(values, String::from("nushell"))?;
assert_next(values, String::from("love you"))?;
assert_next(values, Vec::<u8>::from_iter([0xf0, 0xff, 0x00]))?;
assert_next(values, Vec::<u8>::from_iter([0xde, 0xad, 0xbe, 0xef]))?;
assert_next(values, Vec::<u8>::from_iter([0xc0, 0xff, 0xee, 0xff, 0xee]))?;
assert_next(values, (true, -2))?;
assert_next(values, (34, 1, ()))?;
assert_next(values, (-1024.125, String::from("foo")))?;
assert_next(
values,
HashMap::from_iter([
(String::from("foo"), Value::test_int(-2)),
(String::from("bar"), Value::test_string("hello")),
]),
)?;
assert_next(
values,
HashMap::from_iter([(String::from("hello"), Value::test_bool(true))]),
)?;
assert_next(
values,
HashMap::from_iter([
(String::from("nushell"), String::from("rocks")),
(String::from("foo"), String::from("bar")),
(String::from("hello"), String::from("world")),
]),
)?;
assert_next(
values,
DateTime::parse_rfc3339("1970-01-01T00:00:01+00:00").expect("valid datetime format"),
)?;
assert_next(
values,
DateTime::parse_rfc3339("1970-01-01T00:00:01.100+00:00").expect("valid datetime format"),
)?;
assert_next(
values,
DateTime::parse_rfc3339("1970-01-01T00:00:01.100+00:00").expect("valid datetime format"),
)?;
assert!(values.next().is_none());
Ok(())
}
#[test]
fn sample_roundtrip() -> Result {
let path_to_sample_nuon = FIXTURES.join("formats").join("msgpack").join("sample.nuon");
let sample_nuon =
std::fs::read_to_string(&path_to_sample_nuon).expect("failed to open sample.nuon");
let sample_value =
nuon::from_nuon(&sample_nuon, None).expect("failed to deserialize sample.nuon");
let outcome: Value = test().run_with_data("to msgpack | from msgpack", sample_value.clone())?;
assert_eq!(sample_value, outcome);
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn objects(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let value: (HashMap<String, String>, String) =
msgpack_test_with_opts(playground, ctx.name, "--objects")?;
assert_eq!(value.0["nushell"], "rocks");
assert_eq!(value.0.len(), 1);
assert_eq!(value.1, "seriously");
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn max_depth(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let msg = shell_error.generic_msg()?;
assert_contains("exceeded depth limit", msg);
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn non_utf8(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
assert!(matches!(shell_error, ShellError::NonUtf8Custom { .. }));
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn empty(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let msg = shell_error.generic_msg()?;
assert_eq!(msg, "failed to fill whole buffer");
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn eof(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let msg = shell_error.generic_msg()?;
assert_eq!(msg, "failed to fill whole buffer");
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn after_eof(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let error = shell_error.generic_error()?;
assert_eq!(error, "Additional data after end of MessagePack object");
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn reserved(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let msg = shell_error.generic_msg()?;
assert_contains("Reserved", msg);
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn u64_too_large(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let error = shell_error.generic_error()?;
assert_eq!(error, "MessagePack integer too big for Nushell");
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn non_string_map_key(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let msg = shell_error.generic_msg()?;
assert_contains("string key", msg);
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn timestamp_wrong_length(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let error = shell_error.generic_error()?;
assert_eq!(error, "Unknown MessagePack extension");
Ok(())
}
#[rstest]
#[nu_test_support::test]
fn other_extension_type(#[context] ctx: Context, #[ignore] playground: Playground) -> Result {
let shell_error = msgpack_test(playground, ctx.name).expect_error()?;
let error = shell_error.generic_error()?;
assert_eq!(error, "Unknown MessagePack extension");
Ok(())
}