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