/usr/lib/python2.7/dist-packages/zonal/tzconvert.py is in python-pycalendar 1:2.1~git20161130.0.e68e150-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | #!/usr/bin/env python
##
# Copyright (c) 2007-2013 Cyrus Daboo. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
from __future__ import with_statement
from __future__ import print_function
from pycalendar.icalendar.calendar import Calendar
from xml.etree.cElementTree import ParseError as XMLParseError
import cStringIO as StringIO
import getopt
import os
import rule
import sys
import tarfile
import urllib
import xml.etree.cElementTree as XML
import zone
"""
Classes to parse a tzdata files and generate VTIMEZONE data.
"""
__all__ = (
"tzconvert",
)
class tzconvert(object):
def __init__(self, verbose=False):
self.rules = {}
self.zones = {}
self.links = {}
self.verbose = verbose
def getZoneNames(self):
return set(self.zones.keys())
def parse(self, file):
try:
with open(file, "r") as f:
ctr = 0
for line in f:
ctr += 1
line = line[:-1]
while True:
if line.startswith("#") or len(line) == 0:
break
elif line.startswith("Rule"):
self.parseRule(line)
break
elif line.startswith("Zone"):
line = self.parseZone(line, f)
if line is None:
break
elif line.startswith("Link"):
self.parseLink(line)
break
elif len(line.strip()) != 0:
assert False, "Could not parse line %d from tzconvert file: '%s'" % (ctr, line,)
else:
break
except:
print("Failed to parse file %s" % (file,))
raise
def parseRule(self, line):
ruleitem = rule.Rule()
ruleitem.parse(line)
self.rules.setdefault(ruleitem.name, rule.RuleSet()).rules.append(ruleitem)
def parseZone(self, line, f):
os = StringIO.StringIO()
os.write(line)
last_line = None
for nextline in f:
nextline = nextline[:-1]
if nextline.startswith("\t") or nextline.startswith(" "):
os.write("\n")
os.write(nextline)
elif nextline.startswith("#") or len(nextline) == 0:
continue
else:
last_line = nextline
break
zoneitem = zone.Zone()
zoneitem.parse(os.getvalue())
self.zones[zoneitem.name] = zoneitem
return last_line
def parseLink(self, line):
splits = line.split()
linkFrom = splits[1]
linkTo = splits[2]
self.links[linkTo] = linkFrom
def parseWindowsAliases(self, aliases):
try:
with open(aliases) as xmlfile:
xmlroot = XML.ElementTree(file=xmlfile).getroot()
except (IOError, XMLParseError):
raise ValueError("Unable to open or read windows alias file: {}".format(aliases))
# Extract the mappings
try:
for elem in xmlroot.findall("./windowsZones/mapTimezones/mapZone"):
if elem.get("territory", "") == "001":
if elem.get("other") not in self.links:
self.links[elem.get("other")] = elem.get("type")
else:
print("Ignoring duplicate Windows alias: {}".format(elem.get("other")))
except (ValueError, KeyError):
raise ValueError("Unable to parse windows alias file: {}".format(aliases))
def expandZone(self, zonename, minYear, maxYear=2018):
"""
Expand a zones transition dates up to the specified year.
"""
zone = self.zones[zonename]
expanded = zone.expand(self.rules, minYear, maxYear)
return [(item[0], item[1], item[2],) for item in expanded]
def vtimezones(self, minYear, maxYear=2018, filterzones=None):
"""
Generate iCalendar data for all VTIMEZONEs or just those specified
"""
cal = Calendar()
for tzzone in self.zones.itervalues():
if filterzones and tzzone.name not in filterzones:
continue
vtz = tzzone.vtimezone(cal, self.rules, minYear, maxYear)
cal.addComponent(vtz)
return cal.getText()
def generateZoneinfoFiles(self, outputdir, minYear, maxYear=2018, links=True, windowsAliases=None, filterzones=None):
# Empty current directory
try:
for root, dirs, files in os.walk(outputdir, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
except OSError:
pass
for tzzone in self.zones.itervalues():
if filterzones and tzzone.name not in filterzones:
continue
cal = Calendar()
vtz = tzzone.vtimezone(cal, self.rules, minYear, maxYear)
cal.addComponent(vtz)
icsdata = cal.getText()
fpath = os.path.join(outputdir, tzzone.name + ".ics")
if not os.path.exists(os.path.dirname(fpath)):
os.makedirs(os.path.dirname(fpath))
with open(fpath, "w") as f:
f.write(icsdata)
if self.verbose:
print("Write path: %s" % (fpath,))
if links:
if windowsAliases is not None:
self.parseWindowsAliases(windowsAliases)
link_list = []
for linkTo, linkFrom in sorted(self.links.iteritems(), key=lambda x: x[0]):
# Check for existing output file
fromPath = os.path.join(outputdir, linkFrom + ".ics")
if not os.path.exists(fromPath):
print("Missing link from: %s to %s" % (linkFrom, linkTo,))
continue
with open(fromPath) as f:
icsdata = f.read()
icsdata = icsdata.replace(linkFrom, linkTo)
toPath = os.path.join(outputdir, linkTo + ".ics")
if not os.path.exists(os.path.dirname(toPath)):
os.makedirs(os.path.dirname(toPath))
with open(toPath, "w") as f:
f.write(icsdata)
if self.verbose:
print("Write link: %s" % (linkTo,))
link_list.append("%s\t%s" % (linkTo, linkFrom,))
# Generate link mapping file
linkPath = os.path.join(outputdir, "links.txt")
with open(linkPath, "w") as f:
f.write("\n".join(link_list))
def usage(error_msg=None):
if error_msg:
print(error_msg)
print("""Usage: tzconvert [options] [DIR]
Options:
-h Print this help and exit
--prodid PROD-ID string to use
--start Start year
--end End year
Arguments:
DIR Directory containing an Olson tzdata directory to read, also
where zoneinfo data will be written
Description:
This utility convert Olson-style timezone data in iCalendar.
VTIMEZONE objects, one .ics file per-timezone.
""")
if error_msg:
raise ValueError(error_msg)
else:
sys.exit(0)
if __name__ == '__main__':
# Set the PRODID value used in generated iCalendar data
prodid = "-//mulberrymail.com//Zonal//EN"
rootdir = "../../temp"
startYear = 1800
endYear = 2018
windowsAliases = None
options, args = getopt.getopt(sys.argv[1:], "h", ["prodid=", "root=", "start=", "end=", "windows="])
for option, value in options:
if option == "-h":
usage()
elif option == "--prodid":
prodid = value
elif option == "--root":
rootdir = os.path.expanduser(value)
elif option == "--start":
startYear = int(value)
elif option == "--end":
endYear = int(value)
elif option == "--windows":
windowsAliases = os.path.expanduser(value)
else:
usage("Unrecognized option: %s" % (option,))
if not os.path.exists(rootdir):
os.makedirs(rootdir)
zonedir = os.path.join(rootdir, "tzdata")
if not os.path.exists(zonedir):
print("Downloading and extracting IANA timezone database")
os.mkdir(zonedir)
iana = "https://www.iana.org/time-zones/repository/tzdata-latest.tar.gz"
data = urllib.urlretrieve(iana)
print("Extract data at: %s" % (data[0]))
with tarfile.open(data[0], "r:gz") as t:
t.extractall(zonedir)
if windowsAliases is None:
windowsAliases = os.path.join(rootdir, "windowsZones.xml")
if not os.path.exists(windowsAliases):
print("Downloading Unicode database")
unicode = "http://unicode.org/repos/cldr/tags/latest/common/supplemental/windowsZones.xml"
data = urllib.urlretrieve(unicode, windowsAliases)
Calendar.sProdID = prodid
zonedir = os.path.join(rootdir, "tzdata")
zonefiles = (
"northamerica",
"southamerica",
"europe",
"africa",
"asia",
"australasia",
"antarctica",
"etcetera",
"backward",
)
parser = tzconvert(verbose=True)
for file in zonefiles:
parser.parse(os.path.join(zonedir, file))
parser.generateZoneinfoFiles(
os.path.join(rootdir, "zoneinfo"),
startYear,
endYear,
windowsAliases=windowsAliases,
filterzones=(
# "America/Montevideo",
# "Europe/Paris",
# "Africa/Cairo",
)
)
|