blob: c07f394b6b1ad8948ef47e78d08fac843d23b2d3 [file] [log] [blame]
Tarek Ziadéc3399782010-02-23 05:39:18 +00001"""Utility functions for copying and archiving files and directory trees.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +00002
Guido van Rossum959fa011999-08-18 20:03:17 +00003XXX The functions here don't copy the resource fork or other metadata on Mac.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +00004
5"""
Guido van Rossumc6360141990-10-13 19:23:40 +00006
Guido van Rossumc96207a1992-03-31 18:55:40 +00007import os
Guido van Rossum83c03e21999-02-23 23:07:51 +00008import sys
Guido van Rossum9d0a3df1997-04-29 14:45:19 +00009import stat
Brett Cannon1c3fa182004-06-19 21:11:35 +000010from os.path import abspath
Georg Brandl2ee470f2008-07-16 12:55:28 +000011import fnmatch
Tarek Ziadé396fad72010-02-23 05:30:31 +000012import collections
Antoine Pitrou910bd512010-03-22 20:11:09 +000013import errno
Tarek Ziadé6ac91722010-04-28 17:51:36 +000014import tarfile
Tarek Ziadé396fad72010-02-23 05:30:31 +000015
16try:
17 from pwd import getpwnam
18except ImportError:
19 getpwnam = None
20
21try:
22 from grp import getgrnam
23except ImportError:
24 getgrnam = None
Guido van Rossumc6360141990-10-13 19:23:40 +000025
Tarek Ziadéc3399782010-02-23 05:39:18 +000026__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
27 "copytree", "move", "rmtree", "Error", "SpecialFileError",
28 "ExecError", "make_archive", "get_archive_formats",
Tarek Ziadé6ac91722010-04-28 17:51:36 +000029 "register_archive_format", "unregister_archive_format",
30 "get_unpack_formats", "register_unpack_format",
31 "unregister_unpack_format", "unpack_archive"]
Martin v. Löwise9ce0b02002-10-07 13:23:24 +000032
Neal Norwitz4ce69a52005-09-01 00:45:28 +000033class Error(EnvironmentError):
Martin v. Löwise9ce0b02002-10-07 13:23:24 +000034 pass
Guido van Rossumc6360141990-10-13 19:23:40 +000035
Antoine Pitrou7fff0962009-05-01 21:09:44 +000036class SpecialFileError(EnvironmentError):
37 """Raised when trying to do a kind of operation (e.g. copying) which is
38 not supported on a special file (e.g. a named pipe)"""
39
Tarek Ziadé396fad72010-02-23 05:30:31 +000040class ExecError(EnvironmentError):
41 """Raised when a command could not be executed"""
42
Tarek Ziadé6ac91722010-04-28 17:51:36 +000043class ReadError(EnvironmentError):
44 """Raised when an archive cannot be read"""
45
46class RegistryError(Exception):
47 """Raised when a registery operation with the archiving
48 and unpacking registeries fails"""
49
50
Georg Brandl6aa2d1f2008-08-12 08:35:52 +000051try:
52 WindowsError
53except NameError:
54 WindowsError = None
55
Greg Stein42bb8b32000-07-12 09:55:30 +000056def copyfileobj(fsrc, fdst, length=16*1024):
57 """copy data from file-like object fsrc to file-like object fdst"""
58 while 1:
59 buf = fsrc.read(length)
60 if not buf:
61 break
62 fdst.write(buf)
63
Johannes Gijsbers46f14592004-08-14 13:30:02 +000064def _samefile(src, dst):
65 # Macintosh, Unix.
Tarek Ziadé1eab9cc2010-04-19 21:19:57 +000066 if hasattr(os.path, 'samefile'):
Johannes Gijsbersf9a098e2004-08-14 14:51:01 +000067 try:
68 return os.path.samefile(src, dst)
69 except OSError:
70 return False
Johannes Gijsbers46f14592004-08-14 13:30:02 +000071
72 # All other platforms: check for same pathname.
73 return (os.path.normcase(os.path.abspath(src)) ==
74 os.path.normcase(os.path.abspath(dst)))
Tim Peters495ad3c2001-01-15 01:36:40 +000075
Guido van Rossumc6360141990-10-13 19:23:40 +000076def copyfile(src, dst):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +000077 """Copy data from src to dst"""
Johannes Gijsbers46f14592004-08-14 13:30:02 +000078 if _samefile(src, dst):
Collin Winterce36ad82007-08-30 01:19:48 +000079 raise Error("`%s` and `%s` are the same file" % (src, dst))
Johannes Gijsbers46f14592004-08-14 13:30:02 +000080
Guido van Rossuma2baf461997-04-29 14:06:46 +000081 fsrc = None
82 fdst = None
Antoine Pitrou7fff0962009-05-01 21:09:44 +000083 for fn in [src, dst]:
84 try:
85 st = os.stat(fn)
86 except OSError:
87 # File most likely does not exist
88 pass
Benjamin Petersonc0d98aa2009-06-05 19:13:27 +000089 else:
90 # XXX What about other special files? (sockets, devices...)
91 if stat.S_ISFIFO(st.st_mode):
92 raise SpecialFileError("`%s` is a named pipe" % fn)
Guido van Rossuma2baf461997-04-29 14:06:46 +000093 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000094 fsrc = open(src, 'rb')
95 fdst = open(dst, 'wb')
Greg Stein42bb8b32000-07-12 09:55:30 +000096 copyfileobj(fsrc, fdst)
Guido van Rossuma2baf461997-04-29 14:06:46 +000097 finally:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000098 if fdst:
99 fdst.close()
100 if fsrc:
101 fsrc.close()
Guido van Rossumc6360141990-10-13 19:23:40 +0000102
Guido van Rossumc6360141990-10-13 19:23:40 +0000103def copymode(src, dst):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000104 """Copy mode bits from src to dst"""
Tim Peters0c947242001-01-21 20:00:00 +0000105 if hasattr(os, 'chmod'):
106 st = os.stat(src)
Walter Dörwald294bbf32002-06-06 09:48:13 +0000107 mode = stat.S_IMODE(st.st_mode)
Tim Peters0c947242001-01-21 20:00:00 +0000108 os.chmod(dst, mode)
Guido van Rossumc6360141990-10-13 19:23:40 +0000109
Guido van Rossumc6360141990-10-13 19:23:40 +0000110def copystat(src, dst):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000111 """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
Guido van Rossuma2baf461997-04-29 14:06:46 +0000112 st = os.stat(src)
Walter Dörwald294bbf32002-06-06 09:48:13 +0000113 mode = stat.S_IMODE(st.st_mode)
Tim Peters0c947242001-01-21 20:00:00 +0000114 if hasattr(os, 'utime'):
Walter Dörwald294bbf32002-06-06 09:48:13 +0000115 os.utime(dst, (st.st_atime, st.st_mtime))
Tim Peters0c947242001-01-21 20:00:00 +0000116 if hasattr(os, 'chmod'):
117 os.chmod(dst, mode)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000118 if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
Antoine Pitrou910bd512010-03-22 20:11:09 +0000119 try:
120 os.chflags(dst, st.st_flags)
121 except OSError as why:
Tarek Ziadé1eab9cc2010-04-19 21:19:57 +0000122 if (not hasattr(errno, 'EOPNOTSUPP') or
123 why.errno != errno.EOPNOTSUPP):
Antoine Pitrou910bd512010-03-22 20:11:09 +0000124 raise
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000125
Guido van Rossumc6360141990-10-13 19:23:40 +0000126def copy(src, dst):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000127 """Copy data and mode bits ("cp src dst").
Tim Peters495ad3c2001-01-15 01:36:40 +0000128
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000129 The destination may be a directory.
130
131 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000132 if os.path.isdir(dst):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000133 dst = os.path.join(dst, os.path.basename(src))
Guido van Rossuma2baf461997-04-29 14:06:46 +0000134 copyfile(src, dst)
135 copymode(src, dst)
Guido van Rossumc6360141990-10-13 19:23:40 +0000136
Guido van Rossumc6360141990-10-13 19:23:40 +0000137def copy2(src, dst):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000138 """Copy data and all stat info ("cp -p src dst").
139
140 The destination may be a directory.
141
142 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000143 if os.path.isdir(dst):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 dst = os.path.join(dst, os.path.basename(src))
Guido van Rossuma2baf461997-04-29 14:06:46 +0000145 copyfile(src, dst)
146 copystat(src, dst)
Guido van Rossumc6360141990-10-13 19:23:40 +0000147
Georg Brandl2ee470f2008-07-16 12:55:28 +0000148def ignore_patterns(*patterns):
149 """Function that can be used as copytree() ignore parameter.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000150
Georg Brandl2ee470f2008-07-16 12:55:28 +0000151 Patterns is a sequence of glob-style patterns
152 that are used to exclude files"""
153 def _ignore_patterns(path, names):
154 ignored_names = []
155 for pattern in patterns:
156 ignored_names.extend(fnmatch.filter(names, pattern))
157 return set(ignored_names)
158 return _ignore_patterns
159
Tarek Ziadéfb437512010-04-20 08:57:33 +0000160def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
161 ignore_dangling_symlinks=False):
Tarek Ziadé5340db32010-04-19 22:30:51 +0000162 """Recursively copy a directory tree.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000163
164 The destination directory must not already exist.
Neal Norwitza4c93b62003-02-23 21:36:32 +0000165 If exception(s) occur, an Error is raised with a list of reasons.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000166
167 If the optional symlinks flag is true, symbolic links in the
168 source tree result in symbolic links in the destination tree; if
169 it is false, the contents of the files pointed to by symbolic
Tarek Ziadéfb437512010-04-20 08:57:33 +0000170 links are copied. If the file pointed by the symlink doesn't
171 exist, an exception will be added in the list of errors raised in
172 an Error exception at the end of the copy process.
173
174 You can set the optional ignore_dangling_symlinks flag to true if you
Tarek Ziadé8c26c7d2010-04-23 13:03:50 +0000175 want to silence this exception. Notice that this has no effect on
176 platforms that don't support os.symlink.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000177
Georg Brandl2ee470f2008-07-16 12:55:28 +0000178 The optional ignore argument is a callable. If given, it
179 is called with the `src` parameter, which is the directory
180 being visited by copytree(), and `names` which is the list of
181 `src` contents, as returned by os.listdir():
182
183 callable(src, names) -> ignored_names
184
185 Since copytree() is called recursively, the callable will be
186 called once for each directory that is copied. It returns a
187 list of names relative to the `src` directory that should
188 not be copied.
189
Tarek Ziadé5340db32010-04-19 22:30:51 +0000190 The optional copy_function argument is a callable that will be used
191 to copy each file. It will be called with the source path and the
192 destination path as arguments. By default, copy2() is used, but any
193 function that supports the same signature (like copy()) can be used.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000194
195 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000196 names = os.listdir(src)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000197 if ignore is not None:
198 ignored_names = ignore(src, names)
199 else:
200 ignored_names = set()
201
Johannes Gijsberse4172ea2005-01-08 12:31:29 +0000202 os.makedirs(dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000203 errors = []
Guido van Rossuma2baf461997-04-29 14:06:46 +0000204 for name in names:
Georg Brandl2ee470f2008-07-16 12:55:28 +0000205 if name in ignored_names:
206 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000207 srcname = os.path.join(src, name)
208 dstname = os.path.join(dst, name)
209 try:
Tarek Ziadéfb437512010-04-20 08:57:33 +0000210 if os.path.islink(srcname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000211 linkto = os.readlink(srcname)
Tarek Ziadéfb437512010-04-20 08:57:33 +0000212 if symlinks:
213 os.symlink(linkto, dstname)
214 else:
215 # ignore dangling symlink if the flag is on
216 if not os.path.exists(linkto) and ignore_dangling_symlinks:
217 continue
218 # otherwise let the copy occurs. copy2 will raise an error
219 copy_function(srcname, dstname)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000220 elif os.path.isdir(srcname):
Tarek Ziadé5340db32010-04-19 22:30:51 +0000221 copytree(srcname, dstname, symlinks, ignore, copy_function)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000222 else:
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000223 # Will raise a SpecialFileError for unsupported file types
Tarek Ziadé5340db32010-04-19 22:30:51 +0000224 copy_function(srcname, dstname)
Georg Brandla1be88e2005-08-31 22:48:45 +0000225 # catch the Error from the recursive copytree so that we can
226 # continue with other files
Guido van Rossumb940e112007-01-10 16:19:56 +0000227 except Error as err:
Georg Brandla1be88e2005-08-31 22:48:45 +0000228 errors.extend(err.args[0])
Antoine Pitrou7fff0962009-05-01 21:09:44 +0000229 except EnvironmentError as why:
230 errors.append((srcname, dstname, str(why)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000231 try:
232 copystat(src, dst)
Guido van Rossumb940e112007-01-10 16:19:56 +0000233 except OSError as why:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000234 if WindowsError is not None and isinstance(why, WindowsError):
235 # Copying file access times may fail on Windows
236 pass
237 else:
238 errors.extend((src, dst, str(why)))
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000239 if errors:
Collin Winterce36ad82007-08-30 01:19:48 +0000240 raise Error(errors)
Guido van Rossumd7673291998-02-06 21:38:09 +0000241
Barry Warsaw234d9a92003-01-24 17:36:15 +0000242def rmtree(path, ignore_errors=False, onerror=None):
Guido van Rossumd7673291998-02-06 21:38:09 +0000243 """Recursively delete a directory tree.
244
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000245 If ignore_errors is set, errors are ignored; otherwise, if onerror
246 is set, it is called to handle the error with arguments (func,
247 path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
248 path is the argument to that function that caused it to fail; and
249 exc_info is a tuple returned by sys.exc_info(). If ignore_errors
250 is false and onerror is None, an exception is raised.
251
Guido van Rossumd7673291998-02-06 21:38:09 +0000252 """
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000253 if ignore_errors:
254 def onerror(*args):
Barry Warsaw234d9a92003-01-24 17:36:15 +0000255 pass
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000256 elif onerror is None:
257 def onerror(*args):
258 raise
Christian Heimes9bd667a2008-01-20 15:14:11 +0000259 try:
260 if os.path.islink(path):
261 # symlinks to directories are forbidden, see bug #1669
262 raise OSError("Cannot call rmtree on a symbolic link")
263 except OSError:
264 onerror(os.path.islink, path, sys.exc_info())
265 # can't continue even if onerror hook returns
266 return
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000267 names = []
268 try:
269 names = os.listdir(path)
Guido van Rossumb940e112007-01-10 16:19:56 +0000270 except os.error as err:
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000271 onerror(os.listdir, path, sys.exc_info())
272 for name in names:
273 fullname = os.path.join(path, name)
274 try:
275 mode = os.lstat(fullname).st_mode
276 except os.error:
277 mode = 0
278 if stat.S_ISDIR(mode):
279 rmtree(fullname, ignore_errors, onerror)
Barry Warsaw234d9a92003-01-24 17:36:15 +0000280 else:
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000281 try:
282 os.remove(fullname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000283 except os.error as err:
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000284 onerror(os.remove, fullname, sys.exc_info())
285 try:
286 os.rmdir(path)
287 except os.error:
288 onerror(os.rmdir, path, sys.exc_info())
Guido van Rossumd7673291998-02-06 21:38:09 +0000289
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000290
Christian Heimesada8c3b2008-03-18 18:26:33 +0000291def _basename(path):
292 # A basename() variant which first strips the trailing slash, if present.
293 # Thus we always get the last component of the path, even for directories.
294 return os.path.basename(path.rstrip(os.path.sep))
295
296def move(src, dst):
297 """Recursively move a file or directory to another location. This is
298 similar to the Unix "mv" command.
299
300 If the destination is a directory or a symlink to a directory, the source
301 is moved inside the directory. The destination path must not already
302 exist.
303
304 If the destination already exists but is not a directory, it may be
305 overwritten depending on os.rename() semantics.
306
307 If the destination is on our current filesystem, then rename() is used.
308 Otherwise, src is copied to the destination and then removed.
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000309 A lot more could be done here... A look at a mv.c shows a lot of
310 the issues this implementation glosses over.
311
312 """
Christian Heimesada8c3b2008-03-18 18:26:33 +0000313 real_dst = dst
314 if os.path.isdir(dst):
315 real_dst = os.path.join(dst, _basename(src))
316 if os.path.exists(real_dst):
317 raise Error("Destination path '%s' already exists" % real_dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000318 try:
Christian Heimesada8c3b2008-03-18 18:26:33 +0000319 os.rename(src, real_dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000320 except OSError:
321 if os.path.isdir(src):
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000322 if _destinsrc(src, dst):
Collin Winterce36ad82007-08-30 01:19:48 +0000323 raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))
Christian Heimesada8c3b2008-03-18 18:26:33 +0000324 copytree(src, real_dst, symlinks=True)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000325 rmtree(src)
326 else:
Christian Heimesada8c3b2008-03-18 18:26:33 +0000327 copy2(src, real_dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000328 os.unlink(src)
Brett Cannon1c3fa182004-06-19 21:11:35 +0000329
Benjamin Peterson247a9b82009-02-20 04:09:19 +0000330def _destinsrc(src, dst):
Antoine Pitrou0dcc3cd2009-01-29 20:26:59 +0000331 src = abspath(src)
332 dst = abspath(dst)
333 if not src.endswith(os.path.sep):
334 src += os.path.sep
335 if not dst.endswith(os.path.sep):
336 dst += os.path.sep
337 return dst.startswith(src)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000338
339def _get_gid(name):
340 """Returns a gid, given a group name."""
341 if getgrnam is None or name is None:
342 return None
343 try:
344 result = getgrnam(name)
345 except KeyError:
346 result = None
347 if result is not None:
348 return result[2]
349 return None
350
351def _get_uid(name):
352 """Returns an uid, given a user name."""
353 if getpwnam is None or name is None:
354 return None
355 try:
356 result = getpwnam(name)
357 except KeyError:
358 result = None
359 if result is not None:
360 return result[2]
361 return None
362
363def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
364 owner=None, group=None, logger=None):
365 """Create a (possibly compressed) tar file from all the files under
366 'base_dir'.
367
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000368 'compress' must be "gzip" (the default), "bzip2", or None.
Tarek Ziadé396fad72010-02-23 05:30:31 +0000369
370 'owner' and 'group' can be used to define an owner and a group for the
371 archive that is being built. If not provided, the current owner and group
372 will be used.
373
374 The output tar file will be named 'base_dir' + ".tar", possibly plus
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000375 the appropriate compression extension (".gz", or ".bz2").
Tarek Ziadé396fad72010-02-23 05:30:31 +0000376
377 Returns the output filename.
378 """
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000379 tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: ''}
380 compress_ext = {'gzip': '.gz', 'bzip2': '.bz2'}
Tarek Ziadé396fad72010-02-23 05:30:31 +0000381
382 # flags for compression program, each element of list will be an argument
383 if compress is not None and compress not in compress_ext.keys():
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000384 raise ValueError("bad value for 'compress': must be None, 'gzip', or "
385 "'bzip2'")
Tarek Ziadé396fad72010-02-23 05:30:31 +0000386
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000387 archive_name = base_name + '.tar' + compress_ext.get(compress, '')
Tarek Ziadé396fad72010-02-23 05:30:31 +0000388 archive_dir = os.path.dirname(archive_name)
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000389
Tarek Ziadé396fad72010-02-23 05:30:31 +0000390 if not os.path.exists(archive_dir):
391 logger.info("creating %s" % archive_dir)
392 if not dry_run:
393 os.makedirs(archive_dir)
394
Tarek Ziadé396fad72010-02-23 05:30:31 +0000395 # creating the tarball
Tarek Ziadé396fad72010-02-23 05:30:31 +0000396 if logger is not None:
397 logger.info('Creating tar archive')
398
399 uid = _get_uid(owner)
400 gid = _get_gid(group)
401
402 def _set_uid_gid(tarinfo):
403 if gid is not None:
404 tarinfo.gid = gid
405 tarinfo.gname = group
406 if uid is not None:
407 tarinfo.uid = uid
408 tarinfo.uname = owner
409 return tarinfo
410
411 if not dry_run:
412 tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
413 try:
414 tar.add(base_dir, filter=_set_uid_gid)
415 finally:
416 tar.close()
417
Tarek Ziadé396fad72010-02-23 05:30:31 +0000418 return archive_name
419
Tarek Ziadée2124162010-04-21 13:35:21 +0000420def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
Tarek Ziadé396fad72010-02-23 05:30:31 +0000421 # XXX see if we want to keep an external call here
422 if verbose:
423 zipoptions = "-r"
424 else:
425 zipoptions = "-rq"
426 from distutils.errors import DistutilsExecError
427 from distutils.spawn import spawn
428 try:
429 spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
430 except DistutilsExecError:
431 # XXX really should distinguish between "couldn't find
432 # external 'zip' command" and "zip failed".
433 raise ExecError("unable to create zip file '%s': "
434 "could neither import the 'zipfile' module nor "
435 "find a standalone zip utility") % zip_filename
436
437def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
438 """Create a zip file from all the files under 'base_dir'.
439
440 The output zip file will be named 'base_dir' + ".zip". Uses either the
441 "zipfile" Python module (if available) or the InfoZIP "zip" utility
442 (if installed and found on the default search path). If neither tool is
443 available, raises ExecError. Returns the name of the output zip
444 file.
445 """
446 zip_filename = base_name + ".zip"
447 archive_dir = os.path.dirname(base_name)
448
449 if not os.path.exists(archive_dir):
450 if logger is not None:
451 logger.info("creating %s", archive_dir)
452 if not dry_run:
453 os.makedirs(archive_dir)
454
455 # If zipfile module is not available, try spawning an external 'zip'
456 # command.
457 try:
458 import zipfile
459 except ImportError:
460 zipfile = None
461
462 if zipfile is None:
Tarek Ziadée2124162010-04-21 13:35:21 +0000463 _call_external_zip(base_dir, zip_filename, verbose, dry_run)
Tarek Ziadé396fad72010-02-23 05:30:31 +0000464 else:
465 if logger is not None:
466 logger.info("creating '%s' and adding '%s' to it",
467 zip_filename, base_dir)
468
469 if not dry_run:
470 zip = zipfile.ZipFile(zip_filename, "w",
471 compression=zipfile.ZIP_DEFLATED)
472
473 for dirpath, dirnames, filenames in os.walk(base_dir):
474 for name in filenames:
475 path = os.path.normpath(os.path.join(dirpath, name))
476 if os.path.isfile(path):
477 zip.write(path, path)
478 if logger is not None:
479 logger.info("adding '%s'", path)
480 zip.close()
481
482 return zip_filename
483
484_ARCHIVE_FORMATS = {
485 'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
486 'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
Tarek Ziadé396fad72010-02-23 05:30:31 +0000487 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
488 'zip': (_make_zipfile, [],"ZIP file")
489 }
490
491def get_archive_formats():
492 """Returns a list of supported formats for archiving and unarchiving.
493
494 Each element of the returned sequence is a tuple (name, description)
495 """
496 formats = [(name, registry[2]) for name, registry in
497 _ARCHIVE_FORMATS.items()]
498 formats.sort()
499 return formats
500
501def register_archive_format(name, function, extra_args=None, description=''):
502 """Registers an archive format.
503
504 name is the name of the format. function is the callable that will be
505 used to create archives. If provided, extra_args is a sequence of
506 (name, value) tuples that will be passed as arguments to the callable.
507 description can be provided to describe the format, and will be returned
508 by the get_archive_formats() function.
509 """
510 if extra_args is None:
511 extra_args = []
512 if not isinstance(function, collections.Callable):
513 raise TypeError('The %s object is not callable' % function)
514 if not isinstance(extra_args, (tuple, list)):
515 raise TypeError('extra_args needs to be a sequence')
516 for element in extra_args:
517 if not isinstance(element, (tuple, list)) or len(element) !=2 :
518 raise TypeError('extra_args elements are : (arg_name, value)')
519
520 _ARCHIVE_FORMATS[name] = (function, extra_args, description)
521
522def unregister_archive_format(name):
523 del _ARCHIVE_FORMATS[name]
524
525def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
526 dry_run=0, owner=None, group=None, logger=None):
527 """Create an archive file (eg. zip or tar).
528
529 'base_name' is the name of the file to create, minus any format-specific
Tarek Ziadé5e2be872010-04-20 21:40:47 +0000530 extension; 'format' is the archive format: one of "zip", "tar", "bztar"
531 or "gztar".
Tarek Ziadé396fad72010-02-23 05:30:31 +0000532
533 'root_dir' is a directory that will be the root directory of the
534 archive; ie. we typically chdir into 'root_dir' before creating the
535 archive. 'base_dir' is the directory where we start archiving from;
536 ie. 'base_dir' will be the common prefix of all files and
537 directories in the archive. 'root_dir' and 'base_dir' both default
538 to the current directory. Returns the name of the archive file.
539
540 'owner' and 'group' are used when creating a tar archive. By default,
541 uses the current owner and group.
542 """
543 save_cwd = os.getcwd()
544 if root_dir is not None:
545 if logger is not None:
546 logger.debug("changing into '%s'", root_dir)
547 base_name = os.path.abspath(base_name)
548 if not dry_run:
549 os.chdir(root_dir)
550
551 if base_dir is None:
552 base_dir = os.curdir
553
554 kwargs = {'dry_run': dry_run, 'logger': logger}
555
556 try:
557 format_info = _ARCHIVE_FORMATS[format]
558 except KeyError:
559 raise ValueError("unknown archive format '%s'" % format)
560
561 func = format_info[0]
562 for arg, val in format_info[1]:
563 kwargs[arg] = val
564
565 if format != 'zip':
566 kwargs['owner'] = owner
567 kwargs['group'] = group
568
569 try:
570 filename = func(base_name, base_dir, **kwargs)
571 finally:
572 if root_dir is not None:
573 if logger is not None:
574 logger.debug("changing back to '%s'", save_cwd)
575 os.chdir(save_cwd)
576
577 return filename
Tarek Ziadé6ac91722010-04-28 17:51:36 +0000578
579
580def get_unpack_formats():
581 """Returns a list of supported formats for unpacking.
582
583 Each element of the returned sequence is a tuple
584 (name, extensions, description)
585 """
586 formats = [(name, info[0], info[3]) for name, info in
587 _UNPACK_FORMATS.items()]
588 formats.sort()
589 return formats
590
591def _check_unpack_options(extensions, function, extra_args):
592 """Checks what gets registered as an unpacker."""
593 # first make sure no other unpacker is registered for this extension
594 existing_extensions = {}
595 for name, info in _UNPACK_FORMATS.items():
596 for ext in info[0]:
597 existing_extensions[ext] = name
598
599 for extension in extensions:
600 if extension in existing_extensions:
601 msg = '%s is already registered for "%s"'
602 raise RegistryError(msg % (extension,
603 existing_extensions[extension]))
604
605 if not isinstance(function, collections.Callable):
606 raise TypeError('The registered function must be a callable')
607
608
609def register_unpack_format(name, extensions, function, extra_args=None,
610 description=''):
611 """Registers an unpack format.
612
613 `name` is the name of the format. `extensions` is a list of extensions
614 corresponding to the format.
615
616 `function` is the callable that will be
617 used to unpack archives. The callable will receive archives to unpack.
618 If it's unable to handle an archive, it needs to raise a ReadError
619 exception.
620
621 If provided, `extra_args` is a sequence of
622 (name, value) tuples that will be passed as arguments to the callable.
623 description can be provided to describe the format, and will be returned
624 by the get_unpack_formats() function.
625 """
626 if extra_args is None:
627 extra_args = []
628 _check_unpack_options(extensions, function, extra_args)
629 _UNPACK_FORMATS[name] = extensions, function, extra_args, description
630
631def unregister_unpack_format(name):
632 """Removes the pack format from the registery."""
633 del _UNPACK_FORMATS[name]
634
635def _ensure_directory(path):
636 """Ensure that the parent directory of `path` exists"""
637 dirname = os.path.dirname(path)
638 if not os.path.isdir(dirname):
639 os.makedirs(dirname)
640
641def _unpack_zipfile(filename, extract_dir):
642 """Unpack zip `filename` to `extract_dir`
643 """
644 try:
645 import zipfile
646 except ImportError:
647 raise ReadError('zlib not supported, cannot unpack this archive.')
648
649 if not zipfile.is_zipfile(filename):
650 raise ReadError("%s is not a zip file" % filename)
651
652 zip = zipfile.ZipFile(filename)
653 try:
654 for info in zip.infolist():
655 name = info.filename
656
657 # don't extract absolute paths or ones with .. in them
658 if name.startswith('/') or '..' in name:
659 continue
660
661 target = os.path.join(extract_dir, *name.split('/'))
662 if not target:
663 continue
664
665 _ensure_directory(target)
666 if not name.endswith('/'):
667 # file
668 data = zip.read(info.filename)
669 f = open(target,'wb')
670 try:
671 f.write(data)
672 finally:
673 f.close()
674 del data
675 finally:
676 zip.close()
677
678def _unpack_tarfile(filename, extract_dir):
679 """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
680 """
681 try:
682 tarobj = tarfile.open(filename)
683 except tarfile.TarError:
684 raise ReadError(
685 "%s is not a compressed or uncompressed tar file" % filename)
686 try:
687 tarobj.extractall(extract_dir)
688 finally:
689 tarobj.close()
690
691_UNPACK_FORMATS = {
692 'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"),
693 'bztar': (['.bz2'], _unpack_tarfile, [], "bzip2'ed tar-file"),
694 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"),
695 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file")
696 }
697
698def _find_unpack_format(filename):
699 for name, info in _UNPACK_FORMATS.items():
700 for extension in info[0]:
701 if filename.endswith(extension):
702 return name
703 return None
704
705def unpack_archive(filename, extract_dir=None, format=None):
706 """Unpack an archive.
707
708 `filename` is the name of the archive.
709
710 `extract_dir` is the name of the target directory, where the archive
711 is unpacked. If not provided, the current working directory is used.
712
713 `format` is the archive format: one of "zip", "tar", or "gztar". Or any
714 other registered format. If not provided, unpack_archive will use the
715 filename extension and see if an unpacker was registered for that
716 extension.
717
718 In case none is found, a ValueError is raised.
719 """
720 if extract_dir is None:
721 extract_dir = os.getcwd()
722
723 if format is not None:
724 try:
725 format_info = _UNPACK_FORMATS[format]
726 except KeyError:
727 raise ValueError("Unknown unpack format '{0}'".format(format))
728
729 func = format_info[0]
730 func(filename, extract_dir, **dict(format_info[1]))
731 else:
732 # we need to look at the registered unpackers supported extensions
733 format = _find_unpack_format(filename)
734 if format is None:
735 raise ReadError("Unknown archive format '{0}'".format(filename))
736
737 func = _UNPACK_FORMATS[format][1]
738 kwargs = dict(_UNPACK_FORMATS[format][2])
739 func(filename, extract_dir, **kwargs)