1 84
import logging
2 84
import os
3 84
import tempfile
4 84
import shutil
5 84
import json
6 84
from subprocess import check_call, check_output
7 84
from tarfile import TarFile
8

9 84
from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME
10

11

12 84
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
13
    """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
14

15
    filename is the timezone tarball from ``ftp.iana.org/tz``.
16

17
    """
18 0
    tmpdir = tempfile.mkdtemp()
19 0
    zonedir = os.path.join(tmpdir, "zoneinfo")
20 0
    moduledir = os.path.dirname(__file__)
21 0
    try:
22 0
        with TarFile.open(filename) as tf:
23 0
            for name in zonegroups:
24 0
                tf.extract(name, tmpdir)
25 0
            filepaths = [os.path.join(tmpdir, n) for n in zonegroups]
26

27 0
            _run_zic(zonedir, filepaths)
28

29
        # write metadata file
30 0
        with open(os.path.join(zonedir, METADATA_FN), 'w') as f:
31 0
            json.dump(metadata, f, indent=4, sort_keys=True)
32 0
        target = os.path.join(moduledir, ZONEFILENAME)
33 0
        with TarFile.open(target, "w:%s" % format) as tf:
34 0
            for entry in os.listdir(zonedir):
35 0
                entrypath = os.path.join(zonedir, entry)
36 0
                tf.add(entrypath, entry)
37
    finally:
38 0
        shutil.rmtree(tmpdir)
39

40

41 84
def _run_zic(zonedir, filepaths):
42
    """Calls the ``zic`` compiler in a compatible way to get a "fat" binary.
43

44
    Recent versions of ``zic`` default to ``-b slim``, while older versions
45
    don't even have the ``-b`` option (but default to "fat" binaries). The
46
    current version of dateutil does not support Version 2+ TZif files, which
47
    causes problems when used in conjunction with "slim" binaries, so this
48
    function is used to ensure that we always get a "fat" binary.
49
    """
50

51 0
    try:
52 0
        help_text = check_output(["zic", "--help"])
53 0
    except OSError as e:
54 0
        _print_on_nosuchfile(e)
55 0
        raise
56

57 0
    if b"-b " in help_text:
58 0
        bloat_args = ["-b", "fat"]
59
    else:
60 0
        bloat_args = []
61

62 0
    check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths)
63

64

65 84
def _print_on_nosuchfile(e):
66
    """Print helpful troubleshooting message
67

68
    e is an exception raised by subprocess.check_call()
69

70
    """
71 0
    if e.errno == 2:
72 0
        logging.error(
73
            "Could not find zic. Perhaps you need to install "
74
            "libc-bin or some other package that provides it, "
75
            "or it's not in your PATH?")

Read our documentation on viewing source code .

Loading