/Lib/distutils/archive_util.py

http://unladen-swallow.googlecode.com/ · Python · 171 lines · 150 code · 13 blank · 8 comment · 8 complexity · f30da101314f492388d358d0f1e23a4c MD5 · raw file

  1. """distutils.archive_util
  2. Utility functions for creating archive files (tarballs, zip files,
  3. that sort of thing)."""
  4. # This module should be kept compatible with Python 2.1.
  5. __revision__ = "$Id: archive_util.py 62904 2008-05-08 22:09:54Z benjamin.peterson $"
  6. import os
  7. from distutils.errors import DistutilsExecError
  8. from distutils.spawn import spawn
  9. from distutils.dir_util import mkpath
  10. from distutils import log
  11. def make_tarball (base_name, base_dir, compress="gzip",
  12. verbose=0, dry_run=0):
  13. """Create a (possibly compressed) tar file from all the files under
  14. 'base_dir'. 'compress' must be "gzip" (the default), "compress",
  15. "bzip2", or None. Both "tar" and the compression utility named by
  16. 'compress' must be on the default program search path, so this is
  17. probably Unix-specific. The output tar file will be named 'base_dir' +
  18. ".tar", possibly plus the appropriate compression extension (".gz",
  19. ".bz2" or ".Z"). Return the output filename.
  20. """
  21. # XXX GNU tar 1.13 has a nifty option to add a prefix directory.
  22. # It's pretty new, though, so we certainly can't require it --
  23. # but it would be nice to take advantage of it to skip the
  24. # "create a tree of hardlinks" step! (Would also be nice to
  25. # detect GNU tar to use its 'z' option and save a step.)
  26. compress_ext = { 'gzip': ".gz",
  27. 'bzip2': '.bz2',
  28. 'compress': ".Z" }
  29. # flags for compression program, each element of list will be an argument
  30. compress_flags = {'gzip': ["-f9"],
  31. 'compress': ["-f"],
  32. 'bzip2': ['-f9']}
  33. if compress is not None and compress not in compress_ext.keys():
  34. raise ValueError, \
  35. "bad value for 'compress': must be None, 'gzip', or 'compress'"
  36. archive_name = base_name + ".tar"
  37. mkpath(os.path.dirname(archive_name), dry_run=dry_run)
  38. cmd = ["tar", "-cf", archive_name, base_dir]
  39. spawn(cmd, dry_run=dry_run)
  40. if compress:
  41. spawn([compress] + compress_flags[compress] + [archive_name],
  42. dry_run=dry_run)
  43. return archive_name + compress_ext[compress]
  44. else:
  45. return archive_name
  46. # make_tarball ()
  47. def make_zipfile (base_name, base_dir, verbose=0, dry_run=0):
  48. """Create a zip file from all the files under 'base_dir'. The output
  49. zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
  50. Python module (if available) or the InfoZIP "zip" utility (if installed
  51. and found on the default search path). If neither tool is available,
  52. raises DistutilsExecError. Returns the name of the output zip file.
  53. """
  54. try:
  55. import zipfile
  56. except ImportError:
  57. zipfile = None
  58. zip_filename = base_name + ".zip"
  59. mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
  60. # If zipfile module is not available, try spawning an external
  61. # 'zip' command.
  62. if zipfile is None:
  63. if verbose:
  64. zipoptions = "-r"
  65. else:
  66. zipoptions = "-rq"
  67. try:
  68. spawn(["zip", zipoptions, zip_filename, base_dir],
  69. dry_run=dry_run)
  70. except DistutilsExecError:
  71. # XXX really should distinguish between "couldn't find
  72. # external 'zip' command" and "zip failed".
  73. raise DistutilsExecError, \
  74. ("unable to create zip file '%s': "
  75. "could neither import the 'zipfile' module nor "
  76. "find a standalone zip utility") % zip_filename
  77. else:
  78. log.info("creating '%s' and adding '%s' to it",
  79. zip_filename, base_dir)
  80. if not dry_run:
  81. z = zipfile.ZipFile(zip_filename, "w",
  82. compression=zipfile.ZIP_DEFLATED)
  83. for dirpath, dirnames, filenames in os.walk(base_dir):
  84. for name in filenames:
  85. path = os.path.normpath(os.path.join(dirpath, name))
  86. if os.path.isfile(path):
  87. z.write(path, path)
  88. log.info("adding '%s'" % path)
  89. z.close()
  90. return zip_filename
  91. # make_zipfile ()
  92. ARCHIVE_FORMATS = {
  93. 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
  94. 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
  95. 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
  96. 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
  97. 'zip': (make_zipfile, [],"ZIP file")
  98. }
  99. def check_archive_formats (formats):
  100. for format in formats:
  101. if format not in ARCHIVE_FORMATS:
  102. return format
  103. else:
  104. return None
  105. def make_archive (base_name, format,
  106. root_dir=None, base_dir=None,
  107. verbose=0, dry_run=0):
  108. """Create an archive file (eg. zip or tar). 'base_name' is the name
  109. of the file to create, minus any format-specific extension; 'format'
  110. is the archive format: one of "zip", "tar", "ztar", or "gztar".
  111. 'root_dir' is a directory that will be the root directory of the
  112. archive; ie. we typically chdir into 'root_dir' before creating the
  113. archive. 'base_dir' is the directory where we start archiving from;
  114. ie. 'base_dir' will be the common prefix of all files and
  115. directories in the archive. 'root_dir' and 'base_dir' both default
  116. to the current directory. Returns the name of the archive file.
  117. """
  118. save_cwd = os.getcwd()
  119. if root_dir is not None:
  120. log.debug("changing into '%s'", root_dir)
  121. base_name = os.path.abspath(base_name)
  122. if not dry_run:
  123. os.chdir(root_dir)
  124. if base_dir is None:
  125. base_dir = os.curdir
  126. kwargs = { 'dry_run': dry_run }
  127. try:
  128. format_info = ARCHIVE_FORMATS[format]
  129. except KeyError:
  130. raise ValueError, "unknown archive format '%s'" % format
  131. func = format_info[0]
  132. for (arg,val) in format_info[1]:
  133. kwargs[arg] = val
  134. filename = apply(func, (base_name, base_dir), kwargs)
  135. if root_dir is not None:
  136. log.debug("changing back to '%s'", save_cwd)
  137. os.chdir(save_cwd)
  138. return filename
  139. # make_archive ()