import os
import re
import sys
lib = sys.argv[1]
here = os.path.dirname(os.path.abspath(__file__))
crate = os.path.dirname(here)
source = open(os.path.join(lib, "timezonedb.h"), encoding="latin-1").read()
slim = source[source.index("#ifdef TIMELIB_SUPPORT_SLIM_FILE"):source.index("#else")]
version = re.search(r'timezonedb_builtin = \{ "([^"]+)", (\d+),', source)
index = re.findall(r'\{ \(char\*\) "([^"]+)"\s*, 0x([0-9A-F]+) \}', slim)
assert len(index) == int(version.group(2)), (len(index), version.group(2))
data_start = slim.index("timelib_timezone_db_data_builtin[")
size = int(re.search(r"timelib_timezone_db_data_builtin\[(\d+)\]", slim).group(1))
body = slim[slim.index("{", data_start) + 1:]
body = re.sub(r"/\*.*?\*/", "", body, flags=re.S)
data = bytes(int(h, 16) for h in re.findall(r"0x([0-9A-Fa-f]{2})", body))
assert len(data) == size, (len(data), size)
with open(os.path.join(here, "timezonedb.bin"), "wb") as f:
f.write(data)
with open(os.path.join(crate, "src", "datetime", "tzindex.rs"), "w") as f:
f.write("//! Generated by `data/timezonedb.py` from PHP's `timezonedb.h`: do not edit.\n\n")
f.write(f"/// `timezone_version_get()`.\npub const VERSION: &str = \"{version.group(1)}\";\n\n")
f.write("/// Zone identifiers (sorted case-insensitively, as PHP searches them) and their offsets in the data.\n")
f.write(f"pub static INDEX: [(&str, u32); {len(index)}] = [\n")
for name, pos in index:
f.write(f" (\"{name}\", 0x{pos}),\n")
f.write("];\n")
def table(path):
rows = []
for line in open(os.path.join(lib, path), encoding="latin-1"):
m = re.match(r'\s*\{\s*"([^"]+)",\s*(\d+),\s*([-0-9 *]+),\s*(NULL|"[^"]*")\s*\}', line)
if m:
name, dst, offset, tz = m.groups()
rows.append((name, int(dst), eval(offset), None if tz == "NULL" else tz.strip('"')))
return rows
with open(os.path.join(crate, "src", "datetime", "abbreviations.rs"), "w") as f:
f.write("//! Generated by `data/timezonedb.py` from timelib's `timezonemap.h` and `fallbackmap.h`: do not edit.\n\n")
f.write("/// An abbreviation row: name, DST flag, UTC offset in seconds, zone identifier.\n")
f.write("pub type Row = (&'static str, i32, i32, Option<&'static str>);\n\n")
for const, path in (("TIMEZONEMAP", "timezonemap.h"), ("FALLBACKMAP", "fallbackmap.h")):
rows = table(path)
f.write(f"/// `{path}`.\npub static {const}: [Row; {len(rows)}] = [\n")
for name, dst, offset, tz in rows:
tz = "None" if tz is None else f'Some("{tz}")'
f.write(f' ("{name}", {dst}, {offset}, {tz}),\n')
f.write("];\n\n")
print(f"timezonedb {version.group(1)}: {len(index)} zones, {len(data)} bytes")