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