use std::fmt::Write;
use super::GrokError;
use crate::time::{Item, Name, Number, StrptimeDialect, TimeFormat, Zone};
const MONTHS: [&str; 12] = [
"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
];
const MONTH_ENDS: [&str; 12] = [
"uary", "ruary", "ch", "il", "", "e", "y", "ust", "tember", "ober", "ember", "ember",
];
const WEEKDAYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
const WEEKDAY_ENDS: [&str; 7] = ["day", "sday", "nesday", "rsday", "day", "urday", "day"];
const HOURS: &str = "(?:[01][0-9]|2[0-3])";
const SIGN: &str = r"[+\-\x{2212}]";
pub fn chrono_date_pattern(format: &str) -> Result<String, GrokError> {
let fail = |why: &str| GrokError::Date(format!("{format:?}: {why}"));
let built = match TimeFormat::strptime(StrptimeDialect::Chrono, format) {
Ok(TimeFormat::Chrono(built)) => built,
Ok(_) => return Err(fail("not a chrono format")),
Err(e) => return Err(fail(&e.to_string())),
};
let items = built.items();
let mut out = String::with_capacity(format.len() * 16);
let mut i = 0;
while let Some(item) = items.get(i) {
let after = &items[i + 1..];
let digit_next = digit_next(after);
let spaced = matches!(after.first(), Some(Item::Space)) && digit_next_after(after);
match item {
Item::Literal(text) => regex_syntax::escape_into(text, &mut out),
Item::Space => out.push_str(r"\s*"),
Item::Number(number) if spaced => {
let free =
numeric(*number, false).ok_or_else(|| fail("a number with no matcher"))?;
let _ = write!(out, r"\s*(?:(?:{free})\s+");
if let Some(fixed) = numeric(*number, true) {
let _ = write!(out, r"|(?:{fixed})\s*");
}
out.push(')');
i += 1;
}
Item::Number(number) => {
let re = numeric(*number, digit_next)
.ok_or_else(|| fail("a digit straight after %s"))?;
out.push_str(r"\s*(?:");
out.push_str(re);
out.push(')');
}
Item::DotFraction(None) if spaced => {
out.push_str(r"(?:\.[0-9]+)?\s+");
i += 1;
}
Item::Name(name) => out.push_str(&names(*name)),
Item::Meridiem => out.push_str("[AaPp][Mm]"),
Item::Fraction(n) => {
let _ = write!(out, "[0-9]{{{n}}}");
}
Item::DotFraction(Some(n)) => {
let _ = write!(out, r"(?:\.[0-9]{{{n}}})?");
}
Item::DotFraction(None) => {
if digit_next {
return Err(fail("a digit straight after %.f"));
}
out.push_str(r"(?:\.[0-9]+)?");
}
Item::ZoneName => {
if !matches!(items.get(i + 1), None | Some(Item::Space)) {
return Err(fail("%Z has to end the format or sit before white space"));
}
out.push_str(r"\S*");
}
Item::Zone(Zone::Numeric) => {
let _ = write!(out, r"\s*{SIGN}{HOURS}[:\s]*[0-5][0-9]");
}
Item::Zone(Zone::Permissive) => {
if digit_next {
return Err(fail("a digit straight after %#z"));
}
let _ = write!(out, r"\s*(?:[Zz]|{SIGN}{HOURS}[:\s]*(?:[0-5][0-9])?)");
}
Item::DateTimeSeparator => out.push_str("[Tt ]"),
Item::RfcZone => {
let _ = write!(
out,
r"\s*(?:[Uu][Tt][Cc]|[Zz]|{SIGN}{HOURS}[:\s]*[0-5][0-9])"
);
}
}
i += 1;
}
Ok(out)
}
const fn numeric(number: Number, digit_next: bool) -> Option<&'static str> {
let (free, fixed) = match number {
Number::Month | Number::Hour12 => ("1[0-2]|0?[1-9]", "1[0-2]|0[1-9]"),
Number::Day => ("3[01]|[12][0-9]|0?[1-9]", "3[01]|[12][0-9]|0[1-9]"),
Number::Hour => ("2[0-3]|[01]?[0-9]", "2[0-3]|[01][0-9]"),
Number::Minute => ("[0-5]?[0-9]", "[0-5][0-9]"),
Number::Second => ("60|[0-5]?[0-9]", "60|[0-5][0-9]"),
Number::Ordinal => (
"36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0?[1-9][0-9]|0{0,2}[1-9]",
"36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]",
),
Number::WeekFromSun | Number::WeekFromMon => ("5[0-3]|[0-4]?[0-9]", "5[0-3]|[0-4][0-9]"),
Number::IsoWeek => ("5[0-3]|[1-4][0-9]|0?[1-9]", "5[0-3]|[1-4][0-9]|0[1-9]"),
Number::Quarter => ("[1-4]", "[1-4]"),
Number::DaysFromSun => ("[0-6]", "[0-6]"),
Number::WeekdayFromMon => ("[1-7]", "[1-7]"),
Number::YearDiv100 | Number::YearMod100 | Number::IsoYearMod100 => {
("[0-9]{1,2}", "[0-9]{2}")
}
Number::Year | Number::IsoYear => ("[+-]0*[0-9]{1,4}|[0-9]{1,4}", "[0-9]{4}"),
Number::Nanosecond => ("[0-9]{1,9}", "[0-9]{9}"),
Number::Timestamp => {
if digit_next {
return None;
}
return Some("0*[0-9]{1,11}");
}
};
Some(if digit_next { fixed } else { free })
}
fn folded(word: &str) -> String {
word.chars()
.flat_map(|c| ['[', c.to_ascii_uppercase(), c, ']'])
.collect()
}
fn names(name: Name) -> String {
let (short, ends): (&[&str], &[&str]) = match name {
Name::ShortMonth | Name::LongMonth => (&MONTHS, &MONTH_ENDS),
Name::ShortWeekday | Name::LongWeekday => (&WEEKDAYS, &WEEKDAY_ENDS),
};
let long = matches!(name, Name::LongMonth | Name::LongWeekday);
let mut out = String::from("(?:");
for (n, (word, end)) in short.iter().zip(ends).enumerate() {
if n > 0 {
out.push('|');
}
out.push_str(&folded(word));
if long && !end.is_empty() {
let _ = write!(out, "(?:{})?", folded(end));
}
}
out.push(')');
out
}
fn digit_next_after(rest: &[Item]) -> bool {
digit_next(rest.get(1..).unwrap_or_default())
}
fn digit_next(rest: &[Item]) -> bool {
for item in rest {
match item {
Item::Literal(text) => return text.starts_with(|c: char| c.is_ascii_digit()),
Item::Number(_) | Item::Fraction(_) | Item::ZoneName => return true,
Item::Space | Item::DotFraction(_) => {}
_ => return false,
}
}
false
}
#[cfg(test)]
mod tests {
use chrono::format::{Parsed, StrftimeItems, parse};
use chrono::{DateTime, FixedOffset};
use proptest::prelude::ProptestConfig;
use proptest::string::string_regex;
use super::*;
const FORMATS: &[&str] = &[
"%Y-%m-%dT%H:%M:%S%.f%:z",
"%Y-%m-%d %H:%M:%S.%3f %#z",
"%d/%b/%Y:%H:%M:%S %z",
"%a, %d %b %Y %H:%M:%S %z",
"%A, %B %e, %Y %l:%M %P",
"%a %b %e %T %Y",
"%Y%m%d%H%M%S",
"%y%m%d %H%M",
"%Y-%j",
"%G-W%V-%u",
"%Y %U %w",
"%F %T%.f",
"%s%.3f",
"%H:%M:%S.%f",
"%+",
"%c",
"%D %r",
"%v",
"%q %Y",
"%FT%T%.9fZ %Z",
];
fn whole(format: &str) -> regex::Regex {
let re = chrono_date_pattern(format).unwrap();
regex::Regex::new(&format!("^(?:{re})$")).unwrap()
}
#[test]
fn a_directive_with_no_matcher_is_refused() {
for format in [
"%Q", "%s%H", "%.f%S", "%#z%H", "%Z%H", "%Y-%", "%5Y", "%s%3f", "%.f%3f",
] {
assert!(
matches!(chrono_date_pattern(format), Err(GrokError::Date(_))),
"{format} built"
);
}
}
#[test]
fn chrono_reads_every_match() {
for format in FORMATS {
let re = chrono_date_pattern(format).unwrap();
proptest::proptest!(ProptestConfig::with_cases(256), |(text in string_regex(&re).unwrap())| {
let mut parsed = Parsed::new();
let read = parse(&mut parsed, &text, StrftimeItems::new(format));
proptest::prop_assert!(read.is_ok(), "{} matched {:?}, which chrono refuses: {:?}", format, text, read);
});
}
}
#[test]
fn the_regex_matches_what_chrono_writes() {
for format in FORMATS {
let re = whole(format);
for k in 0..400_i64 {
let secs = k * 4_000_000;
let nanos = u32::try_from((k * 7_919_123) % 1_000_000_000).unwrap();
let offset = i32::try_from(((k * 37) % 95 - 47) * 15 * 60).unwrap();
let text = DateTime::from_timestamp(secs, nanos)
.unwrap()
.with_timezone(&FixedOffset::east_opt(offset).unwrap())
.format(&format.replace("%#z", "%z"))
.to_string();
assert!(re.is_match(&text), "{format} missed {text:?}");
}
}
}
}