blob: fcda08e20a2740a8702bf97a4f58ec8856781f98 [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 +00006import os
Tarek Ziadé77c8b372009-05-28 13:01:13 +00007from warnings import warn
8import sys
9
Antoine Pitrou2c50a092011-03-15 21:02:59 +010010try:
11 import zipfile
12except ImportError:
13 zipfile = None
14
15
Greg Wardaebf7062000-04-04 02:05:59 +000016from distutils.errors import DistutilsExecError
17from distutils.spawn import spawn
Greg Ward04e25a12000-08-22 01:48:54 +000018from distutils.dir_util import mkpath
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000019from distutils import log
Greg Wardaebf7062000-04-04 02:05:59 +000020
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +000021def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0):
Greg Wardaebf7062000-04-04 02:05:59 +000022 """Create a (possibly compressed) tar file from all the files under
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +000023 'base_dir'.
24
25 'compress' must be "gzip" (the default), "compress", "bzip2", or None.
26 Both "tar" and the compression utility named by 'compress' must be on
27 the default program search path, so this is probably Unix-specific.
28 The output tar file will be named 'base_dir' + ".tar", possibly plus
29 the appropriate compression extension (".gz", ".bz2" or ".Z").
30 Returns the output filename.
Greg Wardca4289f2000-09-26 02:13:49 +000031 """
Tarek Ziadé77c8b372009-05-28 13:01:13 +000032 tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: '', 'compress': ''}
33 compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'compress': '.Z'}
Fred Drakeb94b8492001-12-06 20:51:35 +000034
Greg Wardf1948782000-04-25 01:38:20 +000035 # flags for compression program, each element of list will be an argument
Greg Wardf1948782000-04-25 01:38:20 +000036 if compress is not None and compress not in compress_ext.keys():
Collin Winter5b7e9d72007-08-30 03:52:21 +000037 raise ValueError(
Tarek Ziadé77c8b372009-05-28 13:01:13 +000038 "bad value for 'compress': must be None, 'gzip', 'bzip2' "
39 "or 'compress'")
Greg Wardaebf7062000-04-04 02:05:59 +000040
Tarek Ziadé77c8b372009-05-28 13:01:13 +000041 archive_name = base_name + '.tar'
42 if compress != 'compress':
43 archive_name += compress_ext.get(compress, '')
44
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000045 mkpath(os.path.dirname(archive_name), dry_run=dry_run)
Greg Wardaebf7062000-04-04 02:05:59 +000046
Tarek Ziadé77c8b372009-05-28 13:01:13 +000047 # creating the tarball
48 import tarfile # late import so Python build itself doesn't break
49
50 log.info('Creating tar archive')
51 if not dry_run:
52 tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
53 try:
54 tar.add(base_dir)
55 finally:
56 tar.close()
57
58 # compression using `compress`
59 if compress == 'compress':
60 warn("'compress' will be deprecated.", PendingDeprecationWarning)
61 # the option varies depending on the platform
62 compressed_name = archive_name + compress_ext[compress]
63 if sys.platform == 'win32':
64 cmd = [compress, archive_name, compressed_name]
65 else:
66 cmd = [compress, '-f', archive_name]
67 spawn(cmd, dry_run=dry_run)
68 return compressed_name
69
70 return archive_name
Greg Wardaebf7062000-04-04 02:05:59 +000071
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +000072def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
73 """Create a zip file from all the files under 'base_dir'.
Greg Wardaebf7062000-04-04 02:05:59 +000074
Éric Araujo7e2e3212010-12-15 20:30:51 +000075 The output zip file will be named 'base_name' + ".zip". Uses either the
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +000076 "zipfile" Python module (if available) or the InfoZIP "zip" utility
77 (if installed and found on the default search path). If neither tool is
78 available, raises DistutilsExecError. Returns the name of the output zip
79 file.
Greg Wardca4289f2000-09-26 02:13:49 +000080 """
Greg Wardaebf7062000-04-04 02:05:59 +000081 zip_filename = base_name + ".zip"
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000082 mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
Greg Wardaebf7062000-04-04 02:05:59 +000083
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +000084 # If zipfile module is not available, try spawning an external
85 # 'zip' command.
86 if zipfile is None:
87 if verbose:
88 zipoptions = "-r"
89 else:
90 zipoptions = "-rq"
Tim Peters182b5ac2004-07-18 06:16:08 +000091
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +000092 try:
93 spawn(["zip", zipoptions, zip_filename, base_dir],
94 dry_run=dry_run)
95 except DistutilsExecError:
96 # XXX really should distinguish between "couldn't find
97 # external 'zip' command" and "zip failed".
Collin Winter5b7e9d72007-08-30 03:52:21 +000098 raise DistutilsExecError(("unable to create zip file '%s': "
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +000099 "could neither import the 'zipfile' module nor "
Collin Winter5b7e9d72007-08-30 03:52:21 +0000100 "find a standalone zip utility") % zip_filename)
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +0000101
102 else:
103 log.info("creating '%s' and adding '%s' to it",
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000104 zip_filename, base_dir)
Andrew M. Kuchlingcdd21572002-11-21 18:33:28 +0000105
Greg Wardaebf7062000-04-04 02:05:59 +0000106 if not dry_run:
Antoine Pitrou2c50a092011-03-15 21:02:59 +0100107 try:
108 zip = zipfile.ZipFile(zip_filename, "w",
109 compression=zipfile.ZIP_DEFLATED)
110 except RuntimeError:
111 zip = zipfile.ZipFile(zip_filename, "w",
112 compression=zipfile.ZIP_STORED)
Greg Wardaebf7062000-04-04 02:05:59 +0000113
Benjamin Peterson699adb92008-05-08 22:27:58 +0000114 for dirpath, dirnames, filenames in os.walk(base_dir):
115 for name in filenames:
116 path = os.path.normpath(os.path.join(dirpath, name))
117 if os.path.isfile(path):
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000118 zip.write(path, path)
Benjamin Peterson699adb92008-05-08 22:27:58 +0000119 log.info("adding '%s'" % path)
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000120 zip.close()
Greg Wardaebf7062000-04-04 02:05:59 +0000121
122 return zip_filename
123
Greg Warddb807542000-04-22 03:09:56 +0000124ARCHIVE_FORMATS = {
Greg Ward2ff78872000-06-24 00:23:20 +0000125 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
126 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
127 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"),
128 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"),
Greg Ward04e25a12000-08-22 01:48:54 +0000129 'zip': (make_zipfile, [],"ZIP file")
Greg Warddb807542000-04-22 03:09:56 +0000130 }
131
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000132def check_archive_formats(formats):
133 """Returns the first format from the 'format' list that is unknown.
134
135 If all formats are known, returns None
136 """
Greg Warddb807542000-04-22 03:09:56 +0000137 for format in formats:
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000138 if format not in ARCHIVE_FORMATS:
Greg Warddb807542000-04-22 03:09:56 +0000139 return format
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000140 return None
Greg Warddb807542000-04-22 03:09:56 +0000141
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000142def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
143 dry_run=0):
144 """Create an archive file (eg. zip or tar).
145
146 'base_name' is the name of the file to create, minus any format-specific
147 extension; 'format' is the archive format: one of "zip", "tar", "ztar",
148 or "gztar".
149
Greg Wardaebf7062000-04-04 02:05:59 +0000150 'root_dir' is a directory that will be the root directory of the
151 archive; ie. we typically chdir into 'root_dir' before creating the
152 archive. 'base_dir' is the directory where we start archiving from;
153 ie. 'base_dir' will be the common prefix of all files and
154 directories in the archive. 'root_dir' and 'base_dir' both default
Greg Ward87909612000-06-01 01:07:55 +0000155 to the current directory. Returns the name of the archive file.
156 """
Greg Wardaebf7062000-04-04 02:05:59 +0000157 save_cwd = os.getcwd()
158 if root_dir is not None:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000159 log.debug("changing into '%s'", root_dir)
Greg Wardca4289f2000-09-26 02:13:49 +0000160 base_name = os.path.abspath(base_name)
Greg Wardaebf7062000-04-04 02:05:59 +0000161 if not dry_run:
Greg Wardca4289f2000-09-26 02:13:49 +0000162 os.chdir(root_dir)
Greg Wardaebf7062000-04-04 02:05:59 +0000163
164 if base_dir is None:
165 base_dir = os.curdir
166
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000167 kwargs = {'dry_run': dry_run}
Fred Drakeb94b8492001-12-06 20:51:35 +0000168
Greg Warddb807542000-04-22 03:09:56 +0000169 try:
170 format_info = ARCHIVE_FORMATS[format]
171 except KeyError:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000172 raise ValueError("unknown archive format '%s'" % format)
Greg Wardaebf7062000-04-04 02:05:59 +0000173
Greg Warddb807542000-04-22 03:09:56 +0000174 func = format_info[0]
Tarek Ziadéeb5f27e2009-05-17 12:12:02 +0000175 for arg, val in format_info[1]:
Greg Warddb807542000-04-22 03:09:56 +0000176 kwargs[arg] = val
Tarek Ziadé53fdb182009-10-24 13:42:10 +0000177 try:
178 filename = func(base_name, base_dir, **kwargs)
179 finally:
180 if root_dir is not None:
181 log.debug("changing back to '%s'", save_cwd)
182 os.chdir(save_cwd)
Greg Wardaebf7062000-04-04 02:05:59 +0000183
Greg Ward87909612000-06-01 01:07:55 +0000184 return filename