Class: Tuile::Locale
- Inherits:
-
Object
- Object
- Tuile::Locale
- Defined in:
- lib/tuile/locale.rb,
sig/tuile.rbs
Overview
The formatting conventions of the person on the other end — a frozen value type held by Screen#locale, seeded at construction from Locale.system:
Screen.instance.locale.date_formats # => ["%Y-%m-%d"]
Screen.instance.locale = Locale::ISO.with(decimal_separator: ",")
It holds formatting conventions — how a value is rendered and parsed. It
never holds prose. That is the rule a ninth member has to pass: no
message catalogue, no lookup, no pluralization. Book ch10 argues it;
D_locale records what it excludes.
Index a name table with the Date accessor that selects it — which is why
the two have different shapes:
locale.month_names[date.month] # Hash keyed 1..12, since Date#month is 1-based
locale.day_names[date.wday] # Array 0..6, since Date#wday is 0-based
A 0-based month array would answer month_names[9] # => "October": a
plausible wrong answer, silently, which is why the shapes differ rather than
matching.
ISO is the only constant; build your own from it, and every member is
validated — by the constructor and again by Data#with, so an invalid
Locale is unreachable:
Locale::ISO.with(date_formats: ["%d.%m.%Y", "%Y-%m-%d"])
Implementation details
Read it at use time and never cache it in an ivar — Screen#locale= can
replace it mid-session, exactly as Screen#theme= can. A Component reads
it through the protected Component#locale, which answers ISO when no
screen exists at all, so a detached tree still works.
Defined Under Namespace
Modules: DateFormats, Formats, TimeFormats
Constant Summary collapse
- MONTHS =
The month numbers a month table is keyed by —
Date#month's range. (1..12).to_a.freeze
- WEEKDAYS =
The weekday numbers a day table is indexed by —
Date#wday's range, Sunday first. (0..6).to_a.freeze
- KEYWORDS =
The
locale(1)keywords system asks for, spanning both categories it reads:LC_TIMEfor the date conventions,LC_NUMERICfor the numeric one. libc resolves each in its own category, so one call is enough.t_fmt_ampmis deliberately absent besidet_fmt: en_GB's is%l:%M:%S %P %Z, which carries a zone name and a blank-padded 12-hour hour — two directives TimeFormats rejects. %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze
- SILENT_LOCALES =
Locale names that mean "the user said nothing" — the C/POSIX default, whose conventions are American. Compared against the name with any codeset suffix removed, so
C.UTF-8counts too. %w[C POSIX].freeze
- PROGRAM =
"locale"- ISO =
The ISO 8601 floor, and the only constant this file ships: it is what a Windows box, a musl container, a
LANG=Crunner and a failed probe all get. Three of its members cite the same standard — ISO 8601 dates, an ISO 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 mandates — which is what makes it a coherent floor rather than a bag of defaults.The names are Ruby's own frozen English tables, re-keyed but not authored, so Tuile still ships zero locale data of its own. The decimal separator is
"."becauseFloat#to_sandBigDecimal#to_swrite one, and a field'svalue=goes through them. new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." )
Instance Attribute Summary collapse
-
#abbr_day_names ⇒ ::Array[String]
readonly
Abbreviated weekday names, indexed 0..6.
-
#abbr_month_names ⇒ ::Hash[Integer, String]
readonly
Abbreviated month names, keyed
1..12. -
#calendar_start ⇒ Numeric
readonly
When the Gregorian calendar takes over from the Julian one, as a Julian Day Number —
Date::GREGORIAN(proleptic) here, not Ruby'sDate::ITALY. -
#date_formats ⇒ ::Array[String]
readonly
The strftime patterns a date field accepts, primary first: it is what Component::DateField writes and canonicalizes into, and only it must survive a round-trip.
-
#day_names ⇒ ::Array[String]
readonly
Full weekday names, indexed 0..6 by
Date#wday(Sunday first). -
#decimal_separator ⇒ String
readonly
What separates a number's integer and fractional parts — one grapheme cluster, one column wide.
-
#first_weekday ⇒ Integer
readonly
The day a calendar week starts on, in
Date#wdaynumbering: 0 = Sunday, 1 = Monday. -
#month_names ⇒ ::Hash[Integer, String]
readonly
Full month names, keyed
1..12byDate#month. -
#time_formats ⇒ ::Array[String]
readonly
The strftime patterns a time field accepts, primary first — carrying the locale's spelling at full detected precision, seconds included, because dropping them is a form field's policy rather than a convention: Component::TimeField strips them per its Component::TimeField#step, and a clock display wants them kept.
Class Method Summary collapse
-
.from_keywords(keywords, env: ENV) ⇒ Locale
Builds a Locale from
locale -kkeyword values, applying the same per-category gates and per-member fallbacks Locale.system does. -
.speaks?(env, category) ⇒ Boolean
Whether the POSIX chain for one category names a locale at all.
- .system(env: ENV) ⇒ Locale
-
.validate_calendar_start(value) ⇒ Numeric
@param
value. -
.validate_day_table(value, member) ⇒ ::Array[String]
@param
value. -
.validate_first_weekday(value) ⇒ Integer
@param
value. -
.validate_month_table(value, member) ⇒ ::Hash[Integer, String]
@param
value. -
.validate_separator(value) ⇒ String
@param
value.
Instance Method Summary collapse
-
#initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) ⇒ Object
constructor
@param
date_formats.
Constructor Details
#initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) ⇒ Object
@param date_formats
@param time_formats
@param calendar_start
@param first_weekday
@param month_names
@param abbr_month_names
@param day_names
@param abbr_day_names
@param decimal_separator
812 813 814 815 816 817 818 819 820 821 822 823 824 825 |
# File 'lib/tuile/locale.rb', line 812 def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end |
Instance Attribute Details
#abbr_day_names ⇒ ::Array[String] (readonly)
Abbreviated weekday names, indexed 0..6. Frozen.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
#abbr_month_names ⇒ ::Hash[Integer, String] (readonly)
Abbreviated month names, keyed 1..12. Frozen.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
#calendar_start ⇒ Numeric (readonly)
When the Gregorian calendar takes over from the Julian one, as a Julian
Day Number — Date::GREGORIAN (proleptic) here, not Ruby's
Date::ITALY. See Component::DateField#calendar_start.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
#date_formats ⇒ ::Array[String] (readonly)
The strftime patterns a date field accepts, primary first: it is what Component::DateField writes and canonicalizes into, and only it must survive a round-trip. Frozen.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
#day_names ⇒ ::Array[String] (readonly)
Full weekday names, indexed 0..6 by Date#wday (Sunday first). Frozen.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
#decimal_separator ⇒ String (readonly)
What separates a number's integer and fractional parts — one grapheme cluster, one column wide.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
#first_weekday ⇒ Integer (readonly)
The day a calendar week starts on, in Date#wday numbering: 0 = Sunday,
1 = Monday. Not glibc's first_weekday, which is a 1-based index
into a Sunday-first list; system converts.
@return — 0..6.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
#month_names ⇒ ::Hash[Integer, String] (readonly)
Full month names, keyed 1..12 by Date#month. Frozen.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
#time_formats ⇒ ::Array[String] (readonly)
The strftime patterns a time field accepts, primary first — carrying the locale's spelling at full detected precision, seconds included, because dropping them is a form field's policy rather than a convention: Component::TimeField strips them per its Component::TimeField#step, and a clock display wants them kept. Frozen.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/tuile/locale.rb', line 75 class Locale < Data.define(:date_formats, :time_formats, :calendar_start, :first_weekday, :month_names, :abbr_month_names, :day_names, :abbr_day_names, :decimal_separator) # The strftime *lexer*, shared by every format validator here — one # tokenizer, so {DateFormats} and {TimeFormats} cannot drift on what a # directive is: # # Formats.each_directive("%d.%m.%Y") { |t| p t } # "%d", ".", "%m", ".", "%Y" # # Each validator over it supplies the rest — a reference value to round-trip # against, a hint table, its own by-name rejections. See {DateFormats} and # {TimeFormats}. module Formats # *Any* strftime directive, known or not — flags, width, the `E`/`O` # modifiers and the `%::z` colons included. Matching the ones a caller # cannot translate is the point: they must reach a hint table's miss # rather than falling through as literal text, or `"%Y-%j"` would # humanize to the lying hint `"yyyy-%j"`. # @return [Regexp] DIRECTIVE = /%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/ # They *look* like a locale channel and are not: Ruby's `%x` is a fixed # `"09/04/26"` under every locale, and it round-trips — so it would pass # validation while silently meaning "American". Rejected by name by # every validator here. # @return [Array<String>] LOCALE_LOOKALIKES = %w[%x %X %c].freeze module_function # Yields each strftime directive in `format`, and each character between # them one at a time — so a caller can tell `"%%"` (one directive, a # literal percent) from a bare `"%"` that is merely text. # @param format [String] # @yieldparam token [String] a whole directive, or a single character. # @return [void] def each_directive(format) scanner = StringScanner.new(format) until scanner.eos? directive = scanner.scan(DIRECTIVE) yield(directive || scanner.getch) end end # @param format [String] # @return [String, nil] the first locale lookalike in `format`, or `nil`. def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) } # Translates a format through `hints`, or `nil` when it holds any # directive the table does not cover — never a half-translated hint. # # Formats.humanize("%d.%m.%Y", DateFormats::HINTS) # => "dd.mm.yyyy" # # @param format [String] # @param hints [Hash{String => String}] # @return [String, nil] frozen. def humanize(format, hints) hint = +"" each_directive(format) do |directive| next hint << directive if directive.length == 1 translated = hints[directive] return nil if translated.nil? hint << translated end hint.freeze end end # The two rules a strftime *date* format list obeys: what may be *in* one # ({validate}) and what one looks like to a human ({humanize}). Both answer # at assignment, so a bad format raises there rather than at the first # keystroke. {TimeFormats} is its sibling over the same {Formats} lexer. module DateFormats # The date every format is round-tripped against. Every property is # load-bearing: *pre-1969* so `%y` fails (it cannot carry a century), # *post-1582-10-15* so the Gregorian reform fails no innocent format, # and *month ≠ day* so a `%m`/`%d` swap is not masked. A canary rather # than a proof — but a century-lossy directive is lossy in both # directions, so one pre-window date catches the class that ships. # @return [Date] REF = Date.new(1962, 9, 4) # The directives {DateFormats.humanize} can turn into a placeholder. # There is deliberately no `%b`/`%B`: a month *name* would need an # invented `mmm`, and an app typing month names sets its own hint. # @return [Hash{String => String}] HINTS = { "%Y" => "yyyy", "%m" => "mm", "%d" => "dd", "%%" => "%" }.freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each. # # DateFormats.validate("%d.%m.%Y") # => ["%d.%m.%Y"] # # **The primary is held to a stricter rule than the rest.** `formats.first` # is what a field *writes*, so it must survive a `strftime`/`strptime` # round-trip; every later entry only ever *parses*, so it need only be a # usable strptime pattern — which is how a lenient list carries a # two-digit-year pattern behind its widened one. # # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a primary # that does not round-trip, or any entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # Translates a format into a typing hint, or `nil` when it holds any # directive {HINTS} does not cover. # # DateFormats.humanize("%d.%m.%Y") # => "dd.mm.yyyy" # DateFormats.humanize("%Y-%j") # => nil, rather than "yyyy-%j" # # @param format [String] # @return [String, nil] frozen. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites every `%y` in `format` as `%Y`, leaving the rest alone. # # DateFormats.widen("%d/%m/%y") # => "%d/%m/%Y" # DateFormats.widen("100%%y") # => "100%%y" — that is a literal % # # For {validate}'s benefit: a two-digit year cannot round-trip, since # `Date.new(1962, 9, 4)` renders `"04/09/62"` and reparses as **2062** # under Ruby's fixed POSIX window. So {Locale.system} widens a detected # `d_fmt` here rather than losing it, where an app assigning the same # pattern gets the rejection instead (`D_locale`). # # @param format [String] # @return [String] frozen. def widen(format) widened = +"" Formats.each_directive(format) do |directive| widened << (directive.end_with?("y") && directive.length > 1 ? "#{directive[0..-2]}Y" : directive) end widened.freeze end # @param format [String] # @param primary [Boolean] whether this is `formats.first`, which is # written as well as read and so must round-trip. # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a locale lookalike or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) Date.strptime(REF.strftime(format), format) == REF rescue ArgumentError # Date::Error is one; so is an unparseable format false end # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: `"%d/%m/%y"` # parses fine, it just parses to the wrong century. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.include?("%y") "%y cannot carry a century (Ruby reads 69 as 1969 and 26 as 2026), so write %Y — " \ "it may still appear later in the list, where it only ever parses" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or is not the directive you meant" end end # {DateFormats}' sibling for *times of day*, over the same {Formats} lexer. # Same two rules — what may be in a list ({validate}), what one looks like # to a human ({humanize}) — plus the two operations a time format needs and # a date one does not: # # TimeFormats.expand("%r") # => "%I:%M:%S %p" libc's shorthand # TimeFormats.strip_seconds("%H.%M.%S") # => "%H.%M" spelling kept, precision dropped # # The tables are kept separate from {DateFormats}' on purpose: `%m` → `mm` # (month) and `%M` → `mm` (minute) are each right in their own table, and # merging them is a question only a date-*and*-time field would have to ask. module TimeFormats # The time every format is round-tripped against, on # {Component::TimeField::MIDNIGHT}'s date. Every property is # load-bearing: *hour ≥ 13* so a 12-hour directive with no `%p` fails # (`"%I:%M"` writes `"01:45"` and reads back 1 o'clock), *minute ≠ hour* # so an `%H`/`%M` swap is not masked, and *second = 0* so a # minute-precision primary is legal — which the shipped default is. # # What it deliberately does not catch is a **precision truncation**: # `"%H:%M"` round-trips itself perfectly, and how precise a field is, is # {Component::TimeField#step}'s business. # @return [Time] REF = Time.utc(2000, 1, 1, 13, 45, 0) # The directives {TimeFormats.humanize} can turn into a placeholder. # `%p` earns a place where {DateFormats}' `%b` did not: `mmm` would be an # invented token, while `AM` is literally what the field prints, and a # placeholder is a typing *sample*. # @return [Hash{String => String}] HINTS = { "%H" => "hh", "%I" => "hh", "%k" => "hh", "%l" => "hh", "%M" => "mm", "%S" => "ss", "%p" => "AM", "%P" => "am", "%%" => "%" }.freeze # libc's compound time formats, expanded at the detection boundary so # every later consumer sees one vocabulary. A representation change and # nothing more — which is why it belongs here and the *seconds* strip # does not (see {strip_seconds}). # @return [Hash{String => String}] EXPANSIONS = { "%T" => "%H:%M:%S", "%R" => "%H:%M", "%r" => "%I:%M:%S %p" }.freeze # Rejected by name because they **round-trip cleanly and lose information # anyway**: `"%H:%M:%S%z"` writes `+0000` and reads it back, while # `Date._strptime("13:45:00+0200", "%H:%M:%S%z")` hands back an offset a # field with no zone drops on the floor — so a user typing one would see # it silently reinterpreted as a local wall time. # @return [Array<String>] ZONE_DIRECTIVES = ["%z", "%Z", "%:z", "%::z", "%s"].freeze # Rejected by name for the same reason: `"%H:%M:%S.%L"` round-trips (the # reference's fraction is 0) while `"13:45:00.500"` parses to a # `sec_fraction` a time of day cannot hold. # @return [Array<String>] SUBSECOND_DIRECTIVES = ["%L", "%N"].freeze module_function # Normalizes one format or a list of them into a frozen `Array` of frozen # `String`s, validating each — the primary by round-trip, the rest by # whether `strptime` can use them at all ({DateFormats.validate} has the # argument; it is the same split). # @param list [String, Array<String>] # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but a String or an Array of Strings. # @raise [ArgumentError] on an empty list, a locale lookalike, a zone or # sub-second directive, a primary that does not round-trip, or any # entry `strptime` cannot use. def validate(list) formats = list.instance_of?(String) ? [list] : list raise TypeError, "expected a String or an Array of Strings, got #{list.inspect}" unless formats.is_a?(Array) raise ArgumentError, "expected at least one format" if formats.empty? formats.each_with_index.map { |format, index| validate_one(format, primary: index.zero?) }.freeze end # @param format [String] # @return [String, nil] frozen; `nil` when `format` holds a directive # {HINTS} does not cover. def humanize(format) = Formats.humanize(format, HINTS) # Rewrites libc's compound directives ({EXPANSIONS}) as their components, # leaving everything else alone. # # TimeFormats.expand("%T") # => "%H:%M:%S" # # @param format [String] # @return [String] frozen. def (format) = +"" Formats.each_directive(format) { << (EXPANSIONS[_1] || _1) } .freeze end # Drops `%S` and the literal run immediately before it, so a format keeps # its *spelling* and loses only its *precision*. # # TimeFormats.strip_seconds("%I:%M:%S %p") # => "%I:%M %p" # TimeFormats.strip_seconds("%H%M%S") # => "%H%M" # TimeFormats.strip_seconds("%H:%M") # => "%H:%M" — nothing to drop # # **Policy, not normalization**, which is why {Locale} carries the # full-precision spelling and the *field* applies this: a clock display # legitimately wants the seconds `t_fmt` gave it (`D_time_field`). # @param format [String] # @return [String] frozen. def strip_seconds(format) tokens = [] Formats.each_directive(format) { tokens << _1 } kept = tokens.each_with_object([]) do |token, out| next out << token unless token == "%S" out.pop while out.last&.length == 1 # the separator run in front of it end kept.join.freeze end # Whether `format` writes at least one whole second. # @param format [String] # @return [Boolean] def seconds?(format) = format.include?("%S") # Parses `text` as a time of day, on `epoch`'s date in UTC. # # Three gates, because `Time` **normalizes where `Date` raised**: # `Date._strptime("24:00", "%H:%M")` yields `hour: 24` and # `Time.utc(…, 24, 0, 0)` is silently *the next day*, while `"13:45:60"` # rolls over to `13:46:00` — both wrong values that save cleanly, and the # rollover lands on a different date from every other value the field # produces, so comparison and sorting quietly break. # # @param text [String] # @param format [String] # @param epoch [Time] whose date the result sits on. # @return [Time, nil] `nil` unless `format` consumes `text` whole *and* # the fields it yields are a real time of day. def parse(text, format, epoch) parsed = Date._strptime(text, format) return nil if parsed.nil? || !parsed[:leftover].to_s.empty? hour, min, sec = parsed.values_at(:hour, :min, :sec).map { _1 || 0 } return nil unless in_range?(hour, min, sec) Time.utc(epoch.year, epoch.month, epoch.day, hour, min, sec) rescue ArgumentError nil end # The one range gate, shared by {parse} and # {Component::TimeField.time_of_day} so # a parsed time and a constructed one cannot disagree on what is legal. # `24:00` is rejected: a legal ISO 8601 end-of-day that `Time` cannot # hold. # @param hour [Integer] # @param min [Integer] # @param sec [Integer] # @return [Boolean] def in_range?(hour, min, sec) = (0..23).cover?(hour) && (0..59).cover?(min) && (0..59).cover?(sec) # @param format [String] # @param primary [Boolean] # @return [String] a frozen copy. # @raise [TypeError] unless `format` is a String. # @raise [ArgumentError] on a rejected directive or a failed check. def validate_one(format, primary: true) raise TypeError, "expected a String format, got #{format.inspect}" unless format.instance_of?(String) reject_by_name(format) usable = primary ? round_trips?(format) : parses?(format) raise ArgumentError, rejection(format, primary: primary) unless usable format.dup.freeze end # @param format [String] # @return [void] # @raise [ArgumentError] naming the directive and why a time of day # cannot carry it. def reject_by_name(format) lookalike = Formats.lookalike(format) raise ArgumentError, "#{lookalike} is not locale-aware in Ruby (it is a fixed American format)" if lookalike zone = ZONE_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{zone} carries a time zone, which this field has none of — the offset would be dropped" \ if zone fraction = SUBSECOND_DIRECTIVES.find { format.include?(_1) } raise ArgumentError, "#{fraction} carries a fraction of a second, which a time of day does not hold" if fraction end # @param format [String] # @return [Boolean] true iff formatting {REF} and parsing the result back # yields {REF} again. def round_trips?(format) = parse(REF.strftime(format), format, REF) == REF # @param format [String] # @return [Boolean] true iff `strptime` consumes its own `strftime` # output whole. Weaker than {round_trips?} on purpose: a later entry # only ever parses. def parses?(format) parsed = Date._strptime(REF.strftime(format), format) !parsed.nil? && parsed[:leftover].to_s.empty? rescue ArgumentError false end # @param format [String] # @param primary [Boolean] # @return [String] why the check failed, in the terms most likely to be # the caller's actual mistake. def rejection(format, primary: true) return "#{format.inspect} is not a usable strptime pattern: #{malformed}" unless primary reason = if format.match?(/%[Il]/) && !format.match?(/%[pP]/) "a 12-hour hour reads back as the morning without a %p or %P beside it" else malformed end "#{format.inspect} does not survive a strftime/strptime round-trip: #{reason}" end # @return [String] def malformed "it is incomplete, is write-only (strptime takes no `-` flag), " \ "or does not write a whole hour and minute" end end # The month numbers a month table is keyed by — `Date#month`'s range. # @return [Array<Integer>] MONTHS = (1..12).to_a.freeze # The weekday numbers a day table is indexed by — `Date#wday`'s range, # Sunday first. # @return [Array<Integer>] WEEKDAYS = (0..6).to_a.freeze # The `locale(1)` keywords {.system} asks for, spanning both categories it # reads: `LC_TIME` for the date conventions, `LC_NUMERIC` for the numeric # one. libc resolves each in its own category, so one call is enough. # @return [Array<String>] # `t_fmt_ampm` is deliberately absent beside `t_fmt`: en_GB's is # `%l:%M:%S %P %Z`, which carries a zone name and a blank-padded 12-hour # hour — two directives {TimeFormats} rejects. KEYWORDS = %w[d_fmt t_fmt first_weekday mon abmon day abday decimal_point].freeze # Locale names that mean "the user said nothing" — the C/POSIX default, # whose conventions are American. Compared against the name with any # codeset suffix removed, so `C.UTF-8` counts too. # @return [Array<String>] SILENT_LOCALES = %w[C POSIX].freeze # The program {.system} asks. POSIX, so present on Linux and macOS; absent # on Windows and in some musl containers, where {.system} yields {ISO}. # @return [String] PROGRAM = "locale" class << self # This system's conventions, or {ISO} when it has none to offer — the # seed for every new {Screen}. # # # under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y": # Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"] # # widened as detected fallback # # **This shells out** (`locale -k`, ~1 ms) — Ruby exposes no locale data # at all — and it is not memoized, so it costs that once per {Screen}. # # Two contracts a caller depends on: # # - **Each half is kept only if its own POSIX chain speaks**: `LC_ALL` / # `LC_TIME` / `LANG` for the date conventions, `LC_ALL` / `LC_NUMERIC` / # `LANG` for the numeric ones, with unset, `C` and `POSIX` all counting # as silence. Silence yields the {ISO} member, *not* what `locale(1)` # would answer — which is American. Book ch10 has the argument. # - **Nothing here fails loudly.** A value that does not validate falls # back to its {ISO} member on its own, and a missing binary or any other # error yields {ISO} whole. `locale(1)`'s exit status is meaningless in # both directions and is ignored. # # @param env [Hash{String => String}] environment to read the gates from; # defaults to `ENV`. The subprocess always inherits the real one. # @return [Locale] def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end # Builds a {Locale} from `locale -k` keyword values, applying the same # per-category gates and per-member fallbacks {.system} does. Public so a # spec can drive the conversion with canned answers rather than the # machine's own. # @api private # @param keywords [Hash{String => String}] as parsed from `locale -k`. # @param env [Hash{String => String}] # @return [Locale] def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end # Whether the POSIX chain for one category names a locale at all. # @api private # @param env [Hash{String => String}] # @param category [String] e.g. `"LC_TIME"`. # @return [Boolean] def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end # @param value [Numeric] # @return [Numeric] # @raise [TypeError] def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end # @param value [Integer] # @return [Integer] # @raise [TypeError] # @raise [ArgumentError] outside `Date#wday`'s 0..6. def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end # @param value [Hash{Integer => String}] # @param member [Symbol] for the message. # @return [Hash{Integer => String}] frozen, as are its values. # @raise [TypeError] on anything but a Hash — an Array especially, which # is the mistake this keying exists to prevent. # @raise [ArgumentError] unless keyed exactly 1..12 with non-empty names. def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end # @param value [Array<String>] # @param member [Symbol] for the message. # @return [Array<String>] frozen, as are its elements. # @raise [TypeError] on anything but an Array. # @raise [ArgumentError] unless it holds exactly 7 non-empty names. def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end # @param value [String] # @return [String] frozen. # @raise [TypeError] # @raise [ArgumentError] unless it is one grapheme cluster one column # wide — a painted glyph, held to the same rule as every other glyph # knob in Tuile. def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end private # @param name [Object] # @param member [Symbol] # @return [String] frozen. def validate_name(name, member) raise TypeError, "#{member} must hold Strings, got #{name.inspect}" unless name.instance_of?(String) raise ArgumentError, "#{member} must hold non-empty names" if name.empty? name.dup.freeze end # Applies one detected member, keeping what {ISO} had whenever the value # is absent or does not validate. Per-member rather than all-or-nothing, # and it reuses the real validator rather than restating its shape rules. # @param locale [Locale] # @param member [Symbol] # @param value [Object, nil] # @return [Locale] def merge(locale, member, value) return locale if value.nil? locale.with(member => value) rescue StandardError locale end # Runs `locale -k` and parses its `key=value` lines. # @return [Hash{String => String}] empty when the program is missing or # says nothing. def probe output = IO.popen([PROGRAM, "-k", *KEYWORDS], err: File::NULL, &:read) parse_keywords(output.to_s) rescue SystemCallError, IOError {} end # @param output [String] # @return [Hash{String => String}] def parse_keywords(output) output.each_line.filter_map do |line| key, separator, value = line.chomp.partition("=") next if separator.empty? [key, unquote(value)] end.to_h end # `locale -k` quotes string values and leaves numeric ones bare. # @param value [String] # @return [String] def unquote(value) quoted = value.length >= 2 && value.start_with?('"') && value.end_with?('"') quoted ? value[1..-2] : value end # The detected list: the widened pattern as primary, the raw one behind # it so what the user types is still understood, and ISO last as a # universal fallback. Lenient in, strict out. # @param raw [String, nil] the `d_fmt` value. # @return [Array<String>, nil] def date_formats_from(raw) return nil if raw.to_s.empty? [DateFormats.widen(raw), raw, ISO.date_formats.first].uniq end # The detected list: libc's shorthand expanded, ISO behind it as a # universal fallback. **Seconds are kept** — `t_fmt` is a clock-display # format, and reducing it to minutes is # {Component::TimeField#step}'s policy, applied where a clock display can # still opt out of it (`D_time_field`). # # No *raw* entry, unlike {date_formats_from}: there is no widening here, # so the expansion parses everything the shorthand did. # @param raw [String, nil] the `t_fmt` value. # @return [Array<String>, nil] def time_formats_from(raw) return nil if raw.to_s.empty? [TimeFormats.(raw), ISO.time_formats.first].uniq end # glibc's `first_weekday` is a **1-based index into `day`, which starts # at Sunday** — so its Monday is 2. Converted here, at the boundary, # never at the consumer. # @param raw [String, nil] # @return [Integer, nil] def first_weekday_from(raw) return nil if raw.to_s.empty? Integer(raw, 10) - 1 rescue ArgumentError, TypeError nil end # @param raw [String, nil] a `;`-separated `mon` / `abmon` value. # @return [Hash{Integer => String}, nil] def month_table_from(raw) names = split_list(raw) names.size == MONTHS.size ? MONTHS.zip(names).to_h : nil end # @param raw [String, nil] a `;`-separated `day` / `abday` value. # @return [Array<String>, nil] def day_table_from(raw) names = split_list(raw) names.size == WEEKDAYS.size ? names : nil end # @param raw [String, nil] # @return [Array<String>] def split_list(raw) = raw.to_s.split(";", -1) end # @param date_formats [Array<String>, String] # @param time_formats [Array<String>, String] # @param calendar_start [Numeric] # @param first_weekday [Integer] # @param month_names [Hash{Integer => String}] # @param abbr_month_names [Hash{Integer => String}] # @param day_names [Array<String>] # @param abbr_day_names [Array<String>] # @param decimal_separator [String] # @raise [TypeError] on a member of the wrong type. # @raise [ArgumentError] on a member of the wrong shape — a format list # that does not validate, a month table not keyed `1..12`, a day table # that is not 7 long, a `first_weekday` outside 0..6, or a decimal # separator that is not one single-column grapheme cluster. def initialize(date_formats:, time_formats:, calendar_start:, first_weekday:, month_names:, abbr_month_names:, day_names:, abbr_day_names:, decimal_separator:) super( date_formats: DateFormats.validate(date_formats), time_formats: TimeFormats.validate(time_formats), calendar_start: Locale.validate_calendar_start(calendar_start), first_weekday: Locale.validate_first_weekday(first_weekday), month_names: Locale.validate_month_table(month_names, :month_names), abbr_month_names: Locale.validate_month_table(abbr_month_names, :abbr_month_names), day_names: Locale.validate_day_table(day_names, :day_names), abbr_day_names: Locale.validate_day_table(abbr_day_names, :abbr_day_names), decimal_separator: Locale.validate_separator(decimal_separator) ) end # The ISO 8601 floor, and the only constant this file ships: it is what a # Windows box, a musl container, a `LANG=C` runner and a failed probe all # get. Three of its members cite the same standard — ISO 8601 dates, an ISO # 8601 Monday week start, and the proleptic Gregorian calendar ISO 8601 # mandates — which is what makes it a coherent floor rather than a bag of # defaults. # # The names are Ruby's own frozen English tables, re-keyed but not # authored, so Tuile still ships zero locale data of its own. The decimal # separator is `"."` because `Float#to_s` and `BigDecimal#to_s` write one, # and a field's `value=` goes through them. # @return [Locale] ISO = new( date_formats: ["%Y-%m-%d"], time_formats: ["%H:%M:%S"], calendar_start: Date::GREGORIAN, first_weekday: 1, month_names: MONTHS.zip(Date::MONTHNAMES[1..]).to_h, abbr_month_names: MONTHS.zip(Date::ABBR_MONTHNAMES[1..]).to_h, day_names: Date::DAYNAMES, abbr_day_names: Date::ABBR_DAYNAMES, decimal_separator: "." ) end |
Class Method Details
.from_keywords(keywords, env: ENV) ⇒ Locale
Builds a Tuile::Locale from locale -k keyword values, applying the same
per-category gates and per-member fallbacks system does. Public so a
spec can drive the conversion with canned answers rather than the
machine's own.
@param keywords — as parsed from locale -k.
@param env
584 585 586 587 588 589 590 591 592 593 594 595 596 597 |
# File 'lib/tuile/locale.rb', line 584 def from_keywords(keywords, env: ENV) locale = ISO if speaks?(env, "LC_TIME") locale = merge(locale, :date_formats, date_formats_from(keywords["d_fmt"])) locale = merge(locale, :time_formats, time_formats_from(keywords["t_fmt"])) locale = merge(locale, :first_weekday, first_weekday_from(keywords["first_weekday"])) locale = merge(locale, :month_names, month_table_from(keywords["mon"])) locale = merge(locale, :abbr_month_names, month_table_from(keywords["abmon"])) locale = merge(locale, :day_names, day_table_from(keywords["day"])) locale = merge(locale, :abbr_day_names, day_table_from(keywords["abday"])) end locale = merge(locale, :decimal_separator, keywords["decimal_point"]) if speaks?(env, "LC_NUMERIC") locale end |
.speaks?(env, category) ⇒ Boolean
Whether the POSIX chain for one category names a locale at all.
@param env
@param category — e.g. "LC_TIME".
604 605 606 607 608 609 |
# File 'lib/tuile/locale.rb', line 604 def speaks?(env, category) name = [env["LC_ALL"], env[category], env["LANG"]].map(&:to_s).find { !_1.empty? } return false if name.nil? !SILENT_LOCALES.include?(name.split(".").first.to_s.upcase) end |
.system(env: ENV) ⇒ Locale
This system's conventions, or ISO when it has none to offer — the seed for every new Screen.
# under en_GB, whose d_fmt is the un-round-trippable "%d/%m/%y":
Locale.system.date_formats # => ["%d/%m/%Y", "%d/%m/%y", "%Y-%m-%d"]
# widened as detected fallback
This shells out (locale -k, ~1 ms) — Ruby exposes no locale data
at all — and it is not memoized, so it costs that once per Screen.
Two contracts a caller depends on:
- Each half is kept only if its own POSIX chain speaks:
LC_ALL/LC_TIME/LANGfor the date conventions,LC_ALL/LC_NUMERIC/LANGfor the numeric ones, with unset,CandPOSIXall counting as silence. Silence yields the ISO member, not whatlocale(1)would answer — which is American. Book ch10 has the argument. - Nothing here fails loudly. A value that does not validate falls
back to its ISO member on its own, and a missing binary or any other
error yields ISO whole.
locale(1)'s exit status is meaningless in both directions and is ignored.
@param env — environment to read the gates from; defaults to ENV. The subprocess always inherits the real one.
568 569 570 571 572 573 574 |
# File 'lib/tuile/locale.rb', line 568 def system(env: ENV) return ISO unless speaks?(env, "LC_TIME") || speaks?(env, "LC_NUMERIC") from_keywords(probe, env: env) rescue StandardError ISO end |
.validate_calendar_start(value) ⇒ Numeric
@param value
614 615 616 617 618 |
# File 'lib/tuile/locale.rb', line 614 def validate_calendar_start(value) raise TypeError, "calendar_start must be Numeric, got #{value.inspect}" unless value.is_a?(Numeric) value end |
.validate_day_table(value, member) ⇒ ::Array[String]
@param value
@param member — for the message.
@return — frozen, as are its elements.
655 656 657 658 659 660 661 662 663 |
# File 'lib/tuile/locale.rb', line 655 def validate_day_table(value, member) unless value.is_a?(Array) raise TypeError, "#{member} must be an Array indexed 0..6 (Date#wday is 0-based), got #{value.inspect}" end raise ArgumentError, "#{member} must hold exactly 7 names, got #{value.size}" unless value.size == WEEKDAYS.size value.map { validate_name(_1, member) }.freeze end |
.validate_first_weekday(value) ⇒ Integer
@param value
624 625 626 627 628 629 630 631 |
# File 'lib/tuile/locale.rb', line 624 def validate_first_weekday(value) raise TypeError, "first_weekday must be an Integer, got #{value.inspect}" unless value.is_a?(Integer) unless WEEKDAYS.include?(value) raise ArgumentError, "first_weekday must be 0..6 in Date#wday numbering (0 = Sunday), got #{value.inspect}" end value end |
.validate_month_table(value, member) ⇒ ::Hash[Integer, String]
@param value
@param member — for the message.
@return — frozen, as are its values.
639 640 641 642 643 644 645 646 647 648 |
# File 'lib/tuile/locale.rb', line 639 def validate_month_table(value, member) unless value.is_a?(Hash) raise TypeError, "#{member} must be a Hash keyed 1..12 (Date#month is 1-based), got #{value.inspect}" end raise ArgumentError, "#{member} must be keyed exactly 1..12, got #{value.keys.inspect}" \ unless value.keys.sort == MONTHS value.to_h { |month, name| [month, validate_name(name, member)] }.freeze end |
.validate_separator(value) ⇒ String
@param value
@return — frozen.
671 672 673 674 675 676 677 678 679 680 681 |
# File 'lib/tuile/locale.rb', line 671 def validate_separator(value) raise TypeError, "decimal_separator must be a String, got #{value.inspect}" unless value.instance_of?(String) clusters = value.grapheme_clusters unless clusters.size == 1 && Buffer.display_width(value) == 1 raise ArgumentError, "decimal_separator must be one single-column grapheme cluster, got #{value.inspect}" end value.dup.freeze end |