blob: 0cc9262cd3eccad7696334e7577e00dda2f5092d [file] [log] [blame]
Tarek Ziadé2900c442010-02-23 05:36:41 +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 Brandle78fbcc2008-07-05 10:13:36 +000011import fnmatch
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000012from warnings import warn
13
14try:
15 from pwd import getpwnam
16except ImportError:
17 getpwnam = None
18
19try:
20 from grp import getgrnam
21except ImportError:
22 getgrnam = None
Guido van Rossumc6360141990-10-13 19:23:40 +000023
Tarek Ziadé2900c442010-02-23 05:36:41 +000024__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
25 "copytree", "move", "rmtree", "Error", "SpecialFileError",
26 "ExecError", "make_archive", "get_archive_formats",
27 "register_archive_format", "unregister_archive_format"]
Martin v. Löwise9ce0b02002-10-07 13:23:24 +000028
Neal Norwitz4ce69a52005-09-01 00:45:28 +000029class Error(EnvironmentError):
Martin v. Löwise9ce0b02002-10-07 13:23:24 +000030 pass
Guido van Rossumc6360141990-10-13 19:23:40 +000031
Antoine Pitrou1fc02312009-05-01 20:55:35 +000032class SpecialFileError(EnvironmentError):
33 """Raised when trying to do a kind of operation (e.g. copying) which is
34 not supported on a special file (e.g. a named pipe)"""
35
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +000036class ExecError(EnvironmentError):
37 """Raised when a command could not be executed"""
38
Antoine Pitrou9fcd4b32008-08-11 17:21:36 +000039try:
40 WindowsError
41except NameError:
42 WindowsError = None
43
Greg Stein42bb8b32000-07-12 09:55:30 +000044def copyfileobj(fsrc, fdst, length=16*1024):
45 """copy data from file-like object fsrc to file-like object fdst"""
46 while 1:
47 buf = fsrc.read(length)
48 if not buf:
49 break
50 fdst.write(buf)
51
Johannes Gijsbers46f14592004-08-14 13:30:02 +000052def _samefile(src, dst):
53 # Macintosh, Unix.
54 if hasattr(os.path,'samefile'):
Johannes Gijsbersf9a098e2004-08-14 14:51:01 +000055 try:
56 return os.path.samefile(src, dst)
57 except OSError:
58 return False
Johannes Gijsbers46f14592004-08-14 13:30:02 +000059
60 # All other platforms: check for same pathname.
61 return (os.path.normcase(os.path.abspath(src)) ==
62 os.path.normcase(os.path.abspath(dst)))
Tim Peters495ad3c2001-01-15 01:36:40 +000063
Guido van Rossumc6360141990-10-13 19:23:40 +000064def copyfile(src, dst):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +000065 """Copy data from src to dst"""
Johannes Gijsbers46f14592004-08-14 13:30:02 +000066 if _samefile(src, dst):
67 raise Error, "`%s` and `%s` are the same file" % (src, dst)
68
Guido van Rossuma2baf461997-04-29 14:06:46 +000069 fsrc = None
70 fdst = None
Antoine Pitrou1fc02312009-05-01 20:55:35 +000071 for fn in [src, dst]:
72 try:
73 st = os.stat(fn)
74 except OSError:
75 # File most likely does not exist
76 pass
Benjamin Petersona663a372009-06-05 19:09:28 +000077 else:
78 # XXX What about other special files? (sockets, devices...)
79 if stat.S_ISFIFO(st.st_mode):
80 raise SpecialFileError("`%s` is a named pipe" % fn)
Guido van Rossuma2baf461997-04-29 14:06:46 +000081 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000082 fsrc = open(src, 'rb')
83 fdst = open(dst, 'wb')
Greg Stein42bb8b32000-07-12 09:55:30 +000084 copyfileobj(fsrc, fdst)
Guido van Rossuma2baf461997-04-29 14:06:46 +000085 finally:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000086 if fdst:
87 fdst.close()
88 if fsrc:
89 fsrc.close()
Guido van Rossumc6360141990-10-13 19:23:40 +000090
Guido van Rossumc6360141990-10-13 19:23:40 +000091def copymode(src, dst):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +000092 """Copy mode bits from src to dst"""
Tim Peters0c947242001-01-21 20:00:00 +000093 if hasattr(os, 'chmod'):
94 st = os.stat(src)
Walter Dörwald294bbf32002-06-06 09:48:13 +000095 mode = stat.S_IMODE(st.st_mode)
Tim Peters0c947242001-01-21 20:00:00 +000096 os.chmod(dst, mode)
Guido van Rossumc6360141990-10-13 19:23:40 +000097
Guido van Rossumc6360141990-10-13 19:23:40 +000098def copystat(src, dst):
Martin v. Löwis382abef2007-02-19 10:55:19 +000099 """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
Guido van Rossuma2baf461997-04-29 14:06:46 +0000100 st = os.stat(src)
Walter Dörwald294bbf32002-06-06 09:48:13 +0000101 mode = stat.S_IMODE(st.st_mode)
Tim Peters0c947242001-01-21 20:00:00 +0000102 if hasattr(os, 'utime'):
Walter Dörwald294bbf32002-06-06 09:48:13 +0000103 os.utime(dst, (st.st_atime, st.st_mtime))
Tim Peters0c947242001-01-21 20:00:00 +0000104 if hasattr(os, 'chmod'):
105 os.chmod(dst, mode)
Martin v. Löwis382abef2007-02-19 10:55:19 +0000106 if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
107 os.chflags(dst, st.st_flags)
Guido van Rossumc6360141990-10-13 19:23:40 +0000108
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000109
Guido van Rossumc6360141990-10-13 19:23:40 +0000110def copy(src, dst):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000111 """Copy data and mode bits ("cp src dst").
Tim Peters495ad3c2001-01-15 01:36:40 +0000112
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000113 The destination may be a directory.
114
115 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000116 if os.path.isdir(dst):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000117 dst = os.path.join(dst, os.path.basename(src))
Guido van Rossuma2baf461997-04-29 14:06:46 +0000118 copyfile(src, dst)
119 copymode(src, dst)
Guido van Rossumc6360141990-10-13 19:23:40 +0000120
Guido van Rossumc6360141990-10-13 19:23:40 +0000121def copy2(src, dst):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000122 """Copy data and all stat info ("cp -p src dst").
123
124 The destination may be a directory.
125
126 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000127 if os.path.isdir(dst):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000128 dst = os.path.join(dst, os.path.basename(src))
Guido van Rossuma2baf461997-04-29 14:06:46 +0000129 copyfile(src, dst)
130 copystat(src, dst)
Guido van Rossumc6360141990-10-13 19:23:40 +0000131
Georg Brandle78fbcc2008-07-05 10:13:36 +0000132def ignore_patterns(*patterns):
133 """Function that can be used as copytree() ignore parameter.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000134
Georg Brandle78fbcc2008-07-05 10:13:36 +0000135 Patterns is a sequence of glob-style patterns
136 that are used to exclude files"""
137 def _ignore_patterns(path, names):
138 ignored_names = []
139 for pattern in patterns:
140 ignored_names.extend(fnmatch.filter(names, pattern))
141 return set(ignored_names)
142 return _ignore_patterns
143
144def copytree(src, dst, symlinks=False, ignore=None):
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000145 """Recursively copy a directory tree using copy2().
146
147 The destination directory must not already exist.
Neal Norwitza4c93b62003-02-23 21:36:32 +0000148 If exception(s) occur, an Error is raised with a list of reasons.
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000149
150 If the optional symlinks flag is true, symbolic links in the
151 source tree result in symbolic links in the destination tree; if
152 it is false, the contents of the files pointed to by symbolic
153 links are copied.
154
Georg Brandle78fbcc2008-07-05 10:13:36 +0000155 The optional ignore argument is a callable. If given, it
156 is called with the `src` parameter, which is the directory
157 being visited by copytree(), and `names` which is the list of
158 `src` contents, as returned by os.listdir():
159
160 callable(src, names) -> ignored_names
161
162 Since copytree() is called recursively, the callable will be
163 called once for each directory that is copied. It returns a
164 list of names relative to the `src` directory that should
165 not be copied.
166
Guido van Rossum9d0a3df1997-04-29 14:45:19 +0000167 XXX Consider this example code rather than the ultimate tool.
168
169 """
Guido van Rossuma2baf461997-04-29 14:06:46 +0000170 names = os.listdir(src)
Georg Brandle78fbcc2008-07-05 10:13:36 +0000171 if ignore is not None:
172 ignored_names = ignore(src, names)
173 else:
174 ignored_names = set()
175
Johannes Gijsberse4172ea2005-01-08 12:31:29 +0000176 os.makedirs(dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000177 errors = []
Guido van Rossuma2baf461997-04-29 14:06:46 +0000178 for name in names:
Georg Brandle78fbcc2008-07-05 10:13:36 +0000179 if name in ignored_names:
180 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000181 srcname = os.path.join(src, name)
182 dstname = os.path.join(dst, name)
183 try:
184 if symlinks and os.path.islink(srcname):
185 linkto = os.readlink(srcname)
186 os.symlink(linkto, dstname)
187 elif os.path.isdir(srcname):
Georg Brandle78fbcc2008-07-05 10:13:36 +0000188 copytree(srcname, dstname, symlinks, ignore)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000189 else:
Antoine Pitrou1fc02312009-05-01 20:55:35 +0000190 # Will raise a SpecialFileError for unsupported file types
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000191 copy2(srcname, dstname)
Georg Brandla1be88e2005-08-31 22:48:45 +0000192 # catch the Error from the recursive copytree so that we can
193 # continue with other files
194 except Error, err:
195 errors.extend(err.args[0])
Antoine Pitrou1fc02312009-05-01 20:55:35 +0000196 except EnvironmentError, why:
197 errors.append((srcname, dstname, str(why)))
Martin v. Löwis4e678382006-07-30 13:00:31 +0000198 try:
199 copystat(src, dst)
Martin v. Löwis4e678382006-07-30 13:00:31 +0000200 except OSError, why:
Antoine Pitrou9fcd4b32008-08-11 17:21:36 +0000201 if WindowsError is not None and isinstance(why, WindowsError):
202 # Copying file access times may fail on Windows
203 pass
204 else:
205 errors.extend((src, dst, str(why)))
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000206 if errors:
207 raise Error, errors
Guido van Rossumd7673291998-02-06 21:38:09 +0000208
Barry Warsaw234d9a92003-01-24 17:36:15 +0000209def rmtree(path, ignore_errors=False, onerror=None):
Guido van Rossumd7673291998-02-06 21:38:09 +0000210 """Recursively delete a directory tree.
211
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000212 If ignore_errors is set, errors are ignored; otherwise, if onerror
213 is set, it is called to handle the error with arguments (func,
214 path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
215 path is the argument to that function that caused it to fail; and
216 exc_info is a tuple returned by sys.exc_info(). If ignore_errors
217 is false and onerror is None, an exception is raised.
218
Guido van Rossumd7673291998-02-06 21:38:09 +0000219 """
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000220 if ignore_errors:
221 def onerror(*args):
Barry Warsaw234d9a92003-01-24 17:36:15 +0000222 pass
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000223 elif onerror is None:
224 def onerror(*args):
225 raise
Georg Brandl52353982008-01-20 14:17:42 +0000226 try:
227 if os.path.islink(path):
228 # symlinks to directories are forbidden, see bug #1669
229 raise OSError("Cannot call rmtree on a symbolic link")
230 except OSError:
231 onerror(os.path.islink, path, sys.exc_info())
232 # can't continue even if onerror hook returns
233 return
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000234 names = []
235 try:
236 names = os.listdir(path)
237 except os.error, err:
238 onerror(os.listdir, path, sys.exc_info())
239 for name in names:
240 fullname = os.path.join(path, name)
241 try:
242 mode = os.lstat(fullname).st_mode
243 except os.error:
244 mode = 0
245 if stat.S_ISDIR(mode):
246 rmtree(fullname, ignore_errors, onerror)
Barry Warsaw234d9a92003-01-24 17:36:15 +0000247 else:
Johannes Gijsbersef5ffc42004-10-31 12:05:31 +0000248 try:
249 os.remove(fullname)
250 except os.error, err:
251 onerror(os.remove, fullname, sys.exc_info())
252 try:
253 os.rmdir(path)
254 except os.error:
255 onerror(os.rmdir, path, sys.exc_info())
Guido van Rossumd7673291998-02-06 21:38:09 +0000256
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000257
Sean Reifscheider493894c2008-03-18 17:24:12 +0000258def _basename(path):
259 # A basename() variant which first strips the trailing slash, if present.
260 # Thus we always get the last component of the path, even for directories.
261 return os.path.basename(path.rstrip(os.path.sep))
262
263def move(src, dst):
264 """Recursively move a file or directory to another location. This is
265 similar to the Unix "mv" command.
266
267 If the destination is a directory or a symlink to a directory, the source
268 is moved inside the directory. The destination path must not already
269 exist.
270
271 If the destination already exists but is not a directory, it may be
272 overwritten depending on os.rename() semantics.
273
274 If the destination is on our current filesystem, then rename() is used.
275 Otherwise, src is copied to the destination and then removed.
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000276 A lot more could be done here... A look at a mv.c shows a lot of
277 the issues this implementation glosses over.
278
279 """
Sean Reifscheider493894c2008-03-18 17:24:12 +0000280 real_dst = dst
281 if os.path.isdir(dst):
282 real_dst = os.path.join(dst, _basename(src))
283 if os.path.exists(real_dst):
284 raise Error, "Destination path '%s' already exists" % real_dst
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000285 try:
Sean Reifscheider493894c2008-03-18 17:24:12 +0000286 os.rename(src, real_dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000287 except OSError:
288 if os.path.isdir(src):
Benjamin Peterson096c3ad2009-02-07 19:08:22 +0000289 if _destinsrc(src, dst):
Brett Cannon1c3fa182004-06-19 21:11:35 +0000290 raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
Sean Reifscheider493894c2008-03-18 17:24:12 +0000291 copytree(src, real_dst, symlinks=True)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000292 rmtree(src)
293 else:
Sean Reifscheider493894c2008-03-18 17:24:12 +0000294 copy2(src, real_dst)
Martin v. Löwise9ce0b02002-10-07 13:23:24 +0000295 os.unlink(src)
Brett Cannon1c3fa182004-06-19 21:11:35 +0000296
Benjamin Peterson096c3ad2009-02-07 19:08:22 +0000297def _destinsrc(src, dst):
Antoine Pitrou707c5932009-01-29 20:19:34 +0000298 src = abspath(src)
299 dst = abspath(dst)
300 if not src.endswith(os.path.sep):
301 src += os.path.sep
302 if not dst.endswith(os.path.sep):
303 dst += os.path.sep
304 return dst.startswith(src)
Tarek Ziadé48cc8dc2010-02-23 05:16:41 +0000305
306def _get_gid(name):
307 """Returns a gid, given a group name."""
308 if getgrnam is None or name is None:
309 return None
310 try:
311 result = getgrnam(name)
312 except KeyError:
313 result = None
314 if result is not None:
315 return result[2]
316 return None
317
318def _get_uid(name):
319 """Returns an uid, given a user name."""
320 if getpwnam is None or name is None:
321 return None
322 try:
323 result = getpwnam(name)
324 except KeyError:
325 result = None
326 if result is not None:
327 return result[2]
328 return None
329
330def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
331 owner=None, group=None, logger=None):
332 """Create a (possibly compressed) tar file from all the files under
333 'base_dir'.
334
335 'compress' must be "gzip" (the default), "compress", "bzip2", or None.
336 (compress will be deprecated in Python 3.2)
337
338 'owner' and 'group' can be used to define an owner and a group for the
339 archive that is being built. If not provided, the current owner and group
340 will be used.
341
342 The output tar file will be named 'base_dir' + ".tar", possibly plus
343 the appropriate compression extension (".gz", ".bz2" or ".Z").
344
345 Returns the output filename.
346 """
347 tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: '', 'compress': ''}
348 compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'compress': '.Z'}
349
350 # flags for compression program, each element of list will be an argument
351 if compress is not None and compress not in compress_ext.keys():
352 raise ValueError, \
353 ("bad value for 'compress': must be None, 'gzip', 'bzip2' "
354 "or 'compress'")
355
356 archive_name = base_name + '.tar'
357 if compress != 'compress':
358 archive_name += compress_ext.get(compress, '')
359
360 archive_dir = os.path.dirname(archive_name)
361 if not os.path.exists(archive_dir):
362 logger.info("creating %s" % archive_dir)
363 if not dry_run:
364 os.makedirs(archive_dir)
365
366
367 # creating the tarball
368 import tarfile # late import so Python build itself doesn't break
369
370 if logger is not None:
371 logger.info('Creating tar archive')
372
373 uid = _get_uid(owner)
374 gid = _get_gid(group)
375
376 def _set_uid_gid(tarinfo):
377 if gid is not None:
378 tarinfo.gid = gid
379 tarinfo.gname = group
380 if uid is not None:
381 tarinfo.uid = uid
382 tarinfo.uname = owner
383 return tarinfo
384
385 if not dry_run:
386 tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
387 try:
388 tar.add(base_dir, filter=_set_uid_gid)
389 finally:
390 tar.close()
391
392 # compression using `compress`
393 # XXX this block will be removed in Python 3.2
394 if compress == 'compress':
395 warn("'compress' will be deprecated.", PendingDeprecationWarning)
396 # the option varies depending on the platform
397 compressed_name = archive_name + compress_ext[compress]
398 if sys.platform == 'win32':
399 cmd = [compress, archive_name, compressed_name]
400 else:
401 cmd = [compress, '-f', archive_name]
402 from distutils.spawn import spawn
403 spawn(cmd, dry_run=dry_run)
404 return compressed_name
405
406 return archive_name
407
408def _call_external_zip(directory, verbose=False):
409 # XXX see if we want to keep an external call here
410 if verbose:
411 zipoptions = "-r"
412 else:
413 zipoptions = "-rq"
414 from distutils.errors import DistutilsExecError
415 from distutils.spawn import spawn
416 try:
417 spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
418 except DistutilsExecError:
419 # XXX really should distinguish between "couldn't find
420 # external 'zip' command" and "zip failed".
421 raise ExecError, \
422 ("unable to create zip file '%s': "
423 "could neither import the 'zipfile' module nor "
424 "find a standalone zip utility") % zip_filename
425
426def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
427 """Create a zip file from all the files under 'base_dir'.
428
429 The output zip file will be named 'base_dir' + ".zip". Uses either the
430 "zipfile" Python module (if available) or the InfoZIP "zip" utility
431 (if installed and found on the default search path). If neither tool is
432 available, raises ExecError. Returns the name of the output zip
433 file.
434 """
435 zip_filename = base_name + ".zip"
436 archive_dir = os.path.dirname(base_name)
437
438 if not os.path.exists(archive_dir):
439 if logger is not None:
440 logger.info("creating %s", archive_dir)
441 if not dry_run:
442 os.makedirs(archive_dir)
443
444 # If zipfile module is not available, try spawning an external 'zip'
445 # command.
446 try:
447 import zipfile
448 except ImportError:
449 zipfile = None
450
451 if zipfile is None:
452 _call_external_zip(base_dir, verbose)
453 else:
454 if logger is not None:
455 logger.info("creating '%s' and adding '%s' to it",
456 zip_filename, base_dir)
457
458 if not dry_run:
459 zip = zipfile.ZipFile(zip_filename, "w",
460 compression=zipfile.ZIP_DEFLATED)
461
462 for dirpath, dirnames, filenames in os.walk(base_dir):
463 for name in filenames:
464 path = os.path.normpath(os.path.join(dirpath, name))
465 if os.path.isfile(path):
466 zip.write(path, path)
467 if logger is not None:
468 logger.info("adding '%s'", path)
469 zip.close()
470
471 return zip_filename
472
473_ARCHIVE_FORMATS = {
474 'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
475 'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
476 'ztar': (_make_tarball, [('compress', 'compress')],
477 "compressed tar file"),
478 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
479 'zip': (_make_zipfile, [],"ZIP file")
480 }
481
482def get_archive_formats():
483 """Returns a list of supported formats for archiving and unarchiving.
484
485 Each element of the returned sequence is a tuple (name, description)
486 """
487 formats = [(name, registry[2]) for name, registry in
488 _ARCHIVE_FORMATS.items()]
489 formats.sort()
490 return formats
491
492def register_archive_format(name, function, extra_args=None, description=''):
493 """Registers an archive format.
494
495 name is the name of the format. function is the callable that will be
496 used to create archives. If provided, extra_args is a sequence of
497 (name, value) tuples that will be passed as arguments to the callable.
498 description can be provided to describe the format, and will be returned
499 by the get_archive_formats() function.
500 """
501 if extra_args is None:
502 extra_args = []
503 if not callable(function):
504 raise TypeError('The %s object is not callable' % function)
505 if not isinstance(extra_args, (tuple, list)):
506 raise TypeError('extra_args needs to be a sequence')
507 for element in extra_args:
508 if not isinstance(element, (tuple, list)) or len(element) !=2 :
509 raise TypeError('extra_args elements are : (arg_name, value)')
510
511 _ARCHIVE_FORMATS[name] = (function, extra_args, description)
512
513def unregister_archive_format(name):
514 del _ARCHIVE_FORMATS[name]
515
516def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
517 dry_run=0, owner=None, group=None, logger=None):
518 """Create an archive file (eg. zip or tar).
519
520 'base_name' is the name of the file to create, minus any format-specific
521 extension; 'format' is the archive format: one of "zip", "tar", "ztar",
522 or "gztar".
523
524 'root_dir' is a directory that will be the root directory of the
525 archive; ie. we typically chdir into 'root_dir' before creating the
526 archive. 'base_dir' is the directory where we start archiving from;
527 ie. 'base_dir' will be the common prefix of all files and
528 directories in the archive. 'root_dir' and 'base_dir' both default
529 to the current directory. Returns the name of the archive file.
530
531 'owner' and 'group' are used when creating a tar archive. By default,
532 uses the current owner and group.
533 """
534 save_cwd = os.getcwd()
535 if root_dir is not None:
536 if logger is not None:
537 logger.debug("changing into '%s'", root_dir)
538 base_name = os.path.abspath(base_name)
539 if not dry_run:
540 os.chdir(root_dir)
541
542 if base_dir is None:
543 base_dir = os.curdir
544
545 kwargs = {'dry_run': dry_run, 'logger': logger}
546
547 try:
548 format_info = _ARCHIVE_FORMATS[format]
549 except KeyError:
550 raise ValueError, "unknown archive format '%s'" % format
551
552 func = format_info[0]
553 for arg, val in format_info[1]:
554 kwargs[arg] = val
555
556 if format != 'zip':
557 kwargs['owner'] = owner
558 kwargs['group'] = group
559
560 try:
561 filename = func(base_name, base_dir, **kwargs)
562 finally:
563 if root_dir is not None:
564 if logger is not None:
565 logger.debug("changing back to '%s'", save_cwd)
566 os.chdir(save_cwd)
567
568 return filename