rebuild.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import logging
  2. import os
  3. import tempfile
  4. import shutil
  5. import json
  6. from subprocess import check_call
  7. from dateutil.zoneinfo import tar_open, METADATA_FN, ZONEFILENAME
  8. def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
  9. """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
  10. filename is the timezone tarball from ftp.iana.org/tz.
  11. """
  12. tmpdir = tempfile.mkdtemp()
  13. zonedir = os.path.join(tmpdir, "zoneinfo")
  14. moduledir = os.path.dirname(__file__)
  15. try:
  16. with tar_open(filename) as tf:
  17. for name in zonegroups:
  18. tf.extract(name, tmpdir)
  19. filepaths = [os.path.join(tmpdir, n) for n in zonegroups]
  20. try:
  21. check_call(["zic", "-d", zonedir] + filepaths)
  22. except OSError as e:
  23. _print_on_nosuchfile(e)
  24. raise
  25. # write metadata file
  26. with open(os.path.join(zonedir, METADATA_FN), 'w') as f:
  27. json.dump(metadata, f, indent=4, sort_keys=True)
  28. target = os.path.join(moduledir, ZONEFILENAME)
  29. with tar_open(target, "w:%s" % format) as tf:
  30. for entry in os.listdir(zonedir):
  31. entrypath = os.path.join(zonedir, entry)
  32. tf.add(entrypath, entry)
  33. finally:
  34. shutil.rmtree(tmpdir)
  35. def _print_on_nosuchfile(e):
  36. """Print helpful troubleshooting message
  37. e is an exception raised by subprocess.check_call()
  38. """
  39. if e.errno == 2:
  40. logging.error(
  41. "Could not find zic. Perhaps you need to install "
  42. "libc-bin or some other package that provides it, "
  43. "or it's not in your PATH?")