diff --git a/.github/workflows/format-tzdata.yaml b/.github/workflows/format-tzdata.yaml new file mode 100644 index 0000000000..1adcbd9d64 --- /dev/null +++ b/.github/workflows/format-tzdata.yaml @@ -0,0 +1,53 @@ +name: Update TZ.h + +on: + workflow_dispatch: + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + enable-cache: true + version: "latest" + + - name: Refresh TZ.h + shell: bash + run: | + pushd tools + + uv python install + uv lock --refresh --upgrade --script format_tzdata.py + uv run format_tzdata.py ../cores/esp8266/TZ.h + + popd + + - name: Check updates + id: check + shell: bash + run: | + git add -u tools/format_tzdata.py.lock + git add cores/esp8266/TZ.h + + if ! git diff --cached --exit-code; then + commit=1 + else + commit=0 + fi + + echo "commit=${commit}" >> $GITHUB_OUTPUT + + - name: Commit updates + if: steps.check.outputs.commit == '1' + shell: bash + run: | + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + + branch=$(date -Im | tr '[:punct:]' '_') + git commit -m 'Core - update timezone data' + + git push origin HEAD:tzdata/update-${branch} diff --git a/tools/format_tzdata.py b/tools/format_tzdata.py index 609a9218bf..e44d0f588e 100755 --- a/tools/format_tzdata.py +++ b/tools/format_tzdata.py @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +# /// script +# dependencies = [ +# "tzdata", +# ] +# requires-python = ">=3.12" +# /// # this script refreshes world timezone definitions in # cores/esp8266/TZ.h @@ -7,167 +13,414 @@ import argparse import contextlib +import itertools import datetime -import mmap -import os import pathlib -import re import sys -import pathlib + +from dataclasses import dataclass +from operator import attrgetter from importlib import resources +from importlib.resources.abc import Traversable + +from collections.abc import Iterable, Callable + +import typing +from typing import TextIO, Self import tzdata # https://tzdata.readthedocs.io/en/latest/ -def known_alias(entry): - swaps = { - "Europe/Zaporozhye": "Europe/Zaporizhzhia", - "Europe/Uzhgorod": "Europe/Uzhhorod", - } +class NotZoneInfo(Exception): + pass - return swaps.get(entry) +def tz_from_zonefile(zonefile: Traversable) -> str: + with zonefile.open("rb") as f: + magic = f.read(4) + if magic != b"TZif": + raise NotZoneInfo() -def fix_name(name): - swaps = [["-", "m"], ["+", "p"], ["/", "_"]] + *_, tail = f.readlines() + tz = tail.strip() + tz = tz.decode("ascii") - for lhs, rhs in swaps: - name = name.replace(lhs, rhs) + return tz - return name +@dataclass(frozen=True) +class Tz: + name: str + value: str -def utc_alias(zone): - return zone in ( - "Universal", - "UTC", - "UCT", - "Zulu", - "GMT", - "GMT+0", - "GMT-0", - "GMT0", - "Greenwich", - ) +@dataclass(frozen=True) +class File: + """ + Newline-delimited file listing IANA keys. Zone information files listed MUST exist. + """ -def tzdata_resource_from_name(name): - pair = name.rsplit("/", 1) - if len(pair) == 1: - return resources.files("tzdata.zoneinfo") / pair[0] + file: Traversable - return resources.files(f'tzdata.zoneinfo.{pair[0].replace("/", ".")}') / pair[1] + @classmethod + def fromString(cls, s: str) -> Self: + return cls(pathlib.Path(s)) -def make_zones_list(f): - return [zone.strip() for zone in f.readlines()] +def multiple_from_file(root: Traversable, zones: File) -> Iterable[Tz]: + with zones.file.open("r") as f: + names = [name.strip() for name in f.readlines()] + for name in names: + zonefile = root.joinpath(name) + tz = tz_from_zonefile(zonefile) + yield Tz(name, tz) -def make_zones(args): - out = [] - for zone in make_zones_list(args.zones): - if args.root: - target = args.root / zone - else: - target = tzdata_resource_from_name(zone) +@dataclass(frozen=True) +class Area: + """ + Area name of one or multiple IANA keys. + --area Europe - with target.open("rb") as f: - magic = f.read(4) - if magic != b"TZif": - continue + This source is ignored when given an invalid area name. + --area DoesntExist""" + + name: str - m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) - newline = m.rfind(b"\n", 0, len(m) - 1) - if newline < 0: - continue - m.seek(newline + 1) - tz = m.readline().strip() - tz = tz.decode("ascii") +def maybe_multiple_for_area(root: Traversable, area: Area) -> list[Tz]: + out: list[Tz] = [] + root = root.joinpath(area.name) - if alias := known_alias(zone): - out.append([alias, tz]) + if root.is_dir(): + for location in root.iterdir(): + if location.is_dir(): + continue - out.append([zone, tz]) + try: + tz = tz_from_zonefile(location) + out.append(Tz(f"{area.name}/{location.name}", tz)) + except NotZoneInfo: + pass - out.sort(key=lambda x: x[0]) return out -def markdown(zones): - utcs = [] - rows = [] +def split_kv(s: str) -> tuple[str, str]: + key, _, val = s.partition("=") + return (key, val) - for name, value in zones: - if utc_alias(name): - utcs.append(name) - continue - rows.append(f"|{name}|`{value}`|") +@dataclass(frozen=True) +class Link: + """ + Named link to an existing IANA key. + --link Foo/Bar=Europe/London - print("|Name|Value|") - print("|---|---|") - for name in utcs: - print(f"|{name}|UTC0|") + This source is ignored if named zone information file already exists. + --link Europe/Isle_of_Man=Europe/London + + This source is ignored if target zone information file doesn't exist. + --link Europe/Isle_of_Man=Doesnt/Exist + + Intended to be combined with either --file or --key""" + + name: str + target: str + + @classmethod + def fromString(cls, s: str) -> Self: + return cls(*split_kv(s)) + + +def maybe_one_link(root: Traversable, link: Link) -> tuple[Tz] | tuple[()]: + if not root.joinpath(link.name).is_file() and root.joinpath(link.target).is_file(): + tz = tz_from_zonefile(root.joinpath(link.target)) + return (Tz(link.name, tz),) + + return tuple() - last = "" - for row in rows: - prefix, _, _ = row.partition("/") - if last != prefix: - last = prefix - print("|||") - print(row) - print() - print("---") - print() - print(f"*Generated with *{tzdata.IANA_VERSION=} {tzdata.__version__=}*") +@dataclass(frozen=True) +class Key: + """ + IANA key name. This source is ignored if zone information file doesn't exist.""" -def header(zones): + name: str + + +def maybe_one_key(root: Traversable, key: Key) -> tuple[Tz] | tuple[()]: + if root.joinpath(key.name).is_file(): + tz = tz_from_zonefile(root.joinpath(key.name)) + return (Tz(key.name, tz),) + + return tuple() + + +@dataclass(frozen=True) +class Raw: + """ + Inject a named TZ variable.""" + + name: str + value: str + + @classmethod + def fromString(cls, s: str) -> Self: + return cls(*split_kv(s)) + + +def safe_macro_name(name: str) -> str: + swaps = [["-", "m"], ["+", "p"], ["/", "_"]] + + for lhs, rhs in swaps: + name = name.replace(lhs, rhs) + + return name + + +def header(info: Iterable[Tz]): print("// ! ! ! DO NOT EDIT, AUTOMATICALLY GENERATED ! ! !") print(f"// File created {datetime.datetime.now(tz=datetime.timezone.utc)}") print(f"// Based on IANA database {tzdata.IANA_VERSION}") - print(f"// Re-run /tools/{sys.argv[0]} to update") + print( + f"// Re-run /tools/{pathlib.Path(__file__).name} to update" + ) print() print("#pragma once") print() - for name, value in zones: - print(f'#define TZ_{fix_name(name)}\tPSTR("{value}")') + for tz in info: + print(f'#define TZ_{safe_macro_name(tz.name)}\tPSTR("{tz.value}")') + + +UTC_NAMES: tuple[str, ...] = ( + "Universal", + "UTC", + "UCT", + "Zulu", + "GMT", + "GMT+0", + "GMT-0", + "GMT0", + "Greenwich", +) + + +def markdown_group(tz: Tz) -> str: + if tz.name in UTC_NAMES: + return "Universal Coordinated Time" + + if not "/" in tz.name: + return "Other" + + prefix, _, _ = tz.name.partition("/") + return prefix + + +def markdown(info: Iterable[Tz]): + print(f"> [!NOTE]") + print(f"> Based on IANA database {tzdata.IANA_VERSION}") + print() + print(f"> [!TIP]") + print(f"> Re-run {pathlib.Path(__file__).name} to update") + print() + print("---") + print() + + info = sorted(info, key=markdown_group) + grouped = itertools.groupby(info, key=markdown_group) + + last = "" + for heading, group in grouped: + if heading != last: + print(f"# {heading}") + print() + last = heading + print("|Name|Value|") + print("|---|---|") + for tz in group: + print(f"|{tz.name}|`{tz.value}`|") + print() + + if last == "": + print() + + +FORMATTERS = { + "header": header, + "markdown": markdown, +} + +type Source = File | Link | Key | Raw + + +DEFAULT_SOURCES: tuple[Source, ...] = ( + File(resources.files("tzdata").joinpath("zones")), + Link("Europe/Zaporizhzhia", "Europe/Zaporozhye"), + Link("Europe/Uzhhorod", "Europe/Uzhgorod"), +) + + +def format_argparse_source(src: Source): + match src: + case File() as file: + return f"--file {file.file}" + case Area() as area: + return f"--area {area.name}" + case Link() as link: + return f"--link {link.name}={link.target}" + case Key() as key: + return f"--key {key.name}" + case Raw() as raw: + return f"--raw {raw.name}={raw.value}" + case _: + raise ValueError(f"Unknown type {type(src)}") + + +# default=... is awkward to use with groups of arguments +def format_argparse_default_sources(sources: Iterable[Source]) -> str: + return "\n".join(f" `{format_argparse_source(src)}`" for src in sources) + + +class Formatter( + argparse.ArgumentDefaultsHelpFormatter, + argparse.RawTextHelpFormatter, +): + pass + + +VERSION = f""" +version: + {tzdata.IANA_VERSION=} + {tzdata.__version__=} +""" + +EPILOG = f""" +default sources: +{format_argparse_default_sources(DEFAULT_SOURCES)} + +{VERSION} +""" if __name__ == "__main__": parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, + epilog=EPILOG, + formatter_class=Formatter, ) - parser.add_argument( - "--output", - type=argparse.FileType("w", encoding="utf-8"), - default=sys.stdout, + + sources_group = parser.add_argument_group("iana zone key sources") + sources_group.add_argument( + "--file", + type=File.fromString, + metavar="FILE", + dest="sources", + action="append", + help=File.__doc__, + default=argparse.SUPPRESS, + ) + + sources_group.add_argument( + "--area", + type=Area, + metavar="NAME", + dest="sources", + action="append", + help=Area.__doc__, + default=argparse.SUPPRESS, + ) + + sources_group.add_argument( + "--link", + type=Link.fromString, + metavar="NAME=TARGET", + dest="sources", + action="append", + help=Link.__doc__, + default=argparse.SUPPRESS, + ) + + sources_group.add_argument( + "--key", + type=Key, + metavar="NAME", + dest="sources", + action="append", + help=Key.__doc__, + default=argparse.SUPPRESS, + ) + + sources_group.add_argument( + "--raw", + type=Raw.fromString, + metavar="NAME=TZ", + dest="sources", + action="append", + help=Raw.__doc__, + default=argparse.SUPPRESS, ) + parser.add_argument( "--format", + choices=tuple(FORMATTERS.keys()), default="header", - choices=["header", "markdown"], - ) - parser.add_argument( - "--zones", - type=argparse.FileType("r", encoding="utf-8"), - help="Zone names file, one per line", - default=os.path.join(os.path.dirname(tzdata.__file__), "zones"), + help="Choose output formatter", ) + parser.add_argument( "--root", help="Where do we get raw zoneinfo files from", type=pathlib.Path, + default=resources.files("tzdata.zoneinfo"), ) - args = parser.parse_args() - zones = make_zones(args) + parser.add_argument( + "--version", + action="version", + version=VERSION, + ) - with contextlib.redirect_stdout(args.output): - if args.format == "markdown": - markdown(zones) - elif args.format == "header": - header(zones) + parser.add_argument( + "output", + type=str, + nargs="?", + default="-", + ) + + args = parser.parse_args() + if not getattr(args, "sources", None): + args.sources = DEFAULT_SOURCES + + root: Traversable = args.root + mapping: dict[str, Tz] = {} + + def update(items: Iterable[Tz]): + for item in items: + if not item.name in mapping: + mapping[item.name] = item + + for src in args.sources: + match src: + case File() as file: + update(multiple_from_file(root, file)) + case Area() as area: + update(maybe_multiple_for_area(root, area)) + case Link() as link: + update(maybe_one_link(root, link)) + case Key() as key: + update(maybe_one_key(root, key)) + case Raw() as raw: + update(Tz(raw.name, raw.value)) + + info = sorted(mapping.values(), key=attrgetter("name")) + + def maybe_stdout(s: str) -> TextIO: + if s == "-": + return sys.stdout + + return pathlib.Path(s).open("w") + + with contextlib.redirect_stdout(maybe_stdout(args.output)): + FORMATTERS[args.format](info) diff --git a/tools/format_tzdata.py.lock b/tools/format_tzdata.py.lock new file mode 100644 index 0000000000..162733ac0e --- /dev/null +++ b/tools/format_tzdata.py.lock @@ -0,0 +1,15 @@ +version = 1 +revision = 5 +requires-python = ">=3.12" + +[manifest] +requirements = [{ name = "tzdata" }] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +]