<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[13621] PyCalendar/trunk/src/zonal/tzconvert.py</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/13621">13621</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2014-06-09 13:26:58 -0700 (Mon, 09 Jun 2014)</dd>
</dl>

<h3>Log Message</h3>
<pre>Support automatic download of the latest IANA tz db during conversion. Also, add in Unicode Windows' timezone aliases
into the set of links that IANA tz db has - that can be automatically downloaded too.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#PyCalendartrunksrczonaltzconvertpy">PyCalendar/trunk/src/zonal/tzconvert.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="PyCalendartrunksrczonaltzconvertpy"></a>
<div class="modfile"><h4>Modified: PyCalendar/trunk/src/zonal/tzconvert.py (13620 => 13621)</h4>
<pre class="diff"><span>
<span class="info">--- PyCalendar/trunk/src/zonal/tzconvert.py        2014-06-09 16:25:14 UTC (rev 13620)
+++ PyCalendar/trunk/src/zonal/tzconvert.py        2014-06-09 20:26:58 UTC (rev 13621)
</span><span class="lines">@@ -16,14 +16,18 @@
</span><span class="cx"> ##
</span><span class="cx"> 
</span><span class="cx"> from __future__ import with_statement
</span><ins>+from __future__ import print_function
</ins><span class="cx"> 
</span><del>-from difflib import unified_diff
</del><span class="cx"> from pycalendar.icalendar.calendar import Calendar
</span><ins>+from xml.etree.cElementTree import ParseError as XMLParseError
</ins><span class="cx"> import cStringIO as StringIO
</span><span class="cx"> import getopt
</span><span class="cx"> import os
</span><span class="cx"> import rule
</span><span class="cx"> import sys
</span><ins>+import tarfile
+import urllib
+import xml.etree.cElementTree as XML
</ins><span class="cx"> import zone
</span><span class="cx"> 
</span><span class="cx"> &quot;&quot;&quot;
</span><span class="lines">@@ -72,7 +76,7 @@
</span><span class="cx">                     else:
</span><span class="cx">                         break
</span><span class="cx">         except:
</span><del>-            print &quot;Failed to parse file %s&quot; % (file,)
</del><ins>+            print(&quot;Failed to parse file %s&quot; % (file,))
</ins><span class="cx">             raise
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="lines">@@ -112,6 +116,26 @@
</span><span class="cx">         self.links[linkTo] = linkFrom
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    def parseWindowsAliases(self, aliases):
+
+        try:
+            xmlfile = open(aliases)
+            xmlroot = XML.ElementTree(file=xmlfile).getroot()
+        except (IOError, XMLParseError):
+            raise ValueError(&quot;Unable to open or read windows alias file: {}&quot;.format(aliases))
+
+        # Extract the mappings
+        try:
+            for elem in xmlroot.findall(&quot;./windowsZones/mapTimezones/mapZone&quot;):
+                if elem.get(&quot;territory&quot;, &quot;&quot;) == &quot;001&quot;:
+                    if elem.get(&quot;other&quot;) not in self.links:
+                        self.links[elem.get(&quot;other&quot;)] = elem.get(&quot;type&quot;)
+                    else:
+                        print(&quot;Ignoring duplicate Windows alias: {}&quot;.format(elem.get(&quot;other&quot;)))
+        except (ValueError, KeyError):
+            raise ValueError(&quot;Unable to parse windows alias file: {}&quot;.format(aliases))
+
+
</ins><span class="cx">     def expandZone(self, zonename, minYear, maxYear=2018):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Expand a zones transition dates up to the specified year.
</span><span class="lines">@@ -136,7 +160,7 @@
</span><span class="cx">         return cal.getText()
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    def generateZoneinfoFiles(self, outputdir, minYear, maxYear=2018, links=True, filterzones=None):
</del><ins>+    def generateZoneinfoFiles(self, outputdir, minYear, maxYear=2018, links=True, windowsAliases=None, filterzones=None):
</ins><span class="cx"> 
</span><span class="cx">         # Empty current directory
</span><span class="cx">         try:
</span><span class="lines">@@ -162,16 +186,19 @@
</span><span class="cx">             with open(fpath, &quot;w&quot;) as f:
</span><span class="cx">                 f.write(icsdata)
</span><span class="cx">             if self.verbose:
</span><del>-                print &quot;Write path: %s&quot; % (fpath,)
</del><ins>+                print(&quot;Write path: %s&quot; % (fpath,))
</ins><span class="cx"> 
</span><span class="cx">         if links:
</span><ins>+            if windowsAliases is not None:
+                self.parseWindowsAliases(windowsAliases)
+
</ins><span class="cx">             link_list = []
</span><del>-            for linkTo, linkFrom in self.links.iteritems():
</del><ins>+            for linkTo, linkFrom in sorted(self.links.iteritems(), key=lambda x: x[0]):
</ins><span class="cx"> 
</span><span class="cx">                 # Check for existing output file
</span><span class="cx">                 fromPath = os.path.join(outputdir, linkFrom + &quot;.ics&quot;)
</span><span class="cx">                 if not os.path.exists(fromPath):
</span><del>-                    print &quot;Missing link from: %s to %s&quot; % (linkFrom, linkTo,)
</del><ins>+                    print(&quot;Missing link from: %s to %s&quot; % (linkFrom, linkTo,))
</ins><span class="cx">                     continue
</span><span class="cx"> 
</span><span class="cx">                 with open(fromPath) as f:
</span><span class="lines">@@ -184,7 +211,7 @@
</span><span class="cx">                 with open(toPath, &quot;w&quot;) as f:
</span><span class="cx">                     f.write(icsdata)
</span><span class="cx">                 if self.verbose:
</span><del>-                    print &quot;Write link: %s&quot; % (linkTo,)
</del><ins>+                    print(&quot;Write link: %s&quot; % (linkTo,))
</ins><span class="cx"> 
</span><span class="cx">                 link_list.append(&quot;%s\t%s&quot; % (linkTo, linkFrom,))
</span><span class="cx"> 
</span><span class="lines">@@ -196,9 +223,9 @@
</span><span class="cx"> 
</span><span class="cx"> def usage(error_msg=None):
</span><span class="cx">     if error_msg:
</span><del>-        print error_msg
</del><ins>+        print(error_msg)
</ins><span class="cx"> 
</span><del>-    print &quot;&quot;&quot;Usage: tzconvert [options] [DIR]
</del><ins>+    print(&quot;&quot;&quot;Usage: tzconvert [options] [DIR]
</ins><span class="cx"> Options:
</span><span class="cx">     -h            Print this help and exit
</span><span class="cx">     --prodid      PROD-ID string to use
</span><span class="lines">@@ -213,7 +240,7 @@
</span><span class="cx">     This utility convert Olson-style timezone data in iCalendar.
</span><span class="cx">     VTIMEZONE objects, one .ics file per-timezone.
</span><span class="cx"> 
</span><del>-&quot;&quot;&quot;
</del><ins>+&quot;&quot;&quot;)
</ins><span class="cx"> 
</span><span class="cx">     if error_msg:
</span><span class="cx">         raise ValueError(error_msg)
</span><span class="lines">@@ -225,11 +252,12 @@
</span><span class="cx"> 
</span><span class="cx">     # Set the PRODID value used in generated iCalendar data
</span><span class="cx">     prodid = &quot;-//mulberrymail.com//Zonal//EN&quot;
</span><del>-    rootdir = &quot;../../stuff/temp&quot;
</del><ins>+    rootdir = &quot;../../temp&quot;
</ins><span class="cx">     startYear = 1800
</span><span class="cx">     endYear = 2018
</span><ins>+    windowsAliases = None
</ins><span class="cx"> 
</span><del>-    options, args = getopt.getopt(sys.argv[1:], &quot;h&quot;, [&quot;prodid=&quot;, &quot;root=&quot;, &quot;start=&quot;, &quot;end=&quot;, ])
</del><ins>+    options, args = getopt.getopt(sys.argv[1:], &quot;h&quot;, [&quot;prodid=&quot;, &quot;root=&quot;, &quot;start=&quot;, &quot;end=&quot;, &quot;windows=&quot;])
</ins><span class="cx"> 
</span><span class="cx">     for option, value in options:
</span><span class="cx">         if option == &quot;-h&quot;:
</span><span class="lines">@@ -237,20 +265,35 @@
</span><span class="cx">         elif option == &quot;--prodid&quot;:
</span><span class="cx">             prodid = value
</span><span class="cx">         elif option == &quot;--root&quot;:
</span><del>-            rootdir = value
</del><ins>+            rootdir = os.path.expanduser(value)
</ins><span class="cx">         elif option == &quot;--start&quot;:
</span><span class="cx">             startYear = int(value)
</span><span class="cx">         elif option == &quot;--end&quot;:
</span><span class="cx">             endYear = int(value)
</span><ins>+        elif option == &quot;--windows&quot;:
+            windowsAliases = os.path.expanduser(value)
</ins><span class="cx">         else:
</span><span class="cx">             usage(&quot;Unrecognized option: %s&quot; % (option,))
</span><span class="cx"> 
</span><del>-    # Process arguments
-    if len(args) &gt; 1:
-        usage(&quot;Must have only one argument&quot;)
-    if len(args) == 1:
-        rootdir = os.path.expanduser(args[0])
</del><ins>+    if not os.path.exists(rootdir):
+        os.makedirs(rootdir)
+    zonedir = os.path.join(rootdir, &quot;tzdata&quot;)
+    if not os.path.exists(zonedir):
+        print(&quot;Downloading and extracting IANA timezone database&quot;)
+        os.mkdir(zonedir)
+        iana = &quot;https://www.iana.org/time-zones/repository/tzdata-latest.tar.gz&quot;
+        data = urllib.urlretrieve(iana)
+        print(&quot;Extract data at: %s&quot; % (data[0]))
+        with tarfile.open(data[0], &quot;r:gz&quot;) as t:
+            t.extractall(zonedir)
</ins><span class="cx"> 
</span><ins>+    if windowsAliases is None:
+        windowsAliases = os.path.join(rootdir, &quot;windowsZones.xml&quot;)
+    if not os.path.exists(windowsAliases):
+        print(&quot;Downloading Unicode database&quot;)
+        unicode = &quot;http://unicode.org/repos/cldr/tags/latest/common/supplemental/windowsZones.xml&quot;
+        data = urllib.urlretrieve(unicode, windowsAliases)
+
</ins><span class="cx">     Calendar.sProdID = prodid
</span><span class="cx"> 
</span><span class="cx">     zonedir = os.path.join(rootdir, &quot;tzdata&quot;)
</span><span class="lines">@@ -270,41 +313,13 @@
</span><span class="cx">     for file in zonefiles:
</span><span class="cx">         parser.parse(os.path.join(zonedir, file))
</span><span class="cx"> 
</span><del>-    if 1:
-        parser.generateZoneinfoFiles(os.path.join(rootdir, &quot;zoneinfo&quot;), startYear, endYear, filterzones=(
-            #&quot;America/Montevideo&quot;,
-            #&quot;Europe/Paris&quot;,
-            #&quot;Africa/Cairo&quot;,
-        ))
-
-    if 0:
-        checkName = &quot;EST&quot;
-        parsed = parser.vtimezones(1800, 2018, filterzones=(
-            checkName,
-        ))
-
-        icsdir = &quot;../2008i/zoneinfo&quot;
-        cal = Calendar()
-        for file in (checkName,):
-            fin = open(os.path.join(icsdir, file + &quot;.ics&quot;), &quot;r&quot;)
-            cal.parse(fin)
-
-        for vtz in cal.getVTimezoneDB():
-            #from pycalendar.vtimezoneelement import VTimezoneElement
-            #vtz.mEmbedded.sort(VTimezoneElement.sort_dtstart)
-            for embedded in vtz.mEmbedded:
-                embedded.finalise()
-            vtz.finalise()
-
-        os = StringIO.StringIO()
-        cal.generate(os, False)
-        actual = os.getvalue()
-
-        print &quot;-- ACTUAL --&quot;
-        print actual
-        print
-        print &quot;-- PARSED --&quot;
-        print parsed
-        print
-        print &quot;-- DIFF --&quot;
-        print &quot;\n&quot;.join([line for line in unified_diff(actual.split(&quot;\n&quot;), parsed.split(&quot;\n&quot;))])
</del><ins>+    parser.generateZoneinfoFiles(
+        os.path.join(rootdir, &quot;zoneinfo&quot;),
+        startYear,
+        endYear,
+        windowsAliases=windowsAliases,
+        filterzones=(
+        #&quot;America/Montevideo&quot;,
+        #&quot;Europe/Paris&quot;,
+        #&quot;Africa/Cairo&quot;,
+    ))
</ins></span></pre>
</div>
</div>

</body>
</html>