aboutsummaryrefslogtreecommitdiff
path: root/tools/python/timezone/common.py
blob: 9e2aea5c2ac2404f08f03cc9de4ffbacbbcfbabb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import json
import zoneinfo
from pathlib import Path
from typing import Set, Optional

OM_ROOT = Path(__file__).parent.parent.parent.parent
COUNTRIES_META_FILE_PATH = OM_ROOT / "data" / "countries_meta.txt"
TIMEZONE_INFO_FILE_PATH = OM_ROOT / "data" / "generator" / "timezone" / "timezone_info.json"


def get_countries_meta_timezones(data: dict = None) -> Set[str]:
    if data is None:
        data = json.loads(COUNTRIES_META_FILE_PATH.read_text(encoding="utf-8"))
    timezones = set()
    if isinstance(data, dict):
        for key, value in data.items():
            if key == "timezone":
                timezones.add(value)
            timezones.update(get_countries_meta_timezones(value))
    elif isinstance(data, list):
        for item in data:
            timezones.update(get_countries_meta_timezones(item))
    return timezones


def get_local_tzdb_version() -> Optional[str]:
    for tzdb_path in zoneinfo.TZPATH:
        version_file = Path(tzdb_path) / "+VERSION"  # Mac OS
        if version_file.exists():
            return version_file.read_text().strip()
        version_file = Path(tzdb_path) / "tzdata.zi"  # Ubuntu
        if version_file.exists():
            with open(version_file, "r") as f:
                header = f.readline().strip();
                if header.startswith("# version "):
                    return header[10:]
    return None