ยปCore Development>Code coverage>Tools/tz/zdump.py

Python code coverage for Tools/tz/zdump.py

#countcontent
1n/aimport sys
2n/aimport os
3n/aimport struct
4n/afrom array import array
5n/afrom collections import namedtuple
6n/afrom datetime import datetime, timedelta
7n/a
8n/attinfo = namedtuple('ttinfo', ['tt_gmtoff', 'tt_isdst', 'tt_abbrind'])
9n/a
10n/aclass TZInfo:
11n/a def __init__(self, transitions, type_indices, ttis, abbrs):
12n/a self.transitions = transitions
13n/a self.type_indices = type_indices
14n/a self.ttis = ttis
15n/a self.abbrs = abbrs
16n/a
17n/a @classmethod
18n/a def fromfile(cls, fileobj):
19n/a if fileobj.read(4).decode() != "TZif":
20n/a raise ValueError("not a zoneinfo file")
21n/a fileobj.seek(20)
22n/a header = fileobj.read(24)
23n/a tzh = (tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,
24n/a tzh_timecnt, tzh_typecnt, tzh_charcnt) = struct.unpack(">6l", header)
25n/a transitions = array('i')
26n/a transitions.fromfile(fileobj, tzh_timecnt)
27n/a if sys.byteorder != 'big':
28n/a transitions.byteswap()
29n/a
30n/a type_indices = array('B')
31n/a type_indices.fromfile(fileobj, tzh_timecnt)
32n/a
33n/a ttis = []
34n/a for i in range(tzh_typecnt):
35n/a ttis.append(ttinfo._make(struct.unpack(">lbb", fileobj.read(6))))
36n/a
37n/a abbrs = fileobj.read(tzh_charcnt)
38n/a
39n/a self = cls(transitions, type_indices, ttis, abbrs)
40n/a self.tzh = tzh
41n/a
42n/a return self
43n/a
44n/a def dump(self, stream, start=None, end=None):
45n/a for j, (trans, i) in enumerate(zip(self.transitions, self.type_indices)):
46n/a utc = datetime.utcfromtimestamp(trans)
47n/a tti = self.ttis[i]
48n/a lmt = datetime.utcfromtimestamp(trans + tti.tt_gmtoff)
49n/a abbrind = tti.tt_abbrind
50n/a abbr = self.abbrs[abbrind:self.abbrs.find(0, abbrind)].decode()
51n/a if j > 0:
52n/a prev_tti = self.ttis[self.type_indices[j - 1]]
53n/a shift = " %+g" % ((tti.tt_gmtoff - prev_tti.tt_gmtoff) / 3600)
54n/a else:
55n/a shift = ''
56n/a print("%s UTC = %s %-5s isdst=%d" % (utc, lmt, abbr, tti[1]) + shift, file=stream)
57n/a
58n/a @classmethod
59n/a def zonelist(cls, zonedir='/usr/share/zoneinfo'):
60n/a zones = []
61n/a for root, _, files in os.walk(zonedir):
62n/a for f in files:
63n/a p = os.path.join(root, f)
64n/a with open(p, 'rb') as o:
65n/a magic = o.read(4)
66n/a if magic == b'TZif':
67n/a zones.append(p[len(zonedir) + 1:])
68n/a return zones
69n/a
70n/aif __name__ == '__main__':
71n/a if len(sys.argv) < 2:
72n/a zones = TZInfo.zonelist()
73n/a for z in zones:
74n/a print(z)
75n/a sys.exit()
76n/a filepath = sys.argv[1]
77n/a if not filepath.startswith('/'):
78n/a filepath = os.path.join('/usr/share/zoneinfo', filepath)
79n/a with open(filepath, 'rb') as fileobj:
80n/a tzi = TZInfo.fromfile(fileobj)
81n/a tzi.dump(sys.stdout)