PageRenderTime 39ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/distutils/archive_util.py

https://github.com/rpattabi/ironruby
Python | 243 lines | 212 code | 21 blank | 10 comment | 27 complexity | 92b13d54b461a9fac4d4c2f2a8b3fe74 MD5 | raw file
  1. """distutils.archive_util
  2. Utility functions for creating archive files (tarballs, zip files,
  3. that sort of thing)."""
  4. __revision__ = "$Id: archive_util.py 75659 2009-10-24 13:29:44Z tarek.ziade $"
  5. import os
  6. from warnings import warn
  7. import sys
  8. from distutils.errors import DistutilsExecError
  9. from distutils.spawn import spawn
  10. from distutils.dir_util import mkpath
  11. from distutils import log
  12. try:
  13. from pwd import getpwnam
  14. except ImportError:
  15. getpwnam = None
  16. try:
  17. from grp import getgrnam
  18. except ImportError:
  19. getgrnam = None
  20. def _get_gid(name):
  21. """Returns a gid, given a group name."""
  22. if getgrnam is None or name is None:
  23. return None
  24. try:
  25. result = getgrnam(name)
  26. except KeyError:
  27. result = None
  28. if result is not None:
  29. return result[2]
  30. return None
  31. def _get_uid(name):
  32. """Returns an uid, given a user name."""
  33. if getpwnam is None or name is None:
  34. return None
  35. try:
  36. result = getpwnam(name)
  37. except KeyError:
  38. result = None
  39. if result is not None:
  40. return result[2]
  41. return None
  42. def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
  43. owner=None, group=None):
  44. """Create a (possibly compressed) tar file from all the files under
  45. 'base_dir'.
  46. 'compress' must be "gzip" (the default), "compress", "bzip2", or None.
  47. (compress will be deprecated in Python 3.2)
  48. 'owner' and 'group' can be used to define an owner and a group for the
  49. archive that is being built. If not provided, the current owner and group
  50. will be used.
  51. The output tar file will be named 'base_dir' + ".tar", possibly plus
  52. the appropriate compression extension (".gz", ".bz2" or ".Z").
  53. Returns the output filename.
  54. """
  55. tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: '', 'compress': ''}
  56. compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'compress': '.Z'}
  57. # flags for compression program, each element of list will be an argument
  58. if compress is not None and compress not in compress_ext.keys():
  59. raise ValueError, \
  60. ("bad value for 'compress': must be None, 'gzip', 'bzip2' "
  61. "or 'compress'")
  62. archive_name = base_name + '.tar'
  63. if compress != 'compress':
  64. archive_name += compress_ext.get(compress, '')
  65. mkpath(os.path.dirname(archive_name), dry_run=dry_run)
  66. # creating the tarball
  67. import tarfile # late import so Python build itself doesn't break
  68. log.info('Creating tar archive')
  69. uid = _get_uid(owner)
  70. gid = _get_gid(group)
  71. def _set_uid_gid(tarinfo):
  72. if gid is not None:
  73. tarinfo.gid = gid
  74. tarinfo.gname = group
  75. if uid is not None:
  76. tarinfo.uid = uid
  77. tarinfo.uname = owner
  78. return tarinfo
  79. if not dry_run:
  80. tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
  81. try:
  82. tar.add(base_dir, filter=_set_uid_gid)
  83. finally:
  84. tar.close()
  85. # compression using `compress`
  86. if compress == 'compress':
  87. warn("'compress' will be deprecated.", PendingDeprecationWarning)
  88. # the option varies depending on the platform
  89. compressed_name = archive_name + compress_ext[compress]
  90. if sys.platform == 'win32':
  91. cmd = [compress, archive_name, compressed_name]
  92. else:
  93. cmd = [compress, '-f', archive_name]
  94. spawn(cmd, dry_run=dry_run)
  95. return compressed_name
  96. return archive_name
  97. def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
  98. """Create a zip file from all the files under 'base_dir'.
  99. The output zip file will be named 'base_dir' + ".zip". Uses either the
  100. "zipfile" Python module (if available) or the InfoZIP "zip" utility
  101. (if installed and found on the default search path). If neither tool is
  102. available, raises DistutilsExecError. Returns the name of the output zip
  103. file.
  104. """
  105. try:
  106. import zipfile
  107. except ImportError:
  108. zipfile = None
  109. zip_filename = base_name + ".zip"
  110. mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
  111. # If zipfile module is not available, try spawning an external
  112. # 'zip' command.
  113. if zipfile is None:
  114. if verbose:
  115. zipoptions = "-r"
  116. else:
  117. zipoptions = "-rq"
  118. try:
  119. spawn(["zip", zipoptions, zip_filename, base_dir],
  120. dry_run=dry_run)
  121. except DistutilsExecError:
  122. # XXX really should distinguish between "couldn't find
  123. # external 'zip' command" and "zip failed".
  124. raise DistutilsExecError, \
  125. ("unable to create zip file '%s': "
  126. "could neither import the 'zipfile' module nor "
  127. "find a standalone zip utility") % zip_filename
  128. else:
  129. log.info("creating '%s' and adding '%s' to it",
  130. zip_filename, base_dir)
  131. if not dry_run:
  132. zip = zipfile.ZipFile(zip_filename, "w",
  133. compression=zipfile.ZIP_DEFLATED)
  134. for dirpath, dirnames, filenames in os.walk(base_dir):
  135. for name in filenames:
  136. path = os.path.normpath(os.path.join(dirpath, name))
  137. if os.path.isfile(path):
  138. zip.write(path, path)
  139. log.info("adding '%s'" % path)
  140. zip.close()
  141. return zip_filename
  142. ARCHIVE_FORMATS = {
  143. 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
  144. 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
  145. 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
  146. 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
  147. 'zip': (make_zipfile, [],"ZIP file")
  148. }
  149. def check_archive_formats(formats):
  150. """Returns the first format from the 'format' list that is unknown.
  151. If all formats are known, returns None
  152. """
  153. for format in formats:
  154. if format not in ARCHIVE_FORMATS:
  155. return format
  156. return None
  157. def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
  158. dry_run=0, owner=None, group=None):
  159. """Create an archive file (eg. zip or tar).
  160. 'base_name' is the name of the file to create, minus any format-specific
  161. extension; 'format' is the archive format: one of "zip", "tar", "ztar",
  162. or "gztar".
  163. 'root_dir' is a directory that will be the root directory of the
  164. archive; ie. we typically chdir into 'root_dir' before creating the
  165. archive. 'base_dir' is the directory where we start archiving from;
  166. ie. 'base_dir' will be the common prefix of all files and
  167. directories in the archive. 'root_dir' and 'base_dir' both default
  168. to the current directory. Returns the name of the archive file.
  169. 'owner' and 'group' are used when creating a tar archive. By default,
  170. uses the current owner and group.
  171. """
  172. save_cwd = os.getcwd()
  173. if root_dir is not None:
  174. log.debug("changing into '%s'", root_dir)
  175. base_name = os.path.abspath(base_name)
  176. if not dry_run:
  177. os.chdir(root_dir)
  178. if base_dir is None:
  179. base_dir = os.curdir
  180. kwargs = {'dry_run': dry_run}
  181. try:
  182. format_info = ARCHIVE_FORMATS[format]
  183. except KeyError:
  184. raise ValueError, "unknown archive format '%s'" % format
  185. func = format_info[0]
  186. for arg, val in format_info[1]:
  187. kwargs[arg] = val
  188. if format != 'zip':
  189. kwargs['owner'] = owner
  190. kwargs['group'] = group
  191. try:
  192. filename = func(base_name, base_dir, **kwargs)
  193. finally:
  194. if root_dir is not None:
  195. log.debug("changing back to '%s'", save_cwd)
  196. os.chdir(save_cwd)
  197. return filename