]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - scripts/check-timezones.py
Implement unreified Variants with Scope and canonical merging
[topic-maps.git] / scripts / check-timezones.py
1 #!/usr/bin/env python3
2 """Independent arbitrary-integer UTC oracle; fixed-offset datetime cross-checks.
3
4 Fractions stay text; no float, implicit local timezone or platform calendar.
5 """
6 import datetime
7 import json
8 from pathlib import Path
9 import re
10 import sys
11 import xml.etree.ElementTree as ET
12
13 if hasattr(sys, 'set_int_max_str_digits'):
14 sys.set_int_max_str_digits(0)
15 report = json.loads(Path(sys.argv[1]).read_text())
16 assert report['kind'] == 'datetime-timezone-evidence' and report['failed'] == 0
17 assert report['passed'] == len(report['checks']) == len(set(report['checks']))
18
19
20 def canonical(text):
21 match = re.fullmatch(r'(-?[0-9]{4,})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?(Z|[+-][0-9]{2}:[0-9]{2})?', text)
22 assert match
23 year, month, day, hour, minute, second, fraction, zone = match.groups()
24 y, mo, d, h, mi, se = map(int, (year, month, day, hour, minute, second))
25 original = y, mo, d, h, mi, se
26 assert se < 60, 'new nonzero-offset leap-second semantics deliberately excluded'
27 offset = 0 if not zone or zone == 'Z' else (1 if zone[0] == '+' else -1) * (int(zone[1:3]) * 60 + int(zone[4:]))
28 carry, minutes = divmod(h * 60 + mi - offset, 1440)
29
30 def days(y, mo):
31 leap = y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
32 return [31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1]
33
34 d += carry
35 while d < 1:
36 mo -= 1
37 if mo == 0:
38 mo = 12
39 y -= 1
40 if y == 0:
41 y = -1
42 d += days(y, mo)
43 while d > days(y, mo):
44 d -= days(y, mo)
45 mo += 1
46 if mo == 13:
47 mo = 1
48 y += 1
49 if y == 0:
50 y = 1
51 h, mi = divmod(minutes, 60)
52 fraction = (fraction or '').rstrip('0')
53 result = f'{"-" if y < 0 else ""}{str(abs(y)).zfill(4)}-{mo:02d}-{d:02d}T{h:02d}:{mi:02d}:{se:02d}'
54 result += ('.' + fraction if fraction else '') + ('Z' if zone else '')
55 # A second, standard-library implementation for CE dates in its range.
56 if 1 <= original[0] <= 9998:
57 yy, mm, dd, hh, mn, ss = original
58 value = datetime.datetime(yy, mm, dd) + datetime.timedelta(hours=hh, minutes=mn, seconds=ss)
59 if zone:
60 value = value.replace(tzinfo=datetime.timezone(datetime.timedelta(minutes=offset))).astimezone(datetime.timezone.utc)
61 spelling = value.strftime('%Y-%m-%dT%H:%M:%S') + ('.' + fraction if fraction else '') + ('Z' if zone else '')
62 assert spelling == result
63 return result
64
65
66 offsets = set()
67 for probe in report['lexicalProbes']:
68 expected = canonical(probe['input'])
69 assert probe['canonicalValue'] == expected
70 mode = probe['mode']
71 if mode == 'helper':
72 offsets.add(probe['input'][-6:])
73 continue
74 assert probe['storedValue'] == (expected if mode == 'bare' else ' ' + probe['input'] + '\t' if mode == 'qualified' else probe['input'])
75 item, = ET.fromstring(probe['actualCXTM']).findall('topic/occurrence')
76 assert item.findtext('value') == expected
77 assert item.findtext('datatype') == 'http://www.w3.org/2001/XMLSchema#dateTime'
78 assert len(offsets) == 1681
79 print(f'TIMEZONE-INDEPENDENT-PASS: {len(report["lexicalProbes"])} exact UTC probes; 1681 signed offset minutes; stored strings and CXTM checked separately')