Debian Codegraph @

Lib/zoneinfo/_common.py

raw
1 import struct
2
3
4 def load_tzdata(key):
5 from importlib import resources
6
7 components = key.split("/")
8 package_name = ".".join(["tzdata.zoneinfo"] + components[:-1])
9 resource_name = components[-1]
10
11 try:
12 path = resources.files(package_name).joinpath(resource_name)
13 # gh-85702: Prevent PermissionError on Windows
14 if path.is_dir():
15 raise IsADirectoryError
16 return path.open("rb")
17 except (ImportError, FileNotFoundError, UnicodeEncodeError, IsADirectoryError):
18 # There are four types of exception that can be raised that all amount
19 # to "we cannot find this key":
20 #
21 # ImportError: If package_name doesn't exist (e.g. if tzdata is not
22 # installed, or if there's an error in the folder name like
23 # Amrica/New_York)
24 # FileNotFoundError: If resource_name doesn't exist in the package
25 # (e.g. Europe/Krasnoy)
26 # UnicodeEncodeError: If package_name or resource_name are not UTF-8,
27 # such as keys containing a surrogate character.
28 # IsADirectoryError: If package_name without a resource_name specified.
29 raise ZoneInfoNotFoundError(f"No time zone found with key {key}")
30
31
32 def load_data(fobj):
33 header = _TZifHeader.from_file(fobj)
34
35 if header.version == 1:
36 time_size = 4
37 time_type = "l"
38 else:
39 # Version 2+ has 64-bit integer transition times
40 time_size = 8
41 time_type = "q"
42
43 # Version 2+ also starts with a Version 1 header and data, which
44 # we need to skip now
45 skip_bytes = (
46 header.timecnt * 5 # Transition times and types
47 + header.typecnt * 6 # Local time type records
48 + header.charcnt # Time zone designations
49 + header.leapcnt * 8 # Leap second records
50 + header.isstdcnt # Standard/wall indicators
51 + header.isutcnt # UT/local indicators
52 )
53
54 fobj.seek(skip_bytes, 1)
55
56 # Now we need to read the second header, which is not the same
57 # as the first
58 header = _TZifHeader.from_file(fobj)
59
60 typecnt = header.typecnt
61 timecnt = header.timecnt
62 charcnt = header.charcnt
63
64 # The data portion starts with timecnt transitions and indices
65 if timecnt:
66 trans_list_utc = struct.unpack(
67 f">{timecnt}{time_type}", fobj.read(timecnt * time_size)
68 )
69 trans_idx = struct.unpack(f">{timecnt}B", fobj.read(timecnt))
70 else:
71 trans_list_utc = ()
72 trans_idx = ()
73
74 # Read the ttinfo struct, (utoff, isdst, abbrind)
75 if typecnt:
76 utcoff, isdst, abbrind = zip(
77 *(struct.unpack(">lbb", fobj.read(6)) for i in range(typecnt))
78 )
79 else:
80 utcoff = ()
81 isdst = ()
82 abbrind = ()
83
84 # Now read the abbreviations. They are null-terminated strings, indexed
85 # not by position in the array but by position in the unsplit
86 # abbreviation string. I suppose this makes more sense in C, which uses
87 # null to terminate the strings, but it's inconvenient here...
88 abbr_vals = {}
89 abbr_chars = fobj.read(charcnt)
90
91 def get_abbr(idx):
92 # Gets a string starting at idx and running until the next \x00
93 #
94 # We cannot pre-populate abbr_vals by splitting on \x00 because there
95 # are some zones that use subsets of longer abbreviations, like so:
96 #
97 # LMT\x00AHST\x00HDT\x00
98 #
99 # Where the idx to abbr mapping should be:
100 #
101 # {0: "LMT", 4: "AHST", 5: "HST", 9: "HDT"}
102 if idx not in abbr_vals:
103 span_end = abbr_chars.find(b"\x00", idx)
104 abbr_vals[idx] = abbr_chars[idx:span_end].decode()
105
106 return abbr_vals[idx]
107
108 abbr = tuple(get_abbr(idx) for idx in abbrind)
109
110 # The remainder of the file consists of leap seconds (currently unused) and
111 # the standard/wall and ut/local indicators, which are metadata we don't need.
112 # In version 2 files, we need to skip the unnecessary data to get at the TZ string:
113 if header.version >= 2:
114 # Each leap second record has size (time_size + 4)
115 skip_bytes = header.isutcnt + header.isstdcnt + header.leapcnt * 12
116 fobj.seek(skip_bytes, 1)
117
118 c = fobj.read(1) # Should be \n
119 assert c == b"\n", c
120
121 line = fobj.readline()
122 if not line.endswith(b"\n"):
123 raise ValueError("Invalid TZif file: unexpected end of file")
124 tz_str = line.rstrip(b"\n")
125 else:
126 tz_str = None
127
128 return trans_idx, trans_list_utc, utcoff, isdst, abbr, tz_str
129
130
131 class _TZifHeader:
132 __slots__ = [
133 "version",
134 "isutcnt",
135 "isstdcnt",
136 "leapcnt",
137 "timecnt",
138 "typecnt",
139 "charcnt",
140 ]
141
142 def __init__(self, *args):
143 for attr, val in zip(self.__slots__, args, strict=True):
144 setattr(self, attr, val)
145
146 @classmethod
147 def from_file(cls, stream):
148 # The header starts with a 4-byte "magic" value
149 if stream.read(4) != b"TZif":
150 raise ValueError("Invalid TZif file: magic not found")
151
152 _version = stream.read(1)
153 if _version == b"\x00":
154 version = 1
155 else:
156 version = int(_version)
157 stream.read(15)
158
159 args = (version,)
160
161 # Slots are defined in the order that the bytes are arranged
162 args = args + struct.unpack(">6l", stream.read(24))
163
164 return cls(*args)
165
166
167 class ZoneInfoNotFoundError(KeyError):
168 """Exception raised when a ZoneInfo key is not found."""