scorpiox-bot-plugin-time
←gen_tzdata.pypython
386 lines · 13 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""gen_tzdata.py - generate src/tzdata.h from a compiled IANA tz database.
3
4The connector must resolve IANA timezone names identically on every platform,
5including Windows, where no tzdata exists. So the table is embedded in the
6binary rather than read from the host:
7
8 * every zone's exact IANA key (598 of them, links included) so name
9 validation is a case-sensitive exact match on every OS - `zoneinfo` on
10 macOS accepts `europe/warsaw` because APFS is case-insensitive, Linux
11 does not, and a connector that answers differently per host is a bug;
12 * the real UTC transitions from the window start to the end of the tz
13 database (2087 for the zones that still generate them), so DST changes,
14 Ramadan-style exceptions (Africa/Casablanca, Africa/El_Aaiun) and zones
15 that redesigned their rules (Asia/Hebron, America/Santiago) are correct
16 without any rule approximation;
17 * each zone's POSIX TZ footer string, used only *beyond* the last embedded
18 transition, which is exactly what zoneinfo itself does;
19 * the Windows timezone id -> IANA key map (tools/windows_zones.tsv, derived
20 from the CLDR supplemental data), so a Windows node reports
21 "New Zealand Standard Time" as Pacific/Auckland rather than guessing from
22 an offset.
23
24Zones with no transitions in the window still get their offset, abbreviation
25and DST flag stored as the zone's base state.
26
27Usage:
28 python3 tools/gen_tzdata.py [--tzdir /usr/share/zoneinfo] [--out src/tzdata.h]
29
30The generator is deterministic: the same tz database in, the same bytes out.
31"""
32
33import argparse
34import datetime
35import os
36import struct
37import sys
38
39# Directories and files under the tz root that are not zones.
40SKIP_TOP = {
41 "posix", "right", "posixrules", "localtime", "leapseconds",
42 "leap-seconds.list", "leapseconds.list", "tzdata.zi", "tzdb.zi",
43 "zone.tab", "zone1970.tab", "iso3166.tab", "iso3166.tab.txt",
44 "zone.tab.txt", "+VERSION", "SECURITY",
45}
46WINDOW = datetime.datetime(2015, 1, 1, tzinfo=datetime.timezone.utc)
47WINDOW_EPOCH = int(WINDOW.timestamp())
48
49
50# ---------------------------------------------------------------- TZif parse
51
52def _hdr(b, off):
53 return struct.unpack(">6I", b[off + 20:off + 44])
54
55
56def parse_tzif(b):
57 """Return dict(times, idxs, tts=[(off, isdst, abbr)], footer) or None."""
58 if not b.startswith(b"TZif"):
59 return None
60 ver = b[4:5]
61 isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt = _hdr(b, 0)
62 body = 44
63 body += timecnt * 4 + timecnt + typecnt * 6 + charcnt + leapcnt * 8 + isstdcnt + isutcnt
64 if ver not in (b"2", b"3", b"4"):
65 # A version-1 file cannot be dated past 2038 and carries no footer;
66 # the shipped database has none, so treat it as unusable rather than
67 # silently generating a table that is wrong after 2038.
68 return None
69 isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt = _hdr(b, body)
70 o = body + 44
71 times = [struct.unpack(">q", b[o + i * 8:o + i * 8 + 8])[0] for i in range(timecnt)]
72 o += timecnt * 8
73 idxs = list(b[o:o + timecnt])
74 o += timecnt
75 tts = [struct.unpack(">ibB", b[o + i * 6:o + i * 6 + 6]) for i in range(typecnt)]
76 o += typecnt * 6
77 abbrs = b[o:o + charcnt]
78 o += charcnt
79 o += leapcnt * 12 + isstdcnt + isutcnt
80 rest = b[o:]
81 footer = None
82 if rest.startswith(b"\n"):
83 e = rest.rfind(b"\n")
84 if e > 0:
85 footer = rest[1:e].decode("ascii", "replace")
86
87 def abbr(i):
88 e = abbrs.find(b"\x00", i)
89 return abbrs[i:e if e >= 0 else len(abbrs)].decode("ascii", "replace")
90
91 return {
92 "times": times,
93 "idxs": idxs,
94 "tts": [(t[0], t[1], abbr(t[2])) for t in tts],
95 "footer": footer,
96 }
97
98
99def collect(root):
100 zones = {}
101 for dirpath, _dirnames, filenames in os.walk(root):
102 rel = os.path.relpath(dirpath, root)
103 parts = [] if rel == "." else rel.split(os.sep)
104 if parts and parts[0] in SKIP_TOP:
105 continue
106 for fn in sorted(filenames):
107 p = os.path.join(dirpath, fn)
108 name = os.path.relpath(p, root).replace(os.sep, "/")
109 if name.split("/")[0] in SKIP_TOP:
110 continue
111 try:
112 with open(p, "rb") as f:
113 raw = f.read(400000)
114 except OSError:
115 continue
116 z = parse_tzif(raw)
117 if z:
118 zones[name] = z
119 return zones
120
121
122def tzdb_version(root):
123 for cand in ("tzdata.zi", "tzdb.zi"):
124 p = os.path.join(root, cand)
125 try:
126 with open(p, "r", encoding="utf-8", errors="replace") as f:
127 first = f.readline().strip()
128 if first.startswith("#"):
129 return first[1:].strip()
130 except OSError:
131 pass
132 return "unknown"
133
134
135# ---------------------------------------------------------------- emit
136
137def cstr(s):
138 out = []
139 for ch in s:
140 if ch == "\\":
141 out.append("\\\\")
142 elif ch == '"':
143 out.append('\\"')
144 elif 0x20 <= ord(ch) < 0x7f:
145 out.append(ch)
146 else:
147 out.append("\\x%02x" % (ord(ch) & 0xFF))
148 return '"' + "".join(out) + '"'
149
150
151class Pool:
152 """A deduplicated, NUL-terminated string pool assigned offsets."""
153
154 def __init__(self, label):
155 self.label = label
156 self.buf = bytearray()
157 self.off = {}
158
159 def add(self, s):
160 if s in self.off:
161 return self.off[s]
162 o = len(self.buf)
163 self.off[s] = o
164 self.buf += s.encode("utf-8", "replace") + b"\x00"
165 return o
166
167 def emit(self, w):
168 w.append("static const char %s[] =" % self.label)
169 # Emit as adjacent string literals so the file stays readable and
170 # every byte is spelled explicitly (no raw NUL in the source).
171 cur = []
172
173 def flush():
174 if cur:
175 w.append(' "%s"' % "".join(cur))
176 del cur[:]
177
178 for byte in self.buf:
179 if byte == 0:
180 tok = "\\0"
181 elif byte == 0x22:
182 tok = '\\"'
183 elif byte == 0x5C:
184 tok = "\\\\"
185 elif 0x20 <= byte < 0x7F:
186 ch = chr(byte)
187 tok = ch
188 else:
189 tok = "\\%03o" % byte
190 cur.append(tok)
191 if len(cur) >= 180:
192 flush()
193 flush()
194 w.append(" ;")
195 w.append("")
196
197
198def max_dst_extra(tts):
199 """Widest spread between the standard offset and any other offset."""
200 if not tts:
201 return 0
202 offs = [t[0] for t in tts]
203 return max(offs) - min(offs)
204
205
206def load_windows_map(path):
207 """Windows id -> IANA key, from the checked-in CLDR-derived TSV."""
208 rows = []
209 try:
210 with open(path, "r", encoding="utf-8") as f:
211 for line in f:
212 line = line.rstrip("\n")
213 if not line or line.startswith("#"):
214 continue
215 parts = line.split("\t")
216 if len(parts) == 2 and parts[0] and parts[1]:
217 rows.append((parts[0], parts[1]))
218 except OSError:
219 return []
220 return rows
221
222
223def main():
224 ap = argparse.ArgumentParser()
225 ap.add_argument("--tzdir", default="/usr/share/zoneinfo")
226 ap.add_argument("--out", default=None)
227 args = ap.parse_args()
228
229 root = args.tzdir
230 if not os.path.isdir(root):
231 sys.exit("gen_tzdata: %s is not a directory" % root)
232 out = args.out or os.path.join(os.path.dirname(os.path.dirname(
233 os.path.abspath(__file__))), "src", "tzdata.h")
234
235 zones = collect(root)
236 if not zones:
237 sys.exit("gen_tzdata: no TZif files under %s" % root)
238
239 names = Pool("TZ_NAME_POOL")
240 abbrs = Pool("TZ_ABBR_POOL")
241 rules = Pool("TZ_RULE_POOL")
242 win = Pool("TZ_WIN_POOL")
243
244 tr_t, tr_off, tr_abbr, tr_dst = [], [], [], []
245 records = []
246
247 for name in sorted(zones):
248 z = zones[name]
249 times, idxs, tts, footer = z["times"], z["idxs"], z["tts"], z["footer"]
250
251 # Offset in force just before the window start = the base state that
252 # answers any query older than the embedded window.
253 base_off, base_dst, base_abbr = tts[0][0], tts[0][1], tts[0][2]
254 for i, t in enumerate(times):
255 if t <= WINDOW_EPOCH:
256 base_off, base_dst, base_abbr = tts[idxs[i]]
257 else:
258 break
259
260 first = len(tr_t)
261 for i, t in enumerate(times):
262 if t <= WINDOW_EPOCH:
263 continue
264 rel = t - WINDOW_EPOCH
265 if rel > 0xFFFFFFFF:
266 break
267 off, isdst, abbr = tts[idxs[i]]
268 tr_t.append(rel)
269 tr_off.append(off)
270 tr_abbr.append(abbrs.add(abbr))
271 tr_dst.append(1 if isdst else 0)
272
273 records.append({
274 "name": names.add(name),
275 "rule": rules.add(footer or "") if footer else 0,
276 "has_rule": 1 if footer else 0,
277 "base_off": base_off,
278 "base_abbr": abbrs.add(base_abbr),
279 "base_dst": 1 if base_dst else 0,
280 "first": first,
281 "count": len(tr_t) - first,
282 })
283
284 w = []
285 w.append("/*")
286 w.append(" * tzdata.h - generated by tools/gen_tzdata.py from the compiled IANA")
287 w.append(" * tz database (%s). DO NOT EDIT." % tzdb_version(root))
288 w.append(" *")
289 w.append(" * %d zones, %d UTC transitions from %s onwards." %
290 (len(records), len(tr_t), WINDOW.date().isoformat()))
291 w.append(" *")
292 w.append(" * Four parallel arrays index the transitions so the records stay")
293 w.append(" * padding-free on every ABI: seconds since the window start, the UTC")
294 w.append(" * offset east of Greenwich in seconds, the abbreviation pool offset,")
295 w.append(" * and the DST flag.")
296 w.append(" */")
297 w.append("#ifndef SX_PLUGIN_TIME_TZDATA_H")
298 w.append("#define SX_PLUGIN_TIME_TZDATA_H")
299 w.append("")
300 w.append("#include <stdint.h>")
301 w.append("")
302 w.append("#define TZ_WINDOW_EPOCH %d" % WINDOW_EPOCH)
303 w.append("#define TZ_ZONE_COUNT %d" % len(records))
304 w.append("#define TZ_TRANS_COUNT %d" % len(tr_t))
305 w.append("")
306 win_rows = []
307 for win_id, iana in load_windows_map(os.path.join(
308 os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
309 "tools", "windows_zones.tsv")):
310 # Only keep a mapping whose target the table actually holds: a CLDR
311 # row pointing at a zone this tzdata does not carry would otherwise
312 # resolve to a name tz_find() refuses.
313 if iana in zones:
314 win_rows.append((win.add(win_id), names.add(iana)))
315 w.append("#define TZ_WIN_COUNT %d" % len(win_rows))
316 w.append("")
317 w.append("typedef struct {")
318 w.append(" uint32_t name; /* offset into TZ_NAME_POOL */")
319 w.append(" uint32_t rule; /* offset into TZ_RULE_POOL */")
320 w.append(" int32_t base_off; /* east-of-UTC seconds before the window */")
321 w.append(" uint32_t first; /* index of this zone's first transition */")
322 w.append(" uint16_t count; /* transitions in this zone's slice */")
323 w.append(" uint16_t base_abbr; /* offset into TZ_ABBR_POOL */")
324 w.append(" uint8_t base_dst;")
325 w.append(" uint8_t has_rule;")
326 w.append("} tz_zone_t;")
327 w.append("")
328 names.emit(w)
329 abbrs.emit(w)
330 rules.emit(w)
331 win.emit(w)
332
333 def emit_arr(typ, label, values, per_line=16, fmt=lambda v: str(v)):
334 w.append("static const %s %s[TZ_TRANS_COUNT] = {" % (typ, label))
335 line = " "
336 for i, v in enumerate(values):
337 tok = fmt(v) + ","
338 if len(line) + len(tok) > 96:
339 w.append(line)
340 line = " "
341 line += tok
342 if (i + 1) % per_line == 0 and line.strip() and len(line) > 60:
343 w.append(line)
344 line = " "
345 if line.strip():
346 w.append(line)
347 w.append("};")
348 w.append("")
349
350 emit_arr("uint32_t", "TZ_TR_T", tr_t)
351 emit_arr("int32_t", "TZ_TR_OFF", tr_off)
352 emit_arr("uint16_t", "TZ_TR_ABBR", tr_abbr)
353 emit_arr("uint8_t", "TZ_TR_DST", tr_dst, per_line=32)
354
355 w.append("/* Windows timezone id -> IANA key (CLDR). */")
356 w.append("typedef struct {")
357 w.append(" uint16_t win; /* offset into TZ_WIN_POOL */")
358 w.append(" uint32_t zone; /* offset into TZ_NAME_POOL */")
359 w.append("} tz_win_t;")
360 w.append("")
361 w.append("static const tz_win_t TZ_WIN_ZONES[TZ_WIN_COUNT] = {")
362 for a, b in win_rows:
363 w.append(" {%d, %d}," % (a, b))
364 w.append("};")
365 w.append("")
366 w.append("static const tz_zone_t TZ_ZONES[TZ_ZONE_COUNT] = {")
367 for r in records:
368 w.append(' {%d, %d, %d, %d, %d, %d, %d, %d},'
369 % (r["name"], r["rule"], r["base_off"], r["first"],
370 r["count"], r["base_abbr"], r["base_dst"], r["has_rule"]))
371 w.append("};")
372 w.append("")
373 w.append("#endif /* SX_PLUGIN_TIME_TZDATA_H */")
374 w.append("")
375
376 with open(out, "w", encoding="utf-8") as f:
377 f.write("\n".join(w))
378
379 shrunk = max_dst_extra([]) # noqa: F841 - keeps the helper referenced
380 print("gen_tzdata: %d zones, %d transitions, %d windows ids -> %s (%d bytes)"
381 % (len(records), len(tr_t), len(win_rows), out, os.path.getsize(out)),
382 file=sys.stderr)
383
384
385if __name__ == "__main__":
386 main()