nu-command 0.112.1

Nushell's built-in commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
use chrono::{Local, TimeZone, Utc};
use fancy_regex::{Regex, RegexBuilder};
use nu_engine::command_prelude::*;
use nu_protocol::PipelineMetadata;
use std::sync::LazyLock;

#[derive(Clone)]
pub struct DetectType;

impl Command for DetectType {
    fn name(&self) -> &str {
        "detect type"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .input_output_types(vec![(Type::String, Type::Any), (Type::Any, Type::Any)])
            .switch(
                "prefer-filesize",
                "For ints display them as human-readable file sizes.",
                Some('f'),
            )
            .switch(
                "prefer-dmy",
                "Prefer day-month-year format for ambiguous dates.",
                None,
            )
            .category(Category::Strings)
            .allow_variants_without_examples(true)
    }

    fn description(&self) -> &str {
        "Infer Nushell datatype from a string."
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["convert", "conversion"]
    }

    fn examples(&self) -> Vec<Example<'_>> {
        vec![
            Example {
                description: "Bool from string",
                example: "'true' | detect type",
                result: Some(Value::test_bool(true)),
            },
            Example {
                description: "Bool is case insensitive",
                example: "'FALSE' | detect type",
                result: Some(Value::test_bool(false)),
            },
            Example {
                description: "Int from plain digits",
                example: "'42' | detect type",
                result: Some(Value::test_int(42)),
            },
            Example {
                description: "Int with underscores",
                example: "'1_000_000' | detect type",
                result: Some(Value::test_int(1_000_000)),
            },
            Example {
                description: "Int with commas",
                example: "'1,234,567' | detect type",
                result: Some(Value::test_int(1_234_567)),
            },
            #[allow(clippy::approx_constant, reason = "approx PI in examples is fine")]
            Example {
                description: "Float from decimal",
                example: "'3.14' | detect type",
                result: Some(Value::test_float(3.14)),
            },
            Example {
                description: "Float in scientific notation",
                example: "'6.02e23' | detect type",
                result: Some(Value::test_float(6.02e23)),
            },
            Example {
                description: "Prefer filesize for ints",
                example: "'1024' | detect type -f",
                result: Some(Value::test_filesize(1024)),
            },
            Example {
                description: "Date Y-M-D",
                example: "'2022-01-01' | detect type",
                result: Some(Value::test_date(
                    Local.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap().into(),
                )),
            },
            Example {
                description: "Date with time and offset",
                example: "'2022-01-01T00:00:00Z' | detect type",
                result: Some(Value::test_date(
                    Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap().into(),
                )),
            },
            Example {
                description: "Date D-M-Y",
                example: "'31-12-2021' | detect type",
                result: Some(Value::test_date(
                    Local
                        .with_ymd_and_hms(2021, 12, 31, 0, 0, 0)
                        .unwrap()
                        .into(),
                )),
            },
            Example {
                description: "Date M-D-Y (default for ambiguous)",
                example: "'01/02/2025' | detect type",
                result: Some(Value::test_date(
                    Local.with_ymd_and_hms(2025, 1, 2, 0, 0, 0).unwrap().into(),
                )),
            },
            Example {
                description: "Prefer DMY for ambiguous dates",
                example: "'01/02/2025' | detect type --prefer-dmy",
                result: Some(Value::test_date(
                    Local.with_ymd_and_hms(2025, 2, 1, 0, 0, 0).unwrap().into(),
                )),
            },
            Example {
                description: "Unknown stays a string",
                example: "'not-a-number' | detect type",
                result: Some(Value::test_string("not-a-number")),
            },
        ]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        mut input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let span = call.head;
        let display_as_filesize = call.has_flag(engine_state, stack, "prefer-filesize")?;
        let prefer_dmy = call.has_flag(engine_state, stack, "prefer-dmy")?;
        let metadata = input.take_metadata();
        let val = input.into_value(call.head)?;
        process(val, metadata, display_as_filesize, prefer_dmy, span)
    }
}

// This function serves to modify the input string by swapping the day and month components
// (e.g., turning `"01/02/2025"` into `"02/01/2025"`) so that `dtparse::parse`, which defaults to interpreting
// ambiguous dates as month-day-year (MDY), correctly parses it as day-month-year (DMY) when `dayfirst` is true.
// This is necessary because `dtparse::parse` doesn't expose a direct `dayfirst` option in its API, and the
// swap ensures consistent parsing based on the regex match. It could be written more idiomatically and with
// the regexes but this is a simpler approach and doesn't have to mess with parsing the time component.
fn swap_day_month(input: &str) -> String {
    let re_slash =
        fancy_regex::Regex::new(r"(\d{1,2})/(\d{1,2})/(\d{4,})").expect("regex should be valid");
    let swapped_slash = re_slash.replace_all(input, "$2/$1/$3");
    let re_dash =
        fancy_regex::Regex::new(r"(\d{1,2})-(\d{1,2})-(\d{4,})").expect("regex should be valid");
    re_dash.replace_all(&swapped_slash, "$2-$1-$3").to_string()
}

fn parse_date_from_string_with_dayfirst(
    input: &str,
    span: Span,
    dayfirst: bool,
) -> Result<chrono::DateTime<chrono::FixedOffset>, nu_protocol::Value> {
    let input = if dayfirst {
        swap_day_month(input)
    } else {
        input.to_string()
    };
    match dtparse::parse(&input) {
        Ok((native_dt, fixed_offset)) => {
            let offset = match fixed_offset {
                Some(offset) => offset,
                None => *chrono::Local
                    .from_local_datetime(&native_dt)
                    .single()
                    .unwrap_or_default()
                    .offset(),
            };
            match offset.from_local_datetime(&native_dt) {
                chrono::LocalResult::Single(d) => Ok(d),
                chrono::LocalResult::Ambiguous(d, _) => Ok(d),
                chrono::LocalResult::None => Err(nu_protocol::Value::error(
                    nu_protocol::ShellError::DatetimeParseError {
                        msg: input.to_string(),
                        span,
                    },
                    span,
                )),
            }
        }
        Err(_) => Err(nu_protocol::Value::error(
            nu_protocol::ShellError::DatetimeParseError {
                msg: input.to_string(),
                span,
            },
            span,
        )),
    }
}

// This function will check if a value matches a regular expression for a particular datatype.
// If it does, it will convert the value to that datatype.
fn process(
    val: Value,
    metadata: Option<PipelineMetadata>,
    display_as_filesize: bool,
    prefer_dmy: bool,
    span: Span,
) -> Result<PipelineData, ShellError> {
    // step 1: convert value to string
    let val_str = val.coerce_str().unwrap_or_default();

    // Determine the order of checking ambiguous date formats (DMY vs MDY) based on the prefer_dmy flag.
    // This ensures that when dates like "01/02/2025" are encountered, we check the preferred format first
    // (e.g., DMY for day-month-year or MDY for month-day-year) to handle ambiguity correctly.
    let (first_regex, first_dayfirst, first_name) = if prefer_dmy {
        (&DATETIME_DMY_RE, true, "DATETIME_DMY_RE")
    } else {
        (&DATETIME_MDY_RE, false, "DATETIME_MDY_RE")
    };
    let (second_regex, second_dayfirst, second_name) = if prefer_dmy {
        (&DATETIME_MDY_RE, false, "DATETIME_MDY_RE")
    } else {
        (&DATETIME_DMY_RE, true, "DATETIME_DMY_RE")
    };

    // step 2: bounce string up against regexes
    let value = if BOOLEAN_RE.is_match(&val_str).unwrap_or(false) {
        let bval = val_str
            .to_lowercase()
            .parse::<bool>()
            .map_err(|_| ShellError::CantConvert {
                to_type: "string".to_string(),
                from_type: "bool".to_string(),
                span,
                help: Some(format!(
                    r#""{val_str}" does not represent a valid boolean value"#
                )),
            })?;

        Ok(Value::bool(bval, span))
    } else if FLOAT_RE.is_match(&val_str).unwrap_or(false) {
        let fval = val_str
            .parse::<f64>()
            .map_err(|_| ShellError::CantConvert {
                to_type: "float".to_string(),
                from_type: "string".to_string(),
                span,
                help: Some(format!(
                    r#""{val_str}" does not represent a valid floating point value"#
                )),
            })?;

        Ok(Value::float(fval, span))
    } else if INTEGER_RE.is_match(&val_str).unwrap_or(false) {
        let ival = val_str
            .parse::<i64>()
            .map_err(|_| ShellError::CantConvert {
                to_type: "int".to_string(),
                from_type: "string".to_string(),
                span,
                help: Some(format!(
                    r#""{val_str}" does not represent a valid integer value"#
                )),
            })?;

        if display_as_filesize {
            Ok(Value::filesize(ival, span))
        } else {
            Ok(Value::int(ival, span))
        }
    } else if INTEGER_WITH_DELIMS_RE.is_match(&val_str).unwrap_or(false) {
        let mut val_str = val_str.into_owned();
        val_str.retain(|x| !['_', ','].contains(&x));

        let ival = val_str
            .parse::<i64>()
            .map_err(|_| ShellError::CantConvert {
                to_type: "int".to_string(),
                from_type: "string".to_string(),
                span,
                help: Some(format!(
                    r#""{val_str}" does not represent a valid integer value"#
                )),
            })?;

        if display_as_filesize {
            Ok(Value::filesize(ival, span))
        } else {
            Ok(Value::int(ival, span))
        }
    } else if first_regex.is_match(&val_str).unwrap_or(false) {
        let dt =
            parse_date_from_string_with_dayfirst(&val_str, span, first_dayfirst).map_err(|_| {
                ShellError::CantConvert {
                    to_type: "datetime".to_string(),
                    from_type: "string".to_string(),
                    span,
                    help: Some(format!(
                        r#""{val_str}" does not represent a valid {first_name} value"#
                    )),
                }
            })?;
        Ok(Value::date(dt, span))
    } else if second_regex.is_match(&val_str).unwrap_or(false) {
        let dt = parse_date_from_string_with_dayfirst(&val_str, span, second_dayfirst).map_err(
            |_| ShellError::CantConvert {
                to_type: "datetime".to_string(),
                from_type: "string".to_string(),
                span,
                help: Some(format!(
                    r#""{val_str}" does not represent a valid {second_name} value"#
                )),
            },
        )?;
        Ok(Value::date(dt, span))
    } else if DATETIME_YMD_RE.is_match(&val_str).unwrap_or(false) {
        let dt = parse_date_from_string_with_dayfirst(&val_str, span, false).map_err(|_| {
            ShellError::CantConvert {
                to_type: "datetime".to_string(),
                from_type: "string".to_string(),
                span,
                help: Some(format!(
                    r#""{val_str}" does not represent a valid DATETIME_YMD_RE value"#
                )),
            }
        })?;

        Ok(Value::date(dt, span))
    } else if DATETIME_YMDZ_RE.is_match(&val_str).unwrap_or(false) {
        let dt = parse_date_from_string_with_dayfirst(&val_str, span, false).map_err(|_| {
            ShellError::CantConvert {
                to_type: "datetime".to_string(),
                from_type: "string".to_string(),
                span,
                help: Some(format!(
                    r#""{val_str}" does not represent a valid DATETIME_YMDZ_RE value"#
                )),
            }
        })?;

        Ok(Value::date(dt, span))
    } else {
        // If we don't know what it is, just return whatever it was passed in as
        return Ok(val.into_pipeline_data_with_metadata(metadata));
    };

    value.map(|value| {
        value.into_pipeline_data_with_metadata(
            metadata.map(|metadata| metadata.with_content_type(None)),
        )
    })
}

// region: datatype regexes
// Examples: "31-12-2021", "01/01/2022", "15-06-2023 12:30"
const DATETIME_DMY_PATTERN: &str = r#"(?x)
        ^
        ['"]?                        # optional quotes
        (?:\d{1,2})                  # day
        [-/]                         # separator
        (?P<month>0?[1-9]|1[0-2])        # month
        [-/]                         # separator
        (?:\d{4,})                   # year
        (?:
            [T\ ]                    # separator
            (?:\d{2})                # hour
            :?                       # separator
            (?:\d{2})                # minute
            (?:
                :?                   # separator
                (?:\d{2})            # second
                (?:
                    \.(?:\d{1,9})    # subsecond
                )?
            )?
        )?
        ['"]?                        # optional quotes
        $
        "#;

static DATETIME_DMY_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(DATETIME_DMY_PATTERN).expect("datetime_dmy_pattern should be valid")
});
// Examples: "2022-01-01", "2022/01/01", "2022-01-01T00:00:00"
const DATETIME_YMD_PATTERN: &str = r#"(?x)
        ^
        ['"]?                      # optional quotes
        (?:\d{4,})                 # year
        [-/]                       # separator
        (?P<month>0?[1-9]|1[0-2])      # month
        [-/]                       # separator
        (?:\d{1,2})                # day
        (?:
            [T\ ]                  # separator
            (?:\d{2})              # hour
            :?                     # separator
            (?:\d{2})              # minute
            (?:
                :?                 # separator
                (?:\d{2})          # seconds
                (?:
                    \.(?:\d{1,9})  # subsecond
                )?
            )?
        )?
        ['"]?                      # optional quotes
        $
        "#;
static DATETIME_YMD_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(DATETIME_YMD_PATTERN).expect("datetime_ymd_pattern should be valid")
});
// Examples: "2022-01-01T00:00:00Z", "2022-01-01T00:00:00+01:00"
const DATETIME_YMDZ_PATTERN: &str = r#"(?x)
        ^
        ['"]?                  # optional quotes
        (?:\d{4,})             # year
        [-/]                   # separator
        (?P<month>0?[1-9]|1[0-2])  # month
        [-/]                   # separator
        (?:\d{1,2})            # day
        [T\ ]                  # separator
        (?:\d{2})              # hour
        :?                     # separator
        (?:\d{2})              # minute
        (?:
            :?                 # separator
            (?:\d{2})          # second
            (?:
                \.(?:\d{1,9})  # subsecond
            )?
        )?
        \s?                    # optional space
        (?:
            # offset (e.g. +01:00)
            [+-](?:\d{2})
            :?
            (?:\d{2})
            # or Zulu suffix
            |Z
        )
        ['"]?                  # optional quotes
        $
        "#;
static DATETIME_YMDZ_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(DATETIME_YMDZ_PATTERN).expect("datetime_ymdz_pattern should be valid")
});

// Examples: "09/24/2012", "09/24/2012 02:43:48", "01/01/2022"
const DATETIME_MDY_PATTERN: &str = r#"(?x)
        ^
        ['"]?                        # optional quotes
        (?P<month>0?[1-9]|1[0-2])        # month
        [-/]                         # separator
        (?:\d{1,2})                  # day
        [-/]                         # separator
        (?:\d{4,})                   # year
        (?:
            [T\ ]                    # separator
            (?:\d{2})                # hour
            :?                       # separator
            (?:\d{2})                # minute
            (?:
                :?                   # separator
                (?:\d{2})            # second
                (?:
                    \.(?:\d{1,9})    # subsecond
                )?
            )?
        )?
        ['"]?                        # optional quotes
        $
        "#;

static DATETIME_MDY_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(DATETIME_MDY_PATTERN).expect("datetime_mdy_pattern should be valid")
});

// Examples: "0.1", "3.0", "3.00001", "-9.9990e-003", "inf", "NaN"
static FLOAT_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*[-+]?((\d*\.\d+)([eE][-+]?\d+)?|inf|NaN|(\d+)[eE][-+]?\d+|\d+\.)$")
        .expect("float pattern should be valid")
});

// Examples: "0", "1", "10", "100", "1000"
static INTEGER_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*-?(\d+)$").expect("integer pattern should be valid"));

// Examples: "1_000", "10_000", "100_000", "1,000", "10,000"
static INTEGER_WITH_DELIMS_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*-?(\d{1,3}([,_]\d{3})+)$")
        .expect("integer with delimiters pattern should be valid")
});

// Examples: "true", "false", "True", "FALSE"
static BOOLEAN_RE: LazyLock<Regex> = LazyLock::new(|| {
    RegexBuilder::new(r"^\s*(true)$|^(false)$")
        .case_insensitive(true)
        .build()
        .expect("boolean pattern should be valid")
});
// endregion:

#[cfg(test)]
mod test {
    use super::*;
    use rstest::rstest;

    #[test]
    fn test_examples() -> nu_test_support::Result {
        nu_test_support::test().examples(DetectType)
    }

    #[test]
    fn test_float_parse() {
        // The regex should work on all these but nushell's float parser is more strict
        assert!(FLOAT_RE.is_match("0.1").unwrap());
        assert!(FLOAT_RE.is_match("3.0").unwrap());
        assert!(FLOAT_RE.is_match("3.00001").unwrap());
        assert!(FLOAT_RE.is_match("-9.9990e-003").unwrap());
        assert!(FLOAT_RE.is_match("9.9990e+003").unwrap());
        assert!(FLOAT_RE.is_match("9.9990E+003").unwrap());
        assert!(FLOAT_RE.is_match("9.9990E+003").unwrap());
        assert!(FLOAT_RE.is_match(".5").unwrap());
        assert!(FLOAT_RE.is_match("2.5E-10").unwrap());
        assert!(FLOAT_RE.is_match("2.5e10").unwrap());
        assert!(FLOAT_RE.is_match("NaN").unwrap());
        assert!(FLOAT_RE.is_match("-NaN").unwrap());
        assert!(FLOAT_RE.is_match("-inf").unwrap());
        assert!(FLOAT_RE.is_match("inf").unwrap());
        assert!(FLOAT_RE.is_match("-7e-05").unwrap());
        assert!(FLOAT_RE.is_match("7e-05").unwrap());
        assert!(FLOAT_RE.is_match("+7e+05").unwrap());
    }

    #[test]
    fn test_int_parse() {
        assert!(INTEGER_RE.is_match("0").unwrap());
        assert!(INTEGER_RE.is_match("1").unwrap());
        assert!(INTEGER_RE.is_match("10").unwrap());
        assert!(INTEGER_RE.is_match("100").unwrap());
        assert!(INTEGER_RE.is_match("1000").unwrap());
        assert!(INTEGER_RE.is_match("10000").unwrap());
        assert!(INTEGER_RE.is_match("100000").unwrap());
        assert!(INTEGER_RE.is_match("1000000").unwrap());
        assert!(INTEGER_RE.is_match("10000000").unwrap());
        assert!(INTEGER_RE.is_match("100000000").unwrap());
        assert!(INTEGER_RE.is_match("1000000000").unwrap());
        assert!(INTEGER_RE.is_match("10000000000").unwrap());
        assert!(INTEGER_RE.is_match("100000000000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("1_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("10_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("100_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("1_000_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("10_000_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("100_000_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("1_000_000_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("10_000_000_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("100_000_000_000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("1,000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("10,000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("100,000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("1,000,000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("10,000,000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("100,000,000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("1,000,000,000").unwrap());
        assert!(INTEGER_WITH_DELIMS_RE.is_match("10,000,000,000").unwrap());
    }

    #[test]
    fn test_bool_parse() {
        assert!(BOOLEAN_RE.is_match("true").unwrap());
        assert!(BOOLEAN_RE.is_match("false").unwrap());
        assert!(!BOOLEAN_RE.is_match("1").unwrap());
        assert!(!BOOLEAN_RE.is_match("0").unwrap());
    }

    #[test]
    fn test_datetime_ymdz_pattern() {
        assert!(DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00Z").unwrap());
        assert!(
            DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789Z")
                .unwrap()
        );
        assert!(
            DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00+01:00")
                .unwrap()
        );
        assert!(
            DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789+01:00")
                .unwrap()
        );
        assert!(
            DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00-01:00")
                .unwrap()
        );
        assert!(
            DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789-01:00")
                .unwrap()
        );
        assert!(DATETIME_YMDZ_RE.is_match("'2022-01-01T00:00:00Z'").unwrap());

        assert!(!DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00").unwrap());
        assert!(!DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00.").unwrap());
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789")
                .unwrap()
        );
        assert!(!DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00+01").unwrap());
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00+01:0")
                .unwrap()
        );
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00+1:00")
                .unwrap()
        );
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789+01")
                .unwrap()
        );
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789+01:0")
                .unwrap()
        );
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789+1:00")
                .unwrap()
        );
        assert!(!DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00-01").unwrap());
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00-01:0")
                .unwrap()
        );
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00-1:00")
                .unwrap()
        );
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789-01")
                .unwrap()
        );
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789-01:0")
                .unwrap()
        );
        assert!(
            !DATETIME_YMDZ_RE
                .is_match("2022-01-01T00:00:00.123456789-1:00")
                .unwrap()
        );
    }

    #[test]
    fn test_datetime_ymd_pattern() {
        assert!(DATETIME_YMD_RE.is_match("2022-01-01").unwrap());
        assert!(DATETIME_YMD_RE.is_match("2022/01/01").unwrap());
        assert!(DATETIME_YMD_RE.is_match("2022-01-01T00:00:00").unwrap());
        assert!(
            DATETIME_YMD_RE
                .is_match("2022-01-01T00:00:00.000000000")
                .unwrap()
        );
        assert!(DATETIME_YMD_RE.is_match("'2022-01-01'").unwrap());

        // The regex isn't this specific, but it would be nice if it were
        // assert!(!DATETIME_YMD_RE.is_match("2022-13-01").unwrap());
        // assert!(!DATETIME_YMD_RE.is_match("2022-01-32").unwrap());
        // assert!(!DATETIME_YMD_RE.is_match("2022-01-01T24:00:00").unwrap());
        // assert!(!DATETIME_YMD_RE.is_match("2022-01-01T00:60:00").unwrap());
        // assert!(!DATETIME_YMD_RE.is_match("2022-01-01T00:00:60").unwrap());
        assert!(
            !DATETIME_YMD_RE
                .is_match("2022-01-01T00:00:00.0000000000")
                .unwrap()
        );
    }

    #[test]
    fn test_datetime_dmy_pattern() {
        assert!(DATETIME_DMY_RE.is_match("31-12-2021").unwrap());
        assert!(DATETIME_DMY_RE.is_match("01/01/2022").unwrap());
        assert!(DATETIME_DMY_RE.is_match("15-06-2023 12:30").unwrap());
        assert!(!DATETIME_DMY_RE.is_match("2022-13-01").unwrap());
        assert!(!DATETIME_DMY_RE.is_match("2022-01-32").unwrap());
        assert!(!DATETIME_DMY_RE.is_match("2022-01-01 24:00").unwrap());
    }

    #[test]
    fn test_datetime_mdy_pattern() {
        assert!(DATETIME_MDY_RE.is_match("09/24/2012").unwrap());
        assert!(DATETIME_MDY_RE.is_match("09/24/2012 02:43:48").unwrap());
        assert!(DATETIME_MDY_RE.is_match("01/01/2022").unwrap());
        assert!(!DATETIME_MDY_RE.is_match("09/24/123").unwrap());
        assert!(!DATETIME_MDY_RE.is_match("09/24/2012 2:43:48").unwrap());
        assert!(!DATETIME_MDY_RE.is_match("009/24/2012").unwrap());
    }

    #[rstest]
    // Ambiguous date defaults to MDY (Jan 2)
    #[case("01/02/2025", 2025, 1, 2)]
    // Non-ambiguous DMY (Feb 13)
    #[case("13/02/2025", 2025, 2, 13)]
    // Non-ambiguous MDY (Feb 13)
    #[case("02/13/2025", 2025, 2, 13)]
    fn test_ambiguous_date_default(
        #[case] input: &str,
        #[case] year: i32,
        #[case] month: u32,
        #[case] day: u32,
    ) {
        use chrono::{DateTime, FixedOffset, Local, TimeZone};
        let span = Span::test_data();
        let result = process(Value::string(input, span), None, false, false, span)
            .unwrap()
            .into_value(span)
            .unwrap();

        if let Value::Date { val, .. } = result {
            assert_eq!(
                val,
                DateTime::<FixedOffset>::from(
                    Local.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap()
                )
            );
        } else {
            panic!("Expected date");
        }
    }

    #[rstest]
    // Ambiguous date with prefer_dmy=true -> parsed as Feb 1 (DMY)
    #[case("01/02/2025", 2025, 2, 1)]
    // Non-ambiguous still works (Feb 13)
    #[case("13/02/2025", 2025, 2, 13)]
    // Non-ambiguous still works (Feb 13)
    #[case("02/13/2025", 2025, 2, 13)]
    fn test_ambiguous_date_prefer_dmy(
        #[case] input: &str,
        #[case] year: i32,
        #[case] month: u32,
        #[case] day: u32,
    ) {
        use chrono::{DateTime, FixedOffset, Local, TimeZone};
        let span = Span::test_data();
        let result = process(Value::string(input, span), None, false, true, span)
            .unwrap()
            .into_value(span)
            .unwrap();

        if let Value::Date { val, .. } = result {
            assert_eq!(
                val,
                DateTime::<FixedOffset>::from(
                    Local.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap()
                )
            );
        } else {
            panic!("Expected date");
        }
    }
}