blob: c06eba351d8e1cab95882eb909755dcb5971835c [file] [log] [blame]
Greg Wardaebf7062000-04-04 02:05:59 +00001"""distutils.archive_util
2
3Utility functions for creating archive files (tarballs, zip files,
4that sort of thing)."""
5
Greg Wardaebf7062000-04-04 02:05:59 +00006__revision__ = "$Id$"
7
8import os
Tarek Ziadé77c8b372009-05-28 13:01:13 +00009from warnings import warn
10import sys
11
Antoine Pitrou2c50a092011-03-15 21:02:59 +010012try:
13 import zipfile
14except ImportError:
15 zipfile = None
16
17
Greg Wardaebf7062000-04-04 02:05:59 +000018from distutils.errors import DistutilsExecError
19from distutils.spawn import spawn
Greg Ward04e25a12000-08-22 01:48:54 +000020from distutils.dir_util import mkpath
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000021from distutils import log
Greg Wardaebf7062000-04-04 02:05:59 +000022
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +000023def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0):
Greg Wardaebf7062000-04-04 02:05:59 +000024 """Create a (possibly compressed) tar file from all the files under
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +000025 'base_dir'.
26
27 'compress' must be "gzip" (the default), "compress", "bzip2", or None.
28 Both "tar" and the compression utility named by 'compress' must be on
29 the default program search path, so this is probably Unix-specific.
30 The output tar file will be named 'base_dir' + ".tar", possibly plus
31 the appropriate compression extension (".gz", ".bz2" or ".Z").
32 Returns the output filename.
Greg Wardca4289f2000-09-26 02:13:49 +000033 """
Tarek Ziadé77c8b372009-05-28 13:01:13 +000034 tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: '', 'compress': ''}
35 compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'compress': '.Z'}
Fred Drakeb94b8492001-12-06 20:51:35 +000036
Greg Wardf1948782000-04-25 01:38:20 +000037 # flags for compression program, each element of list will be an argument
Greg Wardf1948782000-04-25 01:38:20 +000038 if compress is not None and compress not in compress_ext.keys():
Collin Winter5b7e9d72007-08-30 03:52:21 +000039 raise ValueError(
Tarek Ziadé77c8b372009-05-28 13:01:13 +000040 "bad value for 'compress': must be None, 'gzip', 'bzip2' "
41 "or 'compress'")
Greg Wardaebf7062000-04-04 02:05:59 +000042
Tarek Ziadé77c8b372009-05-28 13:01:13 +000043 archive_name = base_name + '.tar'
44 if compress != 'compress':
45 archive_name += compress_ext.get(compress, '')
46
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000047 mkpath(os.path.dirname(archive_name), dry_run=dry_run)
Greg Wardaebf7062000-04-04 02:05:59 +000048
Tarek Ziadé77c8b372009-05-28 13:01:13 +000049 # creating the tarball
50 import tarfile # late import so Python build itself doesn't break
51
52 log.info('Creating tar archive')
53 if not dry_run:
54 tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
55 try:
56 tar.add(base_dir)
57 finally:
58 tar.close()
59
60 # compression using `compress`
61 if compress == 'compress':
62 warn("'compress' will be deprecated.", PendingDeprecationWarning)
63 # the option varies depending on the platform
64 compressed_name = archive_name + compress_ext[compress]
65 if sys.platform == 'win32':
66 cmd = [compress, archive_name, compressed_name]
67 else:
68 cmd = [compress, '-f', archive_name]
69 spawn(cmd, dry_run=dry_run)
70 return compressed_name
71
72 return archive_name
Greg Wardaebf7062000-04-04 02:05:59 +000073
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +000074def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
75 """Create a zip file from all the files under 'base_dir'.
Greg Wardaebf7062000-04-04 02:05:59 +000076
Éric Araujo7e2e3212010-12-15 20:30:51 +000077 The output zip file will be named 'base_name' + ".zip". Uses either the
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +000078 "zipfile" Python module (if available) or the InfoZIP "zip" utility
79 (if installed and found on the default search path). If neither tool is
80 available, raises DistutilsExecError. Returns the name of the output zip
81 file.
Greg Wardca4289f2000-09-26 02:13:49 +000082 """
Greg Wardaebf7062000-04-04 02:05:59 +000083 zip_filename = base_name + ".zip"
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000084 mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
Greg Wardaebf7062000-04-04 02:05:59 +000085
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +000086 # If zipfile module is not available, try spawning an external
87 # 'zip' command.
88 if zipfile is None:
89 if verbose:
90 zipoptions = "-r"
91 else:
92 zipoptions = "-rq"
Tim Peters182b5ac2004-07-18 06:16:08 +000093
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +000094 try:
95 spawn(["zip", zipoptions, zip_filename, base_dir],
96 dry_run=dry_run)
97 except DistutilsExecError:
98 # XXX really should distinguish between "couldn't find
99 # external 'zip' command" and "zip failed".
Collin Winter5b7e9d72007-08-30 03:52:21 +0000100 raise DistutilsExecError(("unable to create zip file '%s': "
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +0000101 "could neither import the 'zipfile' module nor "
Collin Winter5b7e9d72007-08-30 03:52:21 +0000102 "find a standalone zip utility") % zip_filename)
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +0000103
104 else:
105 log.info("creating '%s' and adding '%s' to it",
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000106 zip_filename, base_dir)
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +0000107
Greg Wardaebf7062000-04-04 02:05:59 +0000108 if not dry_run:
Antoine Pitrou2c50a092011-03-15 21:02:59 +0100109 try:
110 zip = zipfile.ZipFile(zip_filename, "w",
111 compression=zipfile.ZIP_DEFLATED)
112 except RuntimeError:
113 zip = zipfile.ZipFile(zip_filename, "w",
114 compression=zipfile.ZIP_STORED)
Greg Wardaebf7062000-04-04 02:05:59 +0000115
Benjamin Peterson699adb92008-05-08 22:27:58 +0000116 for dirpath, dirnames, filenames in os.walk(base_dir):
117 for name in filenames:
118 path = os.path.normpath(os.path.join(dirpath, name))
119 if os.path.isfile(path):
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000120 zip.write(path, path)
Benjamin Peterson699adb92008-05-08 22:27:58 +0000121 log.info("adding '%s'" % path)
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000122 zip.close()
Greg Wardaebf7062000-04-04 02:05:59 +0000123
124 return zip_filename
125
Greg Warddb807542000-04-22 03:09:56 +0000126ARCHIVE_FORMATS = {
Greg Ward2ff78872000-06-24 00:23:20 +0000127 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
128 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
129 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
130 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
Greg Ward04e25a12000-08-22 01:48:54 +0000131 'zip': (make_zipfile, [],"ZIP file")
Greg Warddb807542000-04-22 03:09:56 +0000132 }
133
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000134def check_archive_formats(formats):
135 """Returns the first format from the 'format' list that is unknown.
136
137 If all formats are known, returns None
138 """
Greg Warddb807542000-04-22 03:09:56 +0000139 for format in formats:
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000140 if format not in ARCHIVE_FORMATS:
Greg Warddb807542000-04-22 03:09:56 +0000141 return format
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000142 return None
Greg Warddb807542000-04-22 03:09:56 +0000143
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000144def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
145 dry_run=0):
146 """Create an archive file (eg. zip or tar).
147
148 'base_name' is the name of the file to create, minus any format-specific
149 extension; 'format' is the archive format: one of "zip", "tar", "ztar",
150 or "gztar".
151
Greg Wardaebf7062000-04-04 02:05:59 +0000152 'root_dir' is a directory that will be the root directory of the
153 archive; ie. we typically chdir into 'root_dir' before creating the
154 archive. 'base_dir' is the directory where we start archiving from;
155 ie. 'base_dir' will be the common prefix of all files and
156 directories in the archive. 'root_dir' and 'base_dir' both default
Greg Ward87909612000-06-01 01:07:55 +0000157 to the current directory. Returns the name of the archive file.
158 """
Greg Wardaebf7062000-04-04 02:05:59 +0000159 save_cwd = os.getcwd()
160 if root_dir is not None:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000161 log.debug("changing into '%s'", root_dir)
Greg Wardca4289f2000-09-26 02:13:49 +0000162 base_name = os.path.abspath(base_name)
Greg Wardaebf7062000-04-04 02:05:59 +0000163 if not dry_run:
Greg Wardca4289f2000-09-26 02:13:49 +0000164 os.chdir(root_dir)
Greg Wardaebf7062000-04-04 02:05:59 +0000165
166 if base_dir is None:
167 base_dir = os.curdir
168
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000169 kwargs = {'dry_run': dry_run}
Fred Drakeb94b8492001-12-06 20:51:35 +0000170
Greg Warddb807542000-04-22 03:09:56 +0000171 try:
172 format_info = ARCHIVE_FORMATS[format]
173 except KeyError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000174 raise ValueError("unknown archive format '%s'" % format)
Greg Wardaebf7062000-04-04 02:05:59 +0000175
Greg Warddb807542000-04-22 03:09:56 +0000176 func = format_info[0]
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000177 for arg, val in format_info[1]:
Greg Warddb807542000-04-22 03:09:56 +0000178 kwargs[arg] = val
Tarek Ziadé53fdb182009-10-24 13:42:10 +0000179 try:
180 filename = func(base_name, base_dir, **kwargs)
181 finally:
182 if root_dir is not None:
183 log.debug("changing back to '%s'", save_cwd)
184 os.chdir(save_cwd)
Greg Wardaebf7062000-04-04 02:05:59 +0000185
Greg Ward87909612000-06-01 01:07:55 +0000186 return filename