Tarek Ziadé | c339978 | 2010-02-23 05:39:18 +0000 | [diff] [blame] | 1 | """Utility functions for copying and archiving files and directory trees. |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 959fa01 | 1999-08-18 20:03:17 +0000 | [diff] [blame] | 3 | XXX The functions here don't copy the resource fork or other metadata on Mac. |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 4 | |
| 5 | """ |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | c96207a | 1992-03-31 18:55:40 +0000 | [diff] [blame] | 7 | import os |
Guido van Rossum | 83c03e2 | 1999-02-23 23:07:51 +0000 | [diff] [blame] | 8 | import sys |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 9 | import stat |
Brett Cannon | 1c3fa18 | 2004-06-19 21:11:35 +0000 | [diff] [blame] | 10 | from os.path import abspath |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 11 | import fnmatch |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 12 | import collections |
Antoine Pitrou | 910bd51 | 2010-03-22 20:11:09 +0000 | [diff] [blame] | 13 | import errno |
Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 14 | import tarfile |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 15 | |
| 16 | try: |
Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 17 | import bz2 |
| 18 | _BZ2_SUPPORTED = True |
| 19 | except ImportError: |
| 20 | _BZ2_SUPPORTED = False |
| 21 | |
| 22 | try: |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 23 | from pwd import getpwnam |
| 24 | except ImportError: |
| 25 | getpwnam = None |
| 26 | |
| 27 | try: |
| 28 | from grp import getgrnam |
| 29 | except ImportError: |
| 30 | getgrnam = None |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 31 | |
Tarek Ziadé | c339978 | 2010-02-23 05:39:18 +0000 | [diff] [blame] | 32 | __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", |
| 33 | "copytree", "move", "rmtree", "Error", "SpecialFileError", |
| 34 | "ExecError", "make_archive", "get_archive_formats", |
Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 35 | "register_archive_format", "unregister_archive_format", |
| 36 | "get_unpack_formats", "register_unpack_format", |
| 37 | "unregister_unpack_format", "unpack_archive"] |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 38 | |
Neal Norwitz | 4ce69a5 | 2005-09-01 00:45:28 +0000 | [diff] [blame] | 39 | class Error(EnvironmentError): |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 40 | pass |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 41 | |
Antoine Pitrou | 7fff096 | 2009-05-01 21:09:44 +0000 | [diff] [blame] | 42 | class SpecialFileError(EnvironmentError): |
| 43 | """Raised when trying to do a kind of operation (e.g. copying) which is |
| 44 | not supported on a special file (e.g. a named pipe)""" |
| 45 | |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 46 | class ExecError(EnvironmentError): |
| 47 | """Raised when a command could not be executed""" |
| 48 | |
Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 49 | class ReadError(EnvironmentError): |
| 50 | """Raised when an archive cannot be read""" |
| 51 | |
| 52 | class RegistryError(Exception): |
| 53 | """Raised when a registery operation with the archiving |
| 54 | and unpacking registeries fails""" |
| 55 | |
| 56 | |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 57 | try: |
| 58 | WindowsError |
| 59 | except NameError: |
| 60 | WindowsError = None |
| 61 | |
Greg Stein | 42bb8b3 | 2000-07-12 09:55:30 +0000 | [diff] [blame] | 62 | def copyfileobj(fsrc, fdst, length=16*1024): |
| 63 | """copy data from file-like object fsrc to file-like object fdst""" |
| 64 | while 1: |
| 65 | buf = fsrc.read(length) |
| 66 | if not buf: |
| 67 | break |
| 68 | fdst.write(buf) |
| 69 | |
Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 70 | def _samefile(src, dst): |
| 71 | # Macintosh, Unix. |
Tarek Ziadé | 1eab9cc | 2010-04-19 21:19:57 +0000 | [diff] [blame] | 72 | if hasattr(os.path, 'samefile'): |
Johannes Gijsbers | f9a098e | 2004-08-14 14:51:01 +0000 | [diff] [blame] | 73 | try: |
| 74 | return os.path.samefile(src, dst) |
| 75 | except OSError: |
| 76 | return False |
Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 77 | |
| 78 | # All other platforms: check for same pathname. |
| 79 | return (os.path.normcase(os.path.abspath(src)) == |
| 80 | os.path.normcase(os.path.abspath(dst))) |
Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 81 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 82 | def copyfile(src, dst): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 83 | """Copy data from src to dst""" |
Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 84 | if _samefile(src, dst): |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 85 | raise Error("`%s` and `%s` are the same file" % (src, dst)) |
Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 86 | |
Antoine Pitrou | 7fff096 | 2009-05-01 21:09:44 +0000 | [diff] [blame] | 87 | for fn in [src, dst]: |
| 88 | try: |
| 89 | st = os.stat(fn) |
| 90 | except OSError: |
| 91 | # File most likely does not exist |
| 92 | pass |
Benjamin Peterson | c0d98aa | 2009-06-05 19:13:27 +0000 | [diff] [blame] | 93 | else: |
| 94 | # XXX What about other special files? (sockets, devices...) |
| 95 | if stat.S_ISFIFO(st.st_mode): |
| 96 | raise SpecialFileError("`%s` is a named pipe" % fn) |
Tarek Ziadé | b01142b | 2010-05-05 22:43:04 +0000 | [diff] [blame] | 97 | |
Tarek Ziadé | ae4d5c6 | 2010-05-05 22:27:31 +0000 | [diff] [blame] | 98 | with open(src, 'rb') as fsrc: |
| 99 | with open(dst, 'wb') as fdst: |
| 100 | copyfileobj(fsrc, fdst) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 101 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 102 | def copymode(src, dst): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 103 | """Copy mode bits from src to dst""" |
Tim Peters | 0c94724 | 2001-01-21 20:00:00 +0000 | [diff] [blame] | 104 | if hasattr(os, 'chmod'): |
| 105 | st = os.stat(src) |
Walter Dörwald | 294bbf3 | 2002-06-06 09:48:13 +0000 | [diff] [blame] | 106 | mode = stat.S_IMODE(st.st_mode) |
Tim Peters | 0c94724 | 2001-01-21 20:00:00 +0000 | [diff] [blame] | 107 | os.chmod(dst, mode) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 108 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 109 | def copystat(src, dst): |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 110 | """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 111 | st = os.stat(src) |
Walter Dörwald | 294bbf3 | 2002-06-06 09:48:13 +0000 | [diff] [blame] | 112 | mode = stat.S_IMODE(st.st_mode) |
Tim Peters | 0c94724 | 2001-01-21 20:00:00 +0000 | [diff] [blame] | 113 | if hasattr(os, 'utime'): |
Walter Dörwald | 294bbf3 | 2002-06-06 09:48:13 +0000 | [diff] [blame] | 114 | os.utime(dst, (st.st_atime, st.st_mtime)) |
Tim Peters | 0c94724 | 2001-01-21 20:00:00 +0000 | [diff] [blame] | 115 | if hasattr(os, 'chmod'): |
| 116 | os.chmod(dst, mode) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 117 | if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): |
Antoine Pitrou | 910bd51 | 2010-03-22 20:11:09 +0000 | [diff] [blame] | 118 | try: |
| 119 | os.chflags(dst, st.st_flags) |
| 120 | except OSError as why: |
Tarek Ziadé | 1eab9cc | 2010-04-19 21:19:57 +0000 | [diff] [blame] | 121 | if (not hasattr(errno, 'EOPNOTSUPP') or |
| 122 | why.errno != errno.EOPNOTSUPP): |
Antoine Pitrou | 910bd51 | 2010-03-22 20:11:09 +0000 | [diff] [blame] | 123 | raise |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 124 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 125 | def copy(src, dst): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 126 | """Copy data and mode bits ("cp src dst"). |
Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 127 | |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 128 | The destination may be a directory. |
| 129 | |
| 130 | """ |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 131 | if os.path.isdir(dst): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 132 | dst = os.path.join(dst, os.path.basename(src)) |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 133 | copyfile(src, dst) |
| 134 | copymode(src, dst) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 135 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 136 | def copy2(src, dst): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 137 | """Copy data and all stat info ("cp -p src dst"). |
| 138 | |
| 139 | The destination may be a directory. |
| 140 | |
| 141 | """ |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 142 | if os.path.isdir(dst): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 143 | dst = os.path.join(dst, os.path.basename(src)) |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 144 | copyfile(src, dst) |
| 145 | copystat(src, dst) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 146 | |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 147 | def ignore_patterns(*patterns): |
| 148 | """Function that can be used as copytree() ignore parameter. |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 149 | |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 150 | Patterns is a sequence of glob-style patterns |
| 151 | that are used to exclude files""" |
| 152 | def _ignore_patterns(path, names): |
| 153 | ignored_names = [] |
| 154 | for pattern in patterns: |
| 155 | ignored_names.extend(fnmatch.filter(names, pattern)) |
| 156 | return set(ignored_names) |
| 157 | return _ignore_patterns |
| 158 | |
Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 159 | def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, |
| 160 | ignore_dangling_symlinks=False): |
Tarek Ziadé | 5340db3 | 2010-04-19 22:30:51 +0000 | [diff] [blame] | 161 | """Recursively copy a directory tree. |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 162 | |
| 163 | The destination directory must not already exist. |
Neal Norwitz | a4c93b6 | 2003-02-23 21:36:32 +0000 | [diff] [blame] | 164 | If exception(s) occur, an Error is raised with a list of reasons. |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 165 | |
| 166 | If the optional symlinks flag is true, symbolic links in the |
| 167 | source tree result in symbolic links in the destination tree; if |
| 168 | it is false, the contents of the files pointed to by symbolic |
Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 169 | links are copied. If the file pointed by the symlink doesn't |
| 170 | exist, an exception will be added in the list of errors raised in |
| 171 | an Error exception at the end of the copy process. |
| 172 | |
| 173 | You can set the optional ignore_dangling_symlinks flag to true if you |
Tarek Ziadé | 8c26c7d | 2010-04-23 13:03:50 +0000 | [diff] [blame] | 174 | want to silence this exception. Notice that this has no effect on |
| 175 | platforms that don't support os.symlink. |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 176 | |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 177 | The optional ignore argument is a callable. If given, it |
| 178 | is called with the `src` parameter, which is the directory |
| 179 | being visited by copytree(), and `names` which is the list of |
| 180 | `src` contents, as returned by os.listdir(): |
| 181 | |
| 182 | callable(src, names) -> ignored_names |
| 183 | |
| 184 | Since copytree() is called recursively, the callable will be |
| 185 | called once for each directory that is copied. It returns a |
| 186 | list of names relative to the `src` directory that should |
| 187 | not be copied. |
| 188 | |
Tarek Ziadé | 5340db3 | 2010-04-19 22:30:51 +0000 | [diff] [blame] | 189 | The optional copy_function argument is a callable that will be used |
| 190 | to copy each file. It will be called with the source path and the |
| 191 | destination path as arguments. By default, copy2() is used, but any |
| 192 | function that supports the same signature (like copy()) can be used. |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 193 | |
| 194 | """ |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 195 | names = os.listdir(src) |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 196 | if ignore is not None: |
| 197 | ignored_names = ignore(src, names) |
| 198 | else: |
| 199 | ignored_names = set() |
| 200 | |
Johannes Gijsbers | e4172ea | 2005-01-08 12:31:29 +0000 | [diff] [blame] | 201 | os.makedirs(dst) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 202 | errors = [] |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 203 | for name in names: |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 204 | if name in ignored_names: |
| 205 | continue |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 206 | srcname = os.path.join(src, name) |
| 207 | dstname = os.path.join(dst, name) |
| 208 | try: |
Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 209 | if os.path.islink(srcname): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 210 | linkto = os.readlink(srcname) |
Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 211 | if symlinks: |
| 212 | os.symlink(linkto, dstname) |
| 213 | else: |
| 214 | # ignore dangling symlink if the flag is on |
| 215 | if not os.path.exists(linkto) and ignore_dangling_symlinks: |
| 216 | continue |
| 217 | # otherwise let the copy occurs. copy2 will raise an error |
| 218 | copy_function(srcname, dstname) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 219 | elif os.path.isdir(srcname): |
Tarek Ziadé | 5340db3 | 2010-04-19 22:30:51 +0000 | [diff] [blame] | 220 | copytree(srcname, dstname, symlinks, ignore, copy_function) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 221 | else: |
Antoine Pitrou | 7fff096 | 2009-05-01 21:09:44 +0000 | [diff] [blame] | 222 | # Will raise a SpecialFileError for unsupported file types |
Tarek Ziadé | 5340db3 | 2010-04-19 22:30:51 +0000 | [diff] [blame] | 223 | copy_function(srcname, dstname) |
Georg Brandl | a1be88e | 2005-08-31 22:48:45 +0000 | [diff] [blame] | 224 | # catch the Error from the recursive copytree so that we can |
| 225 | # continue with other files |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 226 | except Error as err: |
Georg Brandl | a1be88e | 2005-08-31 22:48:45 +0000 | [diff] [blame] | 227 | errors.extend(err.args[0]) |
Antoine Pitrou | 7fff096 | 2009-05-01 21:09:44 +0000 | [diff] [blame] | 228 | except EnvironmentError as why: |
| 229 | errors.append((srcname, dstname, str(why))) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 230 | try: |
| 231 | copystat(src, dst) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 232 | except OSError as why: |
Georg Brandl | 6aa2d1f | 2008-08-12 08:35:52 +0000 | [diff] [blame] | 233 | if WindowsError is not None and isinstance(why, WindowsError): |
| 234 | # Copying file access times may fail on Windows |
| 235 | pass |
| 236 | else: |
| 237 | errors.extend((src, dst, str(why))) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 238 | if errors: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 239 | raise Error(errors) |
Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 240 | |
Barry Warsaw | 234d9a9 | 2003-01-24 17:36:15 +0000 | [diff] [blame] | 241 | def rmtree(path, ignore_errors=False, onerror=None): |
Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 242 | """Recursively delete a directory tree. |
| 243 | |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 244 | If ignore_errors is set, errors are ignored; otherwise, if onerror |
| 245 | is set, it is called to handle the error with arguments (func, |
| 246 | path, exc_info) where func is os.listdir, os.remove, or os.rmdir; |
| 247 | path is the argument to that function that caused it to fail; and |
| 248 | exc_info is a tuple returned by sys.exc_info(). If ignore_errors |
| 249 | is false and onerror is None, an exception is raised. |
| 250 | |
Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 251 | """ |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 252 | if ignore_errors: |
| 253 | def onerror(*args): |
Barry Warsaw | 234d9a9 | 2003-01-24 17:36:15 +0000 | [diff] [blame] | 254 | pass |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 255 | elif onerror is None: |
| 256 | def onerror(*args): |
| 257 | raise |
Christian Heimes | 9bd667a | 2008-01-20 15:14:11 +0000 | [diff] [blame] | 258 | try: |
| 259 | if os.path.islink(path): |
| 260 | # symlinks to directories are forbidden, see bug #1669 |
| 261 | raise OSError("Cannot call rmtree on a symbolic link") |
| 262 | except OSError: |
| 263 | onerror(os.path.islink, path, sys.exc_info()) |
| 264 | # can't continue even if onerror hook returns |
| 265 | return |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 266 | names = [] |
| 267 | try: |
| 268 | names = os.listdir(path) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 269 | except os.error as err: |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 270 | onerror(os.listdir, path, sys.exc_info()) |
| 271 | for name in names: |
| 272 | fullname = os.path.join(path, name) |
| 273 | try: |
| 274 | mode = os.lstat(fullname).st_mode |
| 275 | except os.error: |
| 276 | mode = 0 |
| 277 | if stat.S_ISDIR(mode): |
| 278 | rmtree(fullname, ignore_errors, onerror) |
Barry Warsaw | 234d9a9 | 2003-01-24 17:36:15 +0000 | [diff] [blame] | 279 | else: |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 280 | try: |
| 281 | os.remove(fullname) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 282 | except os.error as err: |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 283 | onerror(os.remove, fullname, sys.exc_info()) |
| 284 | try: |
| 285 | os.rmdir(path) |
| 286 | except os.error: |
| 287 | onerror(os.rmdir, path, sys.exc_info()) |
Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 288 | |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 289 | |
Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 290 | def _basename(path): |
| 291 | # A basename() variant which first strips the trailing slash, if present. |
| 292 | # Thus we always get the last component of the path, even for directories. |
| 293 | return os.path.basename(path.rstrip(os.path.sep)) |
| 294 | |
| 295 | def move(src, dst): |
| 296 | """Recursively move a file or directory to another location. This is |
| 297 | similar to the Unix "mv" command. |
| 298 | |
| 299 | If the destination is a directory or a symlink to a directory, the source |
| 300 | is moved inside the directory. The destination path must not already |
| 301 | exist. |
| 302 | |
| 303 | If the destination already exists but is not a directory, it may be |
| 304 | overwritten depending on os.rename() semantics. |
| 305 | |
| 306 | If the destination is on our current filesystem, then rename() is used. |
| 307 | Otherwise, src is copied to the destination and then removed. |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 308 | A lot more could be done here... A look at a mv.c shows a lot of |
| 309 | the issues this implementation glosses over. |
| 310 | |
| 311 | """ |
Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 312 | real_dst = dst |
| 313 | if os.path.isdir(dst): |
| 314 | real_dst = os.path.join(dst, _basename(src)) |
| 315 | if os.path.exists(real_dst): |
| 316 | raise Error("Destination path '%s' already exists" % real_dst) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 317 | try: |
Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 318 | os.rename(src, real_dst) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 319 | except OSError: |
| 320 | if os.path.isdir(src): |
Benjamin Peterson | 247a9b8 | 2009-02-20 04:09:19 +0000 | [diff] [blame] | 321 | if _destinsrc(src, dst): |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 322 | raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst)) |
Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 323 | copytree(src, real_dst, symlinks=True) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 324 | rmtree(src) |
| 325 | else: |
Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 326 | copy2(src, real_dst) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 327 | os.unlink(src) |
Brett Cannon | 1c3fa18 | 2004-06-19 21:11:35 +0000 | [diff] [blame] | 328 | |
Benjamin Peterson | 247a9b8 | 2009-02-20 04:09:19 +0000 | [diff] [blame] | 329 | def _destinsrc(src, dst): |
Antoine Pitrou | 0dcc3cd | 2009-01-29 20:26:59 +0000 | [diff] [blame] | 330 | src = abspath(src) |
| 331 | dst = abspath(dst) |
| 332 | if not src.endswith(os.path.sep): |
| 333 | src += os.path.sep |
| 334 | if not dst.endswith(os.path.sep): |
| 335 | dst += os.path.sep |
| 336 | return dst.startswith(src) |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 337 | |
| 338 | def _get_gid(name): |
| 339 | """Returns a gid, given a group name.""" |
| 340 | if getgrnam is None or name is None: |
| 341 | return None |
| 342 | try: |
| 343 | result = getgrnam(name) |
| 344 | except KeyError: |
| 345 | result = None |
| 346 | if result is not None: |
| 347 | return result[2] |
| 348 | return None |
| 349 | |
| 350 | def _get_uid(name): |
| 351 | """Returns an uid, given a user name.""" |
| 352 | if getpwnam is None or name is None: |
| 353 | return None |
| 354 | try: |
| 355 | result = getpwnam(name) |
| 356 | except KeyError: |
| 357 | result = None |
| 358 | if result is not None: |
| 359 | return result[2] |
| 360 | return None |
| 361 | |
| 362 | def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, |
| 363 | owner=None, group=None, logger=None): |
| 364 | """Create a (possibly compressed) tar file from all the files under |
| 365 | 'base_dir'. |
| 366 | |
Tarek Ziadé | 5e2be87 | 2010-04-20 21:40:47 +0000 | [diff] [blame] | 367 | 'compress' must be "gzip" (the default), "bzip2", or None. |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 368 | |
| 369 | 'owner' and 'group' can be used to define an owner and a group for the |
| 370 | archive that is being built. If not provided, the current owner and group |
| 371 | will be used. |
| 372 | |
Éric Araujo | 4433a5f | 2010-12-15 20:26:30 +0000 | [diff] [blame] | 373 | The output tar file will be named 'base_name' + ".tar", possibly plus |
Tarek Ziadé | 5e2be87 | 2010-04-20 21:40:47 +0000 | [diff] [blame] | 374 | the appropriate compression extension (".gz", or ".bz2"). |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 375 | |
| 376 | Returns the output filename. |
| 377 | """ |
Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 378 | tar_compression = {'gzip': 'gz', None: ''} |
| 379 | compress_ext = {'gzip': '.gz'} |
| 380 | |
| 381 | if _BZ2_SUPPORTED: |
| 382 | tar_compression['bzip2'] = 'bz2' |
| 383 | compress_ext['bzip2'] = '.bz2' |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 384 | |
| 385 | # flags for compression program, each element of list will be an argument |
| 386 | if compress is not None and compress not in compress_ext.keys(): |
Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 387 | raise ValueError("bad value for 'compress', or compression format not " |
| 388 | "supported : {0}".format(compress)) |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 389 | |
Tarek Ziadé | 5e2be87 | 2010-04-20 21:40:47 +0000 | [diff] [blame] | 390 | archive_name = base_name + '.tar' + compress_ext.get(compress, '') |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 391 | archive_dir = os.path.dirname(archive_name) |
Tarek Ziadé | 5e2be87 | 2010-04-20 21:40:47 +0000 | [diff] [blame] | 392 | |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 393 | if not os.path.exists(archive_dir): |
Éric Araujo | ac4e58e | 2011-01-29 20:32:11 +0000 | [diff] [blame] | 394 | if logger is not None: |
| 395 | logger.info("creating %s" % archive_dir) |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 396 | if not dry_run: |
| 397 | os.makedirs(archive_dir) |
| 398 | |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 399 | # creating the tarball |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 400 | if logger is not None: |
| 401 | logger.info('Creating tar archive') |
| 402 | |
| 403 | uid = _get_uid(owner) |
| 404 | gid = _get_gid(group) |
| 405 | |
| 406 | def _set_uid_gid(tarinfo): |
| 407 | if gid is not None: |
| 408 | tarinfo.gid = gid |
| 409 | tarinfo.gname = group |
| 410 | if uid is not None: |
| 411 | tarinfo.uid = uid |
| 412 | tarinfo.uname = owner |
| 413 | return tarinfo |
| 414 | |
| 415 | if not dry_run: |
| 416 | tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress]) |
| 417 | try: |
| 418 | tar.add(base_dir, filter=_set_uid_gid) |
| 419 | finally: |
| 420 | tar.close() |
| 421 | |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 422 | return archive_name |
| 423 | |
Tarek Ziadé | e212416 | 2010-04-21 13:35:21 +0000 | [diff] [blame] | 424 | def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False): |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 425 | # XXX see if we want to keep an external call here |
| 426 | if verbose: |
| 427 | zipoptions = "-r" |
| 428 | else: |
| 429 | zipoptions = "-rq" |
| 430 | from distutils.errors import DistutilsExecError |
| 431 | from distutils.spawn import spawn |
| 432 | try: |
| 433 | spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run) |
| 434 | except DistutilsExecError: |
| 435 | # XXX really should distinguish between "couldn't find |
| 436 | # external 'zip' command" and "zip failed". |
| 437 | raise ExecError("unable to create zip file '%s': " |
| 438 | "could neither import the 'zipfile' module nor " |
| 439 | "find a standalone zip utility") % zip_filename |
| 440 | |
| 441 | def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): |
| 442 | """Create a zip file from all the files under 'base_dir'. |
| 443 | |
Éric Araujo | 4433a5f | 2010-12-15 20:26:30 +0000 | [diff] [blame] | 444 | The output zip file will be named 'base_name' + ".zip". Uses either the |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 445 | "zipfile" Python module (if available) or the InfoZIP "zip" utility |
| 446 | (if installed and found on the default search path). If neither tool is |
| 447 | available, raises ExecError. Returns the name of the output zip |
| 448 | file. |
| 449 | """ |
| 450 | zip_filename = base_name + ".zip" |
| 451 | archive_dir = os.path.dirname(base_name) |
| 452 | |
| 453 | if not os.path.exists(archive_dir): |
| 454 | if logger is not None: |
| 455 | logger.info("creating %s", archive_dir) |
| 456 | if not dry_run: |
| 457 | os.makedirs(archive_dir) |
| 458 | |
| 459 | # If zipfile module is not available, try spawning an external 'zip' |
| 460 | # command. |
| 461 | try: |
| 462 | import zipfile |
| 463 | except ImportError: |
| 464 | zipfile = None |
| 465 | |
| 466 | if zipfile is None: |
Tarek Ziadé | e212416 | 2010-04-21 13:35:21 +0000 | [diff] [blame] | 467 | _call_external_zip(base_dir, zip_filename, verbose, dry_run) |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 468 | else: |
| 469 | if logger is not None: |
| 470 | logger.info("creating '%s' and adding '%s' to it", |
| 471 | zip_filename, base_dir) |
| 472 | |
| 473 | if not dry_run: |
| 474 | zip = zipfile.ZipFile(zip_filename, "w", |
| 475 | compression=zipfile.ZIP_DEFLATED) |
| 476 | |
| 477 | for dirpath, dirnames, filenames in os.walk(base_dir): |
| 478 | for name in filenames: |
| 479 | path = os.path.normpath(os.path.join(dirpath, name)) |
| 480 | if os.path.isfile(path): |
| 481 | zip.write(path, path) |
| 482 | if logger is not None: |
| 483 | logger.info("adding '%s'", path) |
| 484 | zip.close() |
| 485 | |
| 486 | return zip_filename |
| 487 | |
| 488 | _ARCHIVE_FORMATS = { |
| 489 | 'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), |
| 490 | 'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"), |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 491 | 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"), |
| 492 | 'zip': (_make_zipfile, [],"ZIP file") |
| 493 | } |
| 494 | |
Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 495 | if _BZ2_SUPPORTED: |
| 496 | _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')], |
| 497 | "bzip2'ed tar-file") |
| 498 | |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 499 | def get_archive_formats(): |
| 500 | """Returns a list of supported formats for archiving and unarchiving. |
| 501 | |
| 502 | Each element of the returned sequence is a tuple (name, description) |
| 503 | """ |
| 504 | formats = [(name, registry[2]) for name, registry in |
| 505 | _ARCHIVE_FORMATS.items()] |
| 506 | formats.sort() |
| 507 | return formats |
| 508 | |
| 509 | def register_archive_format(name, function, extra_args=None, description=''): |
| 510 | """Registers an archive format. |
| 511 | |
| 512 | name is the name of the format. function is the callable that will be |
| 513 | used to create archives. If provided, extra_args is a sequence of |
| 514 | (name, value) tuples that will be passed as arguments to the callable. |
| 515 | description can be provided to describe the format, and will be returned |
| 516 | by the get_archive_formats() function. |
| 517 | """ |
| 518 | if extra_args is None: |
| 519 | extra_args = [] |
| 520 | if not isinstance(function, collections.Callable): |
| 521 | raise TypeError('The %s object is not callable' % function) |
| 522 | if not isinstance(extra_args, (tuple, list)): |
| 523 | raise TypeError('extra_args needs to be a sequence') |
| 524 | for element in extra_args: |
| 525 | if not isinstance(element, (tuple, list)) or len(element) !=2 : |
| 526 | raise TypeError('extra_args elements are : (arg_name, value)') |
| 527 | |
| 528 | _ARCHIVE_FORMATS[name] = (function, extra_args, description) |
| 529 | |
| 530 | def unregister_archive_format(name): |
| 531 | del _ARCHIVE_FORMATS[name] |
| 532 | |
| 533 | def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, |
| 534 | dry_run=0, owner=None, group=None, logger=None): |
| 535 | """Create an archive file (eg. zip or tar). |
| 536 | |
| 537 | 'base_name' is the name of the file to create, minus any format-specific |
Tarek Ziadé | 5e2be87 | 2010-04-20 21:40:47 +0000 | [diff] [blame] | 538 | extension; 'format' is the archive format: one of "zip", "tar", "bztar" |
| 539 | or "gztar". |
Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 540 | |
| 541 | 'root_dir' is a directory that will be the root directory of the |
| 542 | archive; ie. we typically chdir into 'root_dir' before creating the |
| 543 | archive. 'base_dir' is the directory where we start archiving from; |
| 544 | ie. 'base_dir' will be the common prefix of all files and |
| 545 | directories in the archive. 'root_dir' and 'base_dir' both default |
| 546 | to the current directory. Returns the name of the archive file. |
| 547 | |
| 548 | 'owner' and 'group' are used when creating a tar archive. By default, |
| 549 | uses the current owner and group. |
| 550 | """ |
| 551 | save_cwd = os.getcwd() |
| 552 | if root_dir is not None: |
| 553 | if logger is not None: |
| 554 | logger.debug("changing into '%s'", root_dir) |
| 555 | base_name = os.path.abspath(base_name) |
| 556 | if not dry_run: |
| 557 | os.chdir(root_dir) |
| 558 | |
| 559 | if base_dir is None: |
| 560 | base_dir = os.curdir |
| 561 | |
| 562 | kwargs = {'dry_run': dry_run, 'logger': logger} |
| 563 | |
| 564 | try: |
| 565 | format_info = _ARCHIVE_FORMATS[format] |
| 566 | except KeyError: |
| 567 | raise ValueError("unknown archive format '%s'" % format) |
| 568 | |
| 569 | func = format_info[0] |
| 570 | for arg, val in format_info[1]: |
| 571 | kwargs[arg] = val |
| 572 | |
| 573 | if format != 'zip': |
| 574 | kwargs['owner'] = owner |
| 575 | kwargs['group'] = group |
| 576 | |
| 577 | try: |
| 578 | filename = func(base_name, base_dir, **kwargs) |
| 579 | finally: |
| 580 | if root_dir is not None: |
| 581 | if logger is not None: |
| 582 | logger.debug("changing back to '%s'", save_cwd) |
| 583 | os.chdir(save_cwd) |
| 584 | |
| 585 | return filename |
Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 586 | |
| 587 | |
| 588 | def get_unpack_formats(): |
| 589 | """Returns a list of supported formats for unpacking. |
| 590 | |
| 591 | Each element of the returned sequence is a tuple |
| 592 | (name, extensions, description) |
| 593 | """ |
| 594 | formats = [(name, info[0], info[3]) for name, info in |
| 595 | _UNPACK_FORMATS.items()] |
| 596 | formats.sort() |
| 597 | return formats |
| 598 | |
| 599 | def _check_unpack_options(extensions, function, extra_args): |
| 600 | """Checks what gets registered as an unpacker.""" |
| 601 | # first make sure no other unpacker is registered for this extension |
| 602 | existing_extensions = {} |
| 603 | for name, info in _UNPACK_FORMATS.items(): |
| 604 | for ext in info[0]: |
| 605 | existing_extensions[ext] = name |
| 606 | |
| 607 | for extension in extensions: |
| 608 | if extension in existing_extensions: |
| 609 | msg = '%s is already registered for "%s"' |
| 610 | raise RegistryError(msg % (extension, |
| 611 | existing_extensions[extension])) |
| 612 | |
| 613 | if not isinstance(function, collections.Callable): |
| 614 | raise TypeError('The registered function must be a callable') |
| 615 | |
| 616 | |
| 617 | def register_unpack_format(name, extensions, function, extra_args=None, |
| 618 | description=''): |
| 619 | """Registers an unpack format. |
| 620 | |
| 621 | `name` is the name of the format. `extensions` is a list of extensions |
| 622 | corresponding to the format. |
| 623 | |
| 624 | `function` is the callable that will be |
| 625 | used to unpack archives. The callable will receive archives to unpack. |
| 626 | If it's unable to handle an archive, it needs to raise a ReadError |
| 627 | exception. |
| 628 | |
| 629 | If provided, `extra_args` is a sequence of |
| 630 | (name, value) tuples that will be passed as arguments to the callable. |
| 631 | description can be provided to describe the format, and will be returned |
| 632 | by the get_unpack_formats() function. |
| 633 | """ |
| 634 | if extra_args is None: |
| 635 | extra_args = [] |
| 636 | _check_unpack_options(extensions, function, extra_args) |
| 637 | _UNPACK_FORMATS[name] = extensions, function, extra_args, description |
| 638 | |
| 639 | def unregister_unpack_format(name): |
| 640 | """Removes the pack format from the registery.""" |
| 641 | del _UNPACK_FORMATS[name] |
| 642 | |
| 643 | def _ensure_directory(path): |
| 644 | """Ensure that the parent directory of `path` exists""" |
| 645 | dirname = os.path.dirname(path) |
| 646 | if not os.path.isdir(dirname): |
| 647 | os.makedirs(dirname) |
| 648 | |
| 649 | def _unpack_zipfile(filename, extract_dir): |
| 650 | """Unpack zip `filename` to `extract_dir` |
| 651 | """ |
| 652 | try: |
| 653 | import zipfile |
| 654 | except ImportError: |
| 655 | raise ReadError('zlib not supported, cannot unpack this archive.') |
| 656 | |
| 657 | if not zipfile.is_zipfile(filename): |
| 658 | raise ReadError("%s is not a zip file" % filename) |
| 659 | |
| 660 | zip = zipfile.ZipFile(filename) |
| 661 | try: |
| 662 | for info in zip.infolist(): |
| 663 | name = info.filename |
| 664 | |
| 665 | # don't extract absolute paths or ones with .. in them |
| 666 | if name.startswith('/') or '..' in name: |
| 667 | continue |
| 668 | |
| 669 | target = os.path.join(extract_dir, *name.split('/')) |
| 670 | if not target: |
| 671 | continue |
| 672 | |
| 673 | _ensure_directory(target) |
| 674 | if not name.endswith('/'): |
| 675 | # file |
| 676 | data = zip.read(info.filename) |
| 677 | f = open(target,'wb') |
| 678 | try: |
| 679 | f.write(data) |
| 680 | finally: |
| 681 | f.close() |
| 682 | del data |
| 683 | finally: |
| 684 | zip.close() |
| 685 | |
| 686 | def _unpack_tarfile(filename, extract_dir): |
| 687 | """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` |
| 688 | """ |
| 689 | try: |
| 690 | tarobj = tarfile.open(filename) |
| 691 | except tarfile.TarError: |
| 692 | raise ReadError( |
| 693 | "%s is not a compressed or uncompressed tar file" % filename) |
| 694 | try: |
| 695 | tarobj.extractall(extract_dir) |
| 696 | finally: |
| 697 | tarobj.close() |
| 698 | |
| 699 | _UNPACK_FORMATS = { |
| 700 | 'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"), |
Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 701 | 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"), |
| 702 | 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file") |
| 703 | } |
| 704 | |
Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 705 | if _BZ2_SUPPORTED: |
| 706 | _UNPACK_FORMATS['bztar'] = (['.bz2'], _unpack_tarfile, [], |
| 707 | "bzip2'ed tar-file") |
| 708 | |
Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 709 | def _find_unpack_format(filename): |
| 710 | for name, info in _UNPACK_FORMATS.items(): |
| 711 | for extension in info[0]: |
| 712 | if filename.endswith(extension): |
| 713 | return name |
| 714 | return None |
| 715 | |
| 716 | def unpack_archive(filename, extract_dir=None, format=None): |
| 717 | """Unpack an archive. |
| 718 | |
| 719 | `filename` is the name of the archive. |
| 720 | |
| 721 | `extract_dir` is the name of the target directory, where the archive |
| 722 | is unpacked. If not provided, the current working directory is used. |
| 723 | |
| 724 | `format` is the archive format: one of "zip", "tar", or "gztar". Or any |
| 725 | other registered format. If not provided, unpack_archive will use the |
| 726 | filename extension and see if an unpacker was registered for that |
| 727 | extension. |
| 728 | |
| 729 | In case none is found, a ValueError is raised. |
| 730 | """ |
| 731 | if extract_dir is None: |
| 732 | extract_dir = os.getcwd() |
| 733 | |
| 734 | if format is not None: |
| 735 | try: |
| 736 | format_info = _UNPACK_FORMATS[format] |
| 737 | except KeyError: |
| 738 | raise ValueError("Unknown unpack format '{0}'".format(format)) |
| 739 | |
Nick Coghlan | abf202d | 2011-03-16 13:52:20 -0400 | [diff] [blame] | 740 | func = format_info[1] |
| 741 | func(filename, extract_dir, **dict(format_info[2])) |
Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 742 | else: |
| 743 | # we need to look at the registered unpackers supported extensions |
| 744 | format = _find_unpack_format(filename) |
| 745 | if format is None: |
| 746 | raise ReadError("Unknown archive format '{0}'".format(filename)) |
| 747 | |
| 748 | func = _UNPACK_FORMATS[format][1] |
| 749 | kwargs = dict(_UNPACK_FORMATS[format][2]) |
| 750 | func(filename, extract_dir, **kwargs) |