lib/DateTime/Format/Genealogy.pm

Structural Coverage (Approximate)

TER1 (Statement): 98.63%
TER2 (Branch): 94.44%
TER3 (LCSAJ): 100.0% (8/8)
Approximate LCSAJ segments: 91

LCSAJ Legend

โ— Covered โ€” this LCSAJ path was executed during testing.

โ— Not covered โ€” this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start โ†’ end โ†’ jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    1: package DateTime::Format::Genealogy;
    2: 
    3: # Author Nigel Horne: njh@nigelhorne.com
    4: # Copyright (C) 2018-2026, Nigel Horne
    5: 
    6: # Usage is subject to licence terms.
    7: 
    8: use strict;
    9: use warnings;
   10: use autodie qw(:all);
   11: use 5.010;
   12: 
   13: # Sub::Private in 'enforce' mode makes calling private subs from outside the
   14: # package a runtime error.  HARNESS_ACTIVE (set by prove/make test) or
   15: # $Sub::Private::BYPASS suppress enforcement so white-box tests can still
   16: # reach private helpers directly.
   17: BEGIN { $Sub::Private::config{mode} = 'enforce' }
   18: use Sub::Private;
   19: use Sub::Protected;
   20: 
   21: # Explicit () -- we use Carp::carp / Carp::croak throughout; importing the
   22: # short names into the namespace only to have namespace::clean remove them
   23: # is unnecessary noise.
   24: use Carp ();
   25: use DateTime::Format::Natural;
   26: use Genealogy::Gedcom::Date 2.01;
   27: use Object::Configure 0.23;
   28: use Params::Get 0.15;
   29: use Params::Validate::Strict qw(validate_strict);
   30: use Readonly;
   31: use Readonly::Values::Months 0.02 qw(@short_month_names);
   32: use Scalar::Util ();
   33: 
   34: # namespace::clean placed last so the import list above is self-documenting:
   35: # every 'use' that precedes it has its imported symbols removed from the
   36: # public namespace at the end of compilation.
   37: use namespace::clean;
   38: 
   39: # ---------------------------------------------------------------------------
   40: # Compile-time constants
   41: # ---------------------------------------------------------------------------
   42: 
   43: # Map non-standard (long, abbreviated, or French/German) month names to the
   44: # 3-letter GEDCOM abbreviation.  Not exported; callers must use parse_datetime.
   45: Readonly my %MONTH_ALIAS => (
   46: 	'January'   => 'Jan',
   47: 	'February'  => 'Feb',
   48: 	'March'     => 'Mar',
   49: 	'April'     => 'Apr',
   50: 	'June'      => 'Jun',
   51: 	'July'      => 'Jul',
   52: 	'August'    => 'Aug',
   53: 	'September' => 'Sep',
   54: 	'October'   => 'Oct',
   55: 	'November'  => 'Nov',
   56: 	'December'  => 'Dec',
   57: 	# Common non-standard abbreviations for September
   58: 	'Sept'      => 'Sep',
   59: 	# French and German month variants found in real genealogical trees.
   60: 	# 'Janv' = French abbreviation for janvier (January).
   61: 	# 'Juli' = German July / occasional French variant.
   62: 	# 'Mai'  = French for May (3 letters, handled here to avoid a separate branch).
   63: 	'Janv'      => 'Jan',
   64: 	'Juli'      => 'Jul',
   65: 	'Mai'       => 'May',
   66: );
   67: 
   68: # Julian-to-Gregorian day offset tiers.  Each pair is [boundary_year, offset].
   69: # The gap widened by 1 day at each century mark after 1582:
   70: #   10 days: 5 Oct 1582 to 28 Feb 1700
   71: #   11 days: 1 Mar 1700 to 28 Feb 1800
   72: #   12 days: 1 Mar 1800 to 28 Feb 1900
   73: #   13 days: 1 Mar 1900 onwards (catch-all, coded as literal 13 in the helper)
   74: Readonly my @JULIAN_OFFSET_TIERS => ([1700, 10], [1800, 11], [1900, 12]);
   75: 
   76: # Maximum unique date strings cached per object before the cache is discarded.
   77: # Prevents adversarial callers from exhausting process memory by feeding an
   78: # unbounded stream of unique-but-invalid strings to parse_datetime.
   79: Readonly my $MAX_CACHE_SIZE => 10_000;
   80: 
   81: # Legitimate recursion depth for parse_datetime is exactly 1: a range ("bet X
   82: # and Y") calls itself once for each half.  Anything deeper means either a
   83: # mutant or a malformed string that tricks the range regex into re-matching its
   84: # own output.  The limit is generous so valid edge cases never trip it.
   85: Readonly my $MAX_PARSE_DEPTH => 10;
   86: our $_parse_depth = 0;
   87: 
   88: # Accepted parameter schema for parse_datetime, used by Params::Validate::Strict
   89: # to reject unknown keys (typos, stale callers) at runtime.
   90: Readonly my %PARSE_DATETIME_SCHEMA => (
   91: 	date   => { type => 'scalar', optional => 1 },
   92: 	quiet  => { type => 'scalar', optional => 1 },
   93: 	strict => { type => 'scalar', optional => 1 },
   94: );
   95: 
   96: =head1 NAME
   97: 
   98: DateTime::Format::Genealogy - Create a DateTime object from a genealogy date string
   99: 
  100: =head1 VERSION
  101: 
  102: Version 0.13
  103: 
  104: =cut
  105: 
  106: our $VERSION = '0.13';
  107: 
  108: =head1 SYNOPSIS
  109: 
  110: C<DateTime::Format::Genealogy> is a Perl module designed to parse genealogy-style
  111: date strings (primarily GEDCOM format) and convert them into L<DateTime> objects.
  112: It wraps L<Genealogy::Gedcom::Date> and L<DateTime::Format::Natural>, adds GEDCOM
  113: calendar-escape handling, and accepts common non-standard month names found in
  114: exported genealogical trees.
  115: 
  116:     use DateTime::Format::Genealogy;
  117:     my $dtg = DateTime::Format::Genealogy->new();
  118:     my $dt  = $dtg->parse_datetime('25 Dec 2022');
  119:     print $dt->dmy;  # 25-12-2022
  120: 
  121: =head1 SUBROUTINES/METHODS
  122: 
  123: =head2 new
  124: 
  125: Creates or clones a C<DateTime::Format::Genealogy> object.
  126: 
  127: =head3 EXAMPLE
  128: 
  129:     # Bare construction
  130:     my $dtg = DateTime::Format::Genealogy->new();
  131: 
  132:     # Construction with flags stored on the object
  133:     my $dtg_quiet = DateTime::Format::Genealogy->new(quiet => 1, strict => 1);
  134: 
  135:     # Clone with an override (inherits quiet => 1, overrides strict)
  136:     my $clone = $dtg_quiet->new(strict => 0);
  137: 
  138: =head3 API SPECIFICATION
  139: 
  140:     # Input (hash or hashref, all keys optional):
  141:     {
  142:         quiet  => $bool,  # suppress carp in internal helpers
  143:         strict => $bool,  # enforce 3-letter GEDCOM month abbreviations
  144:         # Any extra keys from Object::Configure are also accepted.
  145:     }
  146: 
  147:     # Output: blessed DateTime::Format::Genealogy object
  148: 
  149: =head3 MESSAGES
  150: 
  151: This method does not emit any diagnostics directly.
  152: 
  153: =head3 PSEUDOCODE
  154: 
  155:     FUNCTION new(class, *args):
  156:       params = get_params(undef, args)
  157:       IF class is not defined:
  158:         class = __PACKAGE__
  159:       ELSE IF class is already an object (blessed):
  160:         RETURN bless( merge(class.attrs, params), ref(class) )
  161:       params = configure(class, params)   # merge any config-file settings
  162:       RETURN bless(params, class)
  163:     END FUNCTION
  164: 
  165: =cut
  166: 
  167: sub new
  168: {
โ—169 โ†’ 173 โ†’ 182  169: 	my $class = shift;
  170: 
  171: 	my $params = Params::Get::get_params(undef, \@_);
  172: 
  173: 	if(!defined($class)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

174: # Called as DateTime::Format::Genealogy::new() with no invocant; 175: # default to the package name so bless still works. 176: $class = __PACKAGE__; 177: } elsif(Scalar::Util::blessed($class)) { 178: # Invocant is an existing object: clone it and overlay any new params. 179: return bless { %{$class}, ($params ? %{$params} : ()) }, ref($class);

Mutants (Total: 2, Killed: 2, Survived: 0)

180: } 181: 182: return bless Object::Configure::configure($class, $params), $class;

Mutants (Total: 2, Killed: 2, Survived: 0)

183: } 184: 185: =head2 parse_datetime 186: 187: Parses a genealogy-style date string and returns a L<DateTime> object. 188: 189: Recognises GEDCOM calendar escapes (C<@#DJULIAN@>, C<@#DHEBREW@>, 190: C<@#DFRENCH R@>) and converts them via the appropriate calendar module when 191: available. 192: 193: Can be called as a class method, an object method, or a bare function. 194: 195: Returns: 196: 197: =over 4 198: 199: =item * 200: 201: A single L<DateTime> object for exact, parseable dates. 202: 203: =item * 204: 205: A two-element list of L<DateTime> objects in I<list> context when the date 206: string is a range (C<bet X and Y> / C<from X to Y>). 207: 208: =item * 209: 210: C<undef> (scalar) or the empty list (list context) when the date cannot be 211: parsed, is a year-only string, is prefixed with an approximation keyword 212: (C<bef>, C<aft>, C<abt>), or represents a date before AD 100. 213: 214: =back 215: 216: Mandatory argument: 217: 218: =over 4 219: 220: =item * C<date> 221: 222: The date string to parse. 223: 224: =back 225: 226: Optional arguments (may be set at construction time and/or overridden 227: per-call; per-call values take precedence): 228: 229: =over 4 230: 231: =item * C<quiet> 232: 233: Suppress L<Carp> warnings on unparseable or approximate dates. 234: 235: =item * C<strict> 236: 237: Enforce the GEDCOM standard: only 3-letter month abbreviations (C<Jan>, 238: C<Feb>, ...) are accepted. Long English names and French/German variants 239: are rejected. 240: 241: =back 242: 243: =head3 EXAMPLE 244: 245: my $dtg = DateTime::Format::Genealogy->new(); 246: 247: # Simple exact date 248: my $dt = $dtg->parse_datetime('25 Dec 2022'); 249: print $dt->dmy; # 25-12-2022 250: 251: # Date range (list context) 252: my ($start, $end) = $dtg->parse_datetime('bet 1 Sep 1939 and 2 Sep 1945'); 253: 254: # GEDCOM calendar escape 255: my $julian = $dtg->parse_datetime('@#DJULIAN@ 15 Mar 1620'); 256: 257: # Class-method form (no constructor required) 258: my $dt2 = DateTime::Format::Genealogy->parse_datetime('1 Jan 2000'); 259: 260: # Long month name (non-strict only) 261: my $dt3 = $dtg->parse_datetime('12 June 2020'); 262: 263: # French month variant (non-strict only) 264: my $dt4 = $dtg->parse_datetime('21 Mai 1681'); 265: 266: =head3 API SPECIFICATION 267: 268: # Input (hash or hashref): 269: { 270: date => $string, # required (non-ref, non-empty) 271: quiet => $bool, # optional; falls back to $self->{'quiet'} 272: strict => $bool, # optional; falls back to $self->{'strict'} 273: } 274: 275: # Return values: 276: # DateTime exact parseable date 277: # (DateTime, DateTime) date range (list context only) 278: # undef / () unparseable, approximate, or year-only 279: 280: =head3 MESSAGES 281: 282: =over 4 283: 284: =item C<< Usage: DateTime::Format::Genealogy::parse_datetime(date => $date) >> 285: 286: Thrown (croak) when no arguments are supplied or when the C<date> value is 287: undef or a reference. 288: 289: =item C<< Invalid parse_datetime parameters: ... >> 290: 291: Thrown (croak) when an unknown parameter key is passed (e.g. a typo). 292: 293: =item C<< $date is invalid, need an exact date to create a DateTime >> 294: 295: Warned (carp) when the date begins with an approximation prefix (C<bef>, 296: C<aft>, C<abt>). Silenced by C<quiet>. 297: 298: =item C<< $date is invalid, there are only 30 days in November >> 299: 300: Warned (carp) for the impossible date C<31 Nov>. Always emitted; not 301: silenced by C<quiet>. 302: 303: =item C<< Changing date '$original' to '$new' >> 304: 305: Warned (carp) when a date is automatically rewritten (ISO dash format or 306: dash-separated range). Silenced by C<quiet>. 307: 308: =item C<< Unparseable date $date - often because the month name isn't 3 letters >> 309: 310: Warned (carp) in strict mode for non-3-letter months, or in non-strict mode 311: for unrecognised long month names. Silenced by C<quiet>. 312: 313: =item C<< $dfn_error_string >> 314: 315: Warned (carp) when L<DateTime::Format::Natural> rejects the date string. 316: Silenced by C<quiet>. 317: 318: =item C<< Hebrew calendar conversion failed: ... >> 319: 320: Warned (carp) when L<DateTime::Calendar::Hebrew> is unavailable or throws. 321: Silenced by C<quiet>. 322: 323: =item C<< French Republican calendar conversion failed: ... >> 324: 325: Warned (carp) when L<DateTime::Calendar::FrenchRevolutionary> is unavailable 326: or throws. Silenced by C<quiet>. 327: 328: =item C<< Calendar type $type not supported >> 329: 330: Warned (carp) for GEDCOM calendar escapes other than GREGORIAN, JULIAN, 331: HEBREW, and FRENCH R. Silenced by C<quiet>. 332: 333: =back 334: 335: =head3 PSEUDOCODE 336: 337: FUNCTION parse_datetime(self, *args): 338: -- Dispatch class/function/hash-invocant calls to an object instance 339: IF self is not a reference: 340: RETURN new()->parse_datetime(args or self) 341: IF ref(self) == 'HASH': 342: RETURN new()->parse_datetime(self) 343: 344: ABORT unless args non-empty 345: params = get_params('date', args) 346: ABORT on unknown keys (validate_strict) 347: 348: date = params.date 349: quiet = params.quiet // self.quiet 350: strict = params.strict // self.strict 351: 352: ABORT unless date is defined, non-empty, and not a reference 353: 354: -- Strip GEDCOM calendar escape if present 355: IF date =~ s/^@#D([A-Z ]+?)@\s*//: calendar_type = 'D' + uc(match) 356: 357: -- Reject approximate/relative dates 358: IF date =~ /^(bef|aft|abt)\s/i: CARP and RETURN undef 359: 360: -- Reject calendar impossibilities 361: IF date =~ /^31\s+Nov/: CARP and RETURN undef 362: 363: -- Rewrite dash-separated ranges and ISO dates 364: IF date =~ /X - Y/: 365: IF date =~ /YYYY-MM-DD/: REFORMAT to "DD Mon YYYY" (carp) 366: ELSE: REFORMAT to "bet X and Y" (carp) 367: 368: -- Dispatch ranges to recursive calls 369: IF date =~ /^bet X and Y/i: 370: RETURN (parse_datetime(X), parse_datetime(Y)) IF wantarray 371: RETURN undef 372: 373: IF !strict AND date =~ /^from X to Y/i: 374: RETURN (parse_datetime(X), parse_datetime(Y)) IF wantarray 375: RETURN undef 376: 377: -- Normalise non-standard month names (non-strict mode only) 378: IF !strict: 379: IF date =~ DD + Aout + YYYY (French non-ASCII August): 380: REWRITE month to 'Aug' 381: ELSE IF date =~ /DD LONG_OR_VARIANT YYYY/: 382: lookup = MONTH_ALIAS{ucfirst(lc(month))} 383: IF lookup: REWRITE month to lookup 384: ELSE IF month is more than 3 letters: CARP and RETURN undef 385: -- 3-letter unknown months fall through unchanged to the parser 386: 387: -- Parse with Genealogy::Gedcom::Date (cached) then DateTime::Format::Natural 388: IF date starts with digit: 389: d = _date_parser_cached(date) 390: IF d defined: 391: RETURN undef if date ends with year-only (< AD100 guard) 392: rc = DateTime::Format::Natural->parse_datetime(d.canonical) 393: IF calendar_type != DGREGORIAN: 394: rc = _convert_calendar(rc, calendar_type, quiet) 395: RETURN rc 396: 397: -- Fallback: try DateTime::Format::Natural directly on the raw string 398: IF date not ~= /^(Abt|ca?)/i AND date =~ /^[\w\s,]+$/: 399: rc = DateTime::Format::Natural->parse_datetime(date) 400: IF rc AND success: RETURN rc 401: ELSE: CARP error 402: 403: RETURN undef 404: END FUNCTION 405: 406: =cut 407: 408: sub parse_datetime 409: { 410: # Guard against unbounded recursion at every entry point, including the 411: # class-method normalisation branches below. 'local' restores the counter 412: # automatically on any return path. Legitimate use bottoms out at depth 1 413: # (range-split recursive call); anything deeper is a mutant or a bug. โ—414 โ†’ 420 โ†’ 430 414: local $_parse_depth = $_parse_depth + 1; 415: return if $_parse_depth > $MAX_PARSE_DEPTH;

Mutants (Total: 3, Killed: 3, Survived: 0)

416: 417: my $self = shift; 418: 419: # Normalise class-method and bare-function call styles into an object call. 420: if(!ref($self)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

421: if(@_) {

Mutants (Total: 1, Killed: 1, Survived: 0)

422: return(__PACKAGE__->new()->parse_datetime(@_)); 423: } 424: return(__PACKAGE__->new()->parse_datetime($self)); 425: } elsif(ref($self) eq 'HASH') { 426: return(__PACKAGE__->new()->parse_datetime($self)); 427: } 428: 429: # Guard before Params::Get so *our* croak message is what Test::Carp sees. โ—430 โ†’ 445 โ†’ 603 430: Carp::croak('Usage: ', __PACKAGE__, '::parse_datetime(date => $date)') unless @_; 431: 432: my $params = Params::Get::get_params('date', @_); 433: 434: # Catch unknown parameter keys early so callers get a clear error rather 435: # than silent misbehaviour from a typo like 'quet' instead of 'quiet'. 436: # validate_strict uses a compile-time-imported croak, so we wrap in eval 437: # and re-throw via Carp::croak (which IS interceptable by Test::Carp). 438: # Capture $@ into a lexical immediately: a DESTROY method firing between 439: # the eval and the check would otherwise silently clear the global $@. 440: my $validate_err; 441: eval { validate_strict(schema => \%PARSE_DATETIME_SCHEMA, input => $params); 1 } 442: or $validate_err = $@; 443: Carp::croak("Invalid parse_datetime parameters: $validate_err") if $validate_err; 444: 445: if((!ref($params->{'date'})) && (my $date = $params->{'date'})) {

Mutants (Total: 1, Killed: 1, Survived: 0)

446: # Per-call flags shadow object-level defaults, enabling per-call overrides 447: # without losing the convenience of constructor-level configuration. 448: my $quiet = $params->{'quiet'} // $self->{'quiet'}; 449: my $strict = $params->{'strict'} // $self->{'strict'}; 450: 451: # Detect and strip any GEDCOM calendar escape at the front of the string. 452: # Pattern: @#D<NAME>@ where NAME is uppercase letters/spaces (lazy match 453: # so it stops at the first closing '@' rather than a later one). 454: my $calendar_type = 'DGREGORIAN'; 455: if($date =~ s/^@#D([A-Z ]+?)@\s*//) {

Mutants (Total: 1, Killed: 1, Survived: 0)

456: $calendar_type = 'D' . uc($1); 457: } 458: 459: # Approximate-date prefixes (bef/aft/abt) signal "no exact date known", 460: # so a DateTime object would be misleading. 461: if($date =~ /^(?:bef|aft|abt)\s/i) {

Mutants (Total: 1, Killed: 1, Survived: 0)

462: Carp::carp(_safe_str($date) . ' is invalid, need an exact date to create a DateTime') 463: unless($quiet); 464: return; 465: } 466: 467: # 31 November does not exist; catch it before any parser attempt. 468: if($date =~ /^31\s+Nov/) {

Mutants (Total: 1, Killed: 1, Survived: 0)

469: Carp::carp(_safe_str($date) . ' is invalid, there are only 30 days in November'); 470: return; 471: } 472: 473: # Rewrite dash-separated constructs. 474: # ISO "YYYY-MM-DD" is checked first -- the pattern is fully anchored with 475: # fixed-width fields so there is zero backtracking. 476: # A spaced range "X - Y" (spaces required on both sides of the hyphen) 477: # is converted to "bet X and Y". The \s+ discriminator ensures that a 478: # bare ISO date (no spaces around the hyphen) never matches this branch, 479: # eliminating the need for a combined pre-filter. 480: if($date =~ /^(\d{4})-(\d{2})-(\d{2})$/) {

Mutants (Total: 1, Killed: 1, Survived: 0)

481: my ($y, $m, $d) = ($1, $2, $3); 482: my $month_idx = $m - 1; 483: # @short_month_names is a 12-element array (indices 0-11). 484: # Month 00 would yield index -1 (wrapping silently to Dec in Perl). 485: # Month 13-99 yields undef and a runtime warning. Reject both. 486: if($month_idx < 0 || $month_idx > 11) {

Mutants (Total: 7, Killed: 7, Survived: 0)

487: Carp::carp("Invalid month '$m' in date '$date'") unless $quiet; 488: return; 489: } 490: my $month = ucfirst($short_month_names[$month_idx]); 491: my $rewritten = "$d $month $y"; 492: Carp::carp("Changing date '" . _safe_str($date) . "' to '$rewritten'") unless($quiet); 493: $date = $rewritten; 494: } elsif($date =~ /^(.+\d)\s+-\s+(.+\d)$/) { 495: my ($lhs, $rhs) = ($1, $2); 496: Carp::carp("Changing date '" . _safe_str($date) . "' to 'bet $lhs and $rhs'") unless($quiet); 497: $date = "bet $lhs and $rhs"; 498: } 499: 500: # Date ranges return two DateTimes in list context; undef in scalar. 501: # Lazy .+? on the first group ensures we split at the FIRST "and"/"to" 502: # keyword, not the last, which matters when a sub-date contains the word. 503: if($date =~ /^bet (.+?) and (.+)/i) {

Mutants (Total: 1, Killed: 1, Survived: 0)

504: if(wantarray) {

Mutants (Total: 1, Killed: 1, Survived: 0)

505: return $self->parse_datetime($1), $self->parse_datetime($2);

Mutants (Total: 2, Killed: 2, Survived: 0)

506: } 507: return; 508: } 509: 510: if((!$strict) && ($date =~ /^from (.+?) to (.+)/i)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

511: if(wantarray) {

Mutants (Total: 1, Killed: 1, Survived: 0)

512: return $self->parse_datetime($1), $self->parse_datetime($2);

Mutants (Total: 2, Killed: 2, Survived: 0)

513: } 514: return; 515: } 516: 517: if($date !~ /^\d{3,4}$/) {

Mutants (Total: 1, Killed: 1, Survived: 0)

518: # Strict mode: only 3-letter GEDCOM abbreviations are valid. 519: if($strict) {

Mutants (Total: 1, Killed: 1, Survived: 0)

520: if($date !~ /^\d{1,2}\s+[A-Z]{3}\s+\d{3,4}$/i) {

Mutants (Total: 1, Killed: 1, Survived: 0)

521: Carp::carp('Unparseable date ' . _safe_str($date) . " - often because the month name isn't 3 letters") unless($quiet); 522: return; 523: } 524: } else { 525: # Aout with circumflex-u (Ao\x{FB}t) must be matched explicitly 526: # because the standard \w character class is ASCII-only and will 527: # not match the non-ASCII 'u with circumflex'. 528: if($date =~ /^(\d{1,2})\s+Ao\x{FB}t\s+(\d{3,4})$/i) {

Mutants (Total: 1, Killed: 1, Survived: 0)

529: $date = "$1 Aug $2"; 530: } elsif($date =~ /^(\d{1,2})\s+([A-Z]{3,}+)\.?\s+(\d{3,4})$/i) { 531: # Look up the month in the alias table. 532: # Unknown 3-letter tokens are passed through unchanged so that 533: # standard GEDCOM abbreviations (Sep, Dec, ...) that did not 534: # trigger the earlier cache path still reach the parser. 535: if(my $abbrev = $MONTH_ALIAS{ucfirst(lc($2))}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

536: $date = "$1 $abbrev $3"; 537: } elsif(length($2) > 3) {

Mutants (Total: 3, Killed: 3, Survived: 0)

538: # Longer-than-3-letter names not in the alias table are 539: # truly unrecognised; there is nothing useful we can do. 540: Carp::carp('Unparseable date ' . _safe_str($date) . " - often because the month name isn't 3 letters") unless($quiet); 541: return; 542: } 543: } elsif($date =~ /^(\d{1,2})\-([A-Z]{3})\-(\d{3,4})$/i) { 544: # Accept the 29-Aug-1938 dash-separated single-date format. 545: $date = "$1 $2 $3"; 546: } 547: } 548: 549: # Lazily initialise DateTime::Format::Natural on first use. 550: my $dfn = $self->{'dfn'} //= DateTime::Format::Natural->new(); 551: 552: if(($date =~ /^\d/) && (my $d = $self->_date_parser_cached($date))) {

Mutants (Total: 1, Killed: 1, Survived: 0)

553: # DateTime::Format::Natural cannot handle dates before AD 100; 554: # a date ending in a 1-or-2-digit year is that old. 555: return if($date =~ /\s\d{1,2}$/); 556: 557: # Guard against a malformed GGD result with an undef canonical 558: # field; passing undef to DFN causes a Params::Validate croak. 559: return unless defined $d->{'canonical'}; 560: 561: my $rc = $dfn->parse_datetime($d->{'canonical'}); 562: 563: # DFN silently returns today's date when it cannot parse the 564: # canonical string (e.g. 3-digit years 100-999, very large 565: # years). We must check success() here just as we do in the 566: # DFN fallback path below, otherwise the caller receives a 567: # completely wrong DateTime. 568: unless($dfn->success) {

Mutants (Total: 1, Killed: 1, Survived: 0)

569: Carp::carp($dfn->error) unless $quiet; 570: return; 571: } 572: 573: if($rc && $calendar_type ne 'DGREGORIAN') {

Mutants (Total: 1, Killed: 1, Survived: 0)

574: return _convert_calendar($rc, $calendar_type, $quiet);

Mutants (Total: 2, Killed: 2, Survived: 0)

575: } 576: 577: return $rc;

Mutants (Total: 2, Killed: 2, Survived: 0)

578: } 579: 580: # Last resort: try DateTime::Format::Natural on the raw string. 581: # Approximate-prefix forms are excluded here because they already 582: # returned undef above; the pattern here guards against 'Abt'/'ca' 583: # leaking through when quiet is enabled (e.g. "Abt1Jan2000" has no 584: # space so it was not caught by the /^abt\s/i check above). 585: if(($date !~ /^(?:Abt|ca?)/i) && ($date =~ /^[\w\s,]+$/)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

586: if(my $rc = $dfn->parse_datetime($date)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

587: if($dfn->success()) {

Mutants (Total: 1, Killed: 1, Survived: 0)

588: return $rc;

Mutants (Total: 2, Killed: 2, Survived: 0)

589: } 590: Carp::carp($dfn->error()) unless($quiet); 591: } 592: # NOTE: DateTime::Format::Natural->parse_datetime always returns 593: # a DateTime object (today's date on failure), never undef. The 594: # else branch that would carp "Can't parse date" is therefore 595: # dead code and has been removed. If a future DFN version can 596: # return undef, this else must be reinstated: 597: # else { Carp::carp("Can't parse date '$date'") unless $quiet } 598: } 599: } 600: return; 601: } 602: 603: Carp::croak('Usage: ', __PACKAGE__, '::parse_datetime(date => $date)'); 604: } 605: 606: # --------------------------------------------------------------------------- 607: # _date_parser_cached 608: # 609: # Purpose: Wrap Genealogy::Gedcom::Date->parse() with a per-object 610: # memoisation layer to avoid re-parsing identical strings. 611: # Entry: $self - blessed object (must carry ->{'date_parser'} slot) 612: # $date - non-empty, non-undef date string (positional) 613: # Exit: Hashref on success ({canonical, day, month, year, ...}), 614: # undef on parse failure or error. 615: # Side Effects: Populates $self->{'all_dates'}{$date} on BOTH success and 616: # failure. Failure is stored as undef so repeated lookups of 617: # the same invalid string are O(1) and carp fires only once. 618: # Carps on parser error unless $self->{'quiet'} is set. 619: # --------------------------------------------------------------------------- 620: 621: sub _date_parser_cached :Protected 622: { 623: # Accept the date as a plain positional arg -- this is a hot-path internal 624: # method called only from parse_datetime. Routing through Params::Get adds 625: # measurable dispatch overhead for no external-API benefit. โ—626 โ†’ 633 โ†’ 639 626: my ($self, $date) = @_; 627: 628: Carp::croak('Usage: _date_parser_cached($date)') unless defined $date; 629: 630: # Evict the whole cache when it reaches the size limit. A full clear is 631: # used instead of LRU because genealogy datasets have bounded unique-date 632: # counts in normal use; LRU overhead is not justified. 633: if(defined($self->{'all_dates'}) && scalar(keys %{$self->{'all_dates'}}) >= $MAX_CACHE_SIZE) {

Mutants (Total: 4, Killed: 1, Survived: 3)
634: $self->{'all_dates'} = {}; 635: } 636: 637: # Short-circuit on any prior result (success OR cached failure). 638: # 'exists' correctly handles undef values stored for invalid dates. โ—639 โ†’ 648 โ†’ 655 639: return $self->{'all_dates'}{$date} if exists $self->{'all_dates'}{$date};

Mutants (Total: 2, Killed: 2, Survived: 0)

640: 641: my $date_parser = $self->{'date_parser'} //= Genealogy::Gedcom::Date->new(); 642: 643: my $parsed_date; 644: eval { 645: $parsed_date = $date_parser->parse(date => $date); 646: }; 647: 648: if(my $error = $date_parser->error()) {

Mutants (Total: 1, Killed: 1, Survived: 0)

649: Carp::carp(_safe_str($date) . ": '$error'") unless $self->{'quiet'}; 650: # Cache the failure so subsequent calls for the same string skip GGD 651: # entirely and do not carp again. 652: return ($self->{'all_dates'}{$date} = undef); 653: } 654: โ—655 โ†’ 655 โ†’ 660 655: if((ref($parsed_date) eq 'ARRAY') && @{$parsed_date}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

656: return $self->{'all_dates'}{$date} = $parsed_date->[0];

Mutants (Total: 2, Killed: 2, Survived: 0)

657: } 658: 659: # Empty or unexpected result -- also cache to prevent repeated GGD calls. 660: return ($self->{'all_dates'}{$date} = undef); 661: } 662: 663: # --------------------------------------------------------------------------- 664: # _convert_calendar 665: # 666: # Purpose: Convert a Gregorian DateTime produced by 667: # Genealogy::Gedcom::Date/DateTime::Format::Natural to the 668: # calendar indicated by the GEDCOM escape that preceded the date. 669: # Entry: $dt - DateTime object in Gregorian coordinates 670: # $calendar_type - normalised escape string (e.g. 'DJULIAN') 671: # $quiet - truthy to suppress carp on failure 672: # Exit: Converted DateTime, or the original $dt for unknown types. 673: # Side Effects: May carp on conversion failure (unless $quiet). 674: # --------------------------------------------------------------------------- 675: 676: sub _convert_calendar :Private 677: { โ—678 โ†’ 680 โ†’ 729 678: my ($dt, $calendar_type, $quiet) = @_; 679: 680: if($calendar_type eq 'DJULIAN') {

Mutants (Total: 1, Killed: 1, Survived: 0)

681: # Add the historical Julian-to-Gregorian day offset. 682: my $offset_days = _julian_to_gregorian_offset($dt->year); 683: return $dt->clone->add(days => $offset_days);

Mutants (Total: 2, Killed: 2, Survived: 0)

684: } elsif($calendar_type eq 'DHEBREW') { 685: # "return" inside eval{} exits the eval block, NOT the enclosing sub, 686: # so we capture the result in $result and return it afterwards. 687: # $@ is captured into a lexical immediately after the eval to prevent 688: # a DESTROY method from clearing the global before we can read it. 689: my $result; 690: my $convert_err; 691: eval { 692: require DateTime::Calendar::Hebrew; 693: my $h = DateTime::Calendar::Hebrew->new( 694: year => $dt->year, 695: month => $dt->month, 696: day => $dt->day 697: ); 698: $result = DateTime->from_object(object => $h); 699: 1; 700: } or $convert_err = $@; 701: Carp::carp("Hebrew calendar conversion failed: $convert_err") 702: if $convert_err && !$quiet; 703: # Return the converted DateTime on success, undef on failure. 704: # The POD (LIMITATIONS) documents that undef is returned when the 705: # optional module is unavailable rather than passing back the 706: # unconverted Gregorian DateTime. 707: return $result;

Mutants (Total: 2, Killed: 2, Survived: 0)

708: } elsif($calendar_type eq 'DFRENCH R') { 709: my $result; 710: my $convert_err; 711: eval { 712: require DateTime::Calendar::FrenchRevolutionary; 713: my $f = DateTime::Calendar::FrenchRevolutionary->new( 714: year => $dt->year, 715: month => $dt->month, 716: day => $dt->day 717: ); 718: $result = DateTime->from_object(object => $f); 719: 1; 720: } or $convert_err = $@; 721: Carp::carp("French Republican calendar conversion failed: $convert_err") 722: if $convert_err && !$quiet; 723: return $result;

Mutants (Total: 2, Killed: 2, Survived: 0)

724: } else { 725: # DROMAN and any other future escape types are not yet supported. 726: Carp::carp("Calendar type $calendar_type not supported") unless $quiet; 727: } 728: 729: return $dt;

Mutants (Total: 2, Killed: 2, Survived: 0)

730: } 731: 732: # --------------------------------------------------------------------------- 733: # _safe_str 734: # 735: # Purpose: Sanitise a user-supplied string for inclusion in diagnostic 736: # messages (Carp::carp/croak). Removes ASCII control characters 737: # that could be used for log injection (fake log lines, ANSI 738: # escape sequences) and truncates to a safe display length. 739: # Entry: $s - string to sanitise (may be undef) 740: # $max - optional maximum length (default 120) 741: # Exit: Sanitised, length-bounded string safe for embedding in messages. 742: # --------------------------------------------------------------------------- 743: 744: sub _safe_str :Private 745: { 746: my ($s, $max) = @_; 747: return '(undef)' unless defined $s;

Mutants (Total: 2, Killed: 0, Survived: 2)
748: $max //= 120; 749: # Replace every ASCII control character (0x00-0x1F, 0x7F) with '?'. 750: # This neutralises CR/LF log injection and ANSI escape sequences. 751: (my $clean = $s) =~ s/[[:cntrl:]]/?/g; 752: return length($clean) <= $max ? $clean : substr($clean, 0, $max - 3) . '...';
Mutants (Total: 5, Killed: 2, Survived: 3)
753: } 754: 755: # --------------------------------------------------------------------------- 756: # _julian_to_gregorian_offset 757: # 758: # Purpose: Return the number of days to add to a Julian date to obtain 759: # the Gregorian equivalent, based on the year. 760: # Entry: $year - integer calendar year 761: # Exit: Integer day offset (10, 11, 12, or 13) 762: # --------------------------------------------------------------------------- 763: 764: sub _julian_to_gregorian_offset :Private 765: { โ—766 โ†’ 771 โ†’ 774 766: my $year = $_[0]; 767: 768: # Iterate once with early exit; avoids the temporary list that grep would 769: # build before we discard all but the first match. 770: # @JULIAN_OFFSET_TIERS is ordered ascending, so the first hit is correct. 771: for my $tier (@JULIAN_OFFSET_TIERS) { 772: return $tier->[1] if $year < $tier->[0];

Mutants (Total: 5, Killed: 5, Survived: 0)

773: } 774: return 13; # catch-all: 1 Mar 1900 onwards

Mutants (Total: 2, Killed: 2, Survived: 0)

775: } 776: 777: =head1 LIMITATIONS 778: 779: =over 4 780: 781: =item * 782: 783: Dates before AD 100 are rejected because L<DateTime::Format::Natural> cannot 784: parse them reliably (it returns today's date instead of an error). 785: 786: =item * 787: 788: The C<Aout> (French August with circumflex-u) entry in the month-alias table 789: uses a non-ASCII Unicode escape (C<\x{FB}>). The module file must be read as 790: UTF-8; this is satisfied by the standard C<perl -Ilib> invocation but may 791: require C<use utf8> or C<open ':encoding(UTF-8)'> in unusual environments. 792: 793: =item * 794: 795: Hebrew and French Republican calendar conversions require 796: L<DateTime::Calendar::Hebrew> and L<DateTime::Calendar::FrenchRevolutionary> 797: respectively. These are optional and not listed as hard dependencies. When 798: absent, the GEDCOM escape is silently discarded and undef is returned unless 799: the C<quiet> flag is off, in which case a carp is emitted. 800: 801: =item * 802: 803: L<Genealogy::Gedcom::Date> cannot parse native Hebrew or French Revolutionary 804: month names (e.g. C<Tishri>, C<Vendemiaire>). Only dates written in 805: Gregorian form with the C<@#DHEBREW@> escape are converted. 806: 807: =item * 808: 809: The C<quiet> and C<strict> flags may be set at construction time 810: (C<< ->new(quiet => 1) >>) and will be respected by all subsequent calls to 811: C<parse_datetime> unless overridden on a per-call basis. The per-call value 812: always takes precedence. 813: 814: =back 815: 816: =head1 AUTHOR 817: 818: Nigel Horne, C<< <njh at nigelhorne.com> >> 819: 820: =head1 BUGS 821: 822: Please report any bugs or feature requests to the author. 823: This module is provided as-is without any warranty. 824: 825: =head1 SEE ALSO 826: 827: =over 4 828: 829: =item * L<Genealogy::Gedcom::Date> 830: 831: =item * L<DateTime> 832: 833: =item * L<DateTime::Format::Natural> 834: 835: =item * L<Configure an Object at Runtime|Object::Configure> 836: 837: =item * L<Test Dashboard|https://nigelhorne.github.io/DateTime-Format-Genealogy/coverage/> 838: 839: =back 840: 841: =head1 SUPPORT 842: 843: You can find documentation for this module with the perldoc command. 844: 845: perldoc DateTime::Format::Genealogy 846: 847: =over 4 848: 849: =item * RT: CPAN's request tracker 850: 851: L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=DateTime-Format-Genealogy> 852: 853: =item * GitHub Issues 854: 855: L<https://github.com/nigelhorne/DateTime-Format-Genealogy/issues> 856: 857: =back 858: 859: =head1 FORMAL SPECIFICATION 860: 861: =head2 new 862: 863: State S ::= [ attrs : Name -> Value ] 864: 865: new(class, params) = bless(params U configure(class)) when !blessed(class) 866: new(obj, params) = bless(obj.attrs (+) params) when blessed(obj) 867: 868: where (+) denotes right-biased union (params values take precedence). 869: 870: =head2 parse_datetime 871: 872: Let D be the set of genealogical date strings and DT the co-domain of 873: L<DateTime> objects. 874: 875: parse_datetime : D -> DT | bot | (DT x DT) 876: 877: YearOnly ::= { s in D | s ~ /^\d{3,4}$/ } 878: Approx ::= { s in D | s ~ /^(bef|aft|abt)\s/i } 879: Ranges ::= { s in D | s ~ /^bet\s.+\sand\s.+/i 880: | s ~ /^from\s.+\sto\s.+/i } 881: 882: Pre: date != bot 883: 884: Post: 885: date in YearOnly => result = bot 886: date in Approx => result = bot (carp unless quiet) 887: date in Ranges /\ wantarray => result in DT x DT 888: date in Ranges /\ !wantarray => result = bot 889: date in Parseable \ 890: (YearOnly u Approx u Ranges) => result in DT 891: date not in Parseable => result = bot (carp unless quiet) 892: 893: =head1 LICENSE AND COPYRIGHT 894: 895: Copyright 2018-2026 Nigel Horne. 896: 897: Usage is subject to the GPL2 licence terms. 898: If you use it, 899: please let me know. 900: 901: =cut 902: 903: 1;