Tarek Ziadé | 2900c44 | 2010-02-23 05:36:41 +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 | e78fbcc | 2008-07-05 10:13:36 +0000 | [diff] [blame] | 11 | import fnmatch |
Tarek Ziadé | 48cc8dc | 2010-02-23 05:16:41 +0000 | [diff] [blame] | 12 | from warnings import warn |
Florent Xicluna | 1f3b4e1 | 2010-03-07 12:14:25 +0000 | [diff] [blame] | 13 | import collections |
Tarek Ziadé | 48cc8dc | 2010-02-23 05:16:41 +0000 | [diff] [blame] | 14 | |
| 15 | try: |
| 16 | from pwd import getpwnam |
| 17 | except ImportError: |
| 18 | getpwnam = None |
| 19 | |
| 20 | try: |
| 21 | from grp import getgrnam |
| 22 | except ImportError: |
| 23 | getgrnam = None |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 24 | |
Tarek Ziadé | 2900c44 | 2010-02-23 05:36:41 +0000 | [diff] [blame] | 25 | __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", |
| 26 | "copytree", "move", "rmtree", "Error", "SpecialFileError", |
| 27 | "ExecError", "make_archive", "get_archive_formats", |
| 28 | "register_archive_format", "unregister_archive_format"] |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 29 | |
Neal Norwitz | 4ce69a5 | 2005-09-01 00:45:28 +0000 | [diff] [blame] | 30 | class Error(EnvironmentError): |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 31 | pass |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 32 | |
Antoine Pitrou | 1fc0231 | 2009-05-01 20:55:35 +0000 | [diff] [blame] | 33 | class SpecialFileError(EnvironmentError): |
| 34 | """Raised when trying to do a kind of operation (e.g. copying) which is |
| 35 | not supported on a special file (e.g. a named pipe)""" |
| 36 | |
Tarek Ziadé | 48cc8dc | 2010-02-23 05:16:41 +0000 | [diff] [blame] | 37 | class ExecError(EnvironmentError): |
| 38 | """Raised when a command could not be executed""" |
| 39 | |
Antoine Pitrou | 9fcd4b3 | 2008-08-11 17:21:36 +0000 | [diff] [blame] | 40 | try: |
| 41 | WindowsError |
| 42 | except NameError: |
| 43 | WindowsError = None |
| 44 | |
Greg Stein | 42bb8b3 | 2000-07-12 09:55:30 +0000 | [diff] [blame] | 45 | def copyfileobj(fsrc, fdst, length=16*1024): |
| 46 | """copy data from file-like object fsrc to file-like object fdst""" |
| 47 | while 1: |
| 48 | buf = fsrc.read(length) |
| 49 | if not buf: |
| 50 | break |
| 51 | fdst.write(buf) |
| 52 | |
Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 53 | def _samefile(src, dst): |
| 54 | # Macintosh, Unix. |
| 55 | if hasattr(os.path,'samefile'): |
Johannes Gijsbers | f9a098e | 2004-08-14 14:51:01 +0000 | [diff] [blame] | 56 | try: |
| 57 | return os.path.samefile(src, dst) |
| 58 | except OSError: |
| 59 | return False |
Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 60 | |
| 61 | # All other platforms: check for same pathname. |
| 62 | return (os.path.normcase(os.path.abspath(src)) == |
| 63 | os.path.normcase(os.path.abspath(dst))) |
Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 64 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 65 | def copyfile(src, dst): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 66 | """Copy data from src to dst""" |
Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 67 | if _samefile(src, dst): |
| 68 | raise Error, "`%s` and `%s` are the same file" % (src, dst) |
| 69 | |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 70 | fsrc = None |
| 71 | fdst = None |
Antoine Pitrou | 1fc0231 | 2009-05-01 20:55:35 +0000 | [diff] [blame] | 72 | for fn in [src, dst]: |
| 73 | try: |
| 74 | st = os.stat(fn) |
| 75 | except OSError: |
| 76 | # File most likely does not exist |
| 77 | pass |
Benjamin Peterson | a663a37 | 2009-06-05 19:09:28 +0000 | [diff] [blame] | 78 | else: |
| 79 | # XXX What about other special files? (sockets, devices...) |
| 80 | if stat.S_ISFIFO(st.st_mode): |
| 81 | raise SpecialFileError("`%s` is a named pipe" % fn) |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 82 | try: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 83 | fsrc = open(src, 'rb') |
| 84 | fdst = open(dst, 'wb') |
Greg Stein | 42bb8b3 | 2000-07-12 09:55:30 +0000 | [diff] [blame] | 85 | copyfileobj(fsrc, fdst) |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 86 | finally: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 87 | if fdst: |
| 88 | fdst.close() |
| 89 | if fsrc: |
| 90 | fsrc.close() |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 91 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 92 | def copymode(src, dst): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 93 | """Copy mode bits from src to dst""" |
Tim Peters | 0c94724 | 2001-01-21 20:00:00 +0000 | [diff] [blame] | 94 | if hasattr(os, 'chmod'): |
| 95 | st = os.stat(src) |
Walter Dörwald | 294bbf3 | 2002-06-06 09:48:13 +0000 | [diff] [blame] | 96 | mode = stat.S_IMODE(st.st_mode) |
Tim Peters | 0c94724 | 2001-01-21 20:00:00 +0000 | [diff] [blame] | 97 | os.chmod(dst, mode) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 98 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 99 | def copystat(src, dst): |
Martin v. Löwis | 382abef | 2007-02-19 10:55:19 +0000 | [diff] [blame] | 100 | """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] | 101 | st = os.stat(src) |
Walter Dörwald | 294bbf3 | 2002-06-06 09:48:13 +0000 | [diff] [blame] | 102 | mode = stat.S_IMODE(st.st_mode) |
Tim Peters | 0c94724 | 2001-01-21 20:00:00 +0000 | [diff] [blame] | 103 | if hasattr(os, 'utime'): |
Walter Dörwald | 294bbf3 | 2002-06-06 09:48:13 +0000 | [diff] [blame] | 104 | os.utime(dst, (st.st_atime, st.st_mtime)) |
Tim Peters | 0c94724 | 2001-01-21 20:00:00 +0000 | [diff] [blame] | 105 | if hasattr(os, 'chmod'): |
| 106 | os.chmod(dst, mode) |
Martin v. Löwis | 382abef | 2007-02-19 10:55:19 +0000 | [diff] [blame] | 107 | if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): |
| 108 | os.chflags(dst, st.st_flags) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 109 | |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 110 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 111 | def copy(src, dst): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 112 | """Copy data and mode bits ("cp src dst"). |
Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 113 | |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 114 | The destination may be a directory. |
| 115 | |
| 116 | """ |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 117 | if os.path.isdir(dst): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 118 | dst = os.path.join(dst, os.path.basename(src)) |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 119 | copyfile(src, dst) |
| 120 | copymode(src, dst) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 121 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 122 | def copy2(src, dst): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 123 | """Copy data and all stat info ("cp -p src dst"). |
| 124 | |
| 125 | The destination may be a directory. |
| 126 | |
| 127 | """ |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 128 | if os.path.isdir(dst): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 129 | dst = os.path.join(dst, os.path.basename(src)) |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 130 | copyfile(src, dst) |
| 131 | copystat(src, dst) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 132 | |
Georg Brandl | e78fbcc | 2008-07-05 10:13:36 +0000 | [diff] [blame] | 133 | def ignore_patterns(*patterns): |
| 134 | """Function that can be used as copytree() ignore parameter. |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 135 | |
Georg Brandl | e78fbcc | 2008-07-05 10:13:36 +0000 | [diff] [blame] | 136 | Patterns is a sequence of glob-style patterns |
| 137 | that are used to exclude files""" |
| 138 | def _ignore_patterns(path, names): |
| 139 | ignored_names = [] |
| 140 | for pattern in patterns: |
| 141 | ignored_names.extend(fnmatch.filter(names, pattern)) |
| 142 | return set(ignored_names) |
| 143 | return _ignore_patterns |
| 144 | |
| 145 | def copytree(src, dst, symlinks=False, ignore=None): |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 146 | """Recursively copy a directory tree using copy2(). |
| 147 | |
| 148 | The destination directory must not already exist. |
Neal Norwitz | a4c93b6 | 2003-02-23 21:36:32 +0000 | [diff] [blame] | 149 | 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] | 150 | |
| 151 | If the optional symlinks flag is true, symbolic links in the |
| 152 | source tree result in symbolic links in the destination tree; if |
| 153 | it is false, the contents of the files pointed to by symbolic |
| 154 | links are copied. |
| 155 | |
Georg Brandl | e78fbcc | 2008-07-05 10:13:36 +0000 | [diff] [blame] | 156 | The optional ignore argument is a callable. If given, it |
| 157 | is called with the `src` parameter, which is the directory |
| 158 | being visited by copytree(), and `names` which is the list of |
| 159 | `src` contents, as returned by os.listdir(): |
| 160 | |
| 161 | callable(src, names) -> ignored_names |
| 162 | |
| 163 | Since copytree() is called recursively, the callable will be |
| 164 | called once for each directory that is copied. It returns a |
| 165 | list of names relative to the `src` directory that should |
| 166 | not be copied. |
| 167 | |
Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 168 | XXX Consider this example code rather than the ultimate tool. |
| 169 | |
| 170 | """ |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 171 | names = os.listdir(src) |
Georg Brandl | e78fbcc | 2008-07-05 10:13:36 +0000 | [diff] [blame] | 172 | if ignore is not None: |
| 173 | ignored_names = ignore(src, names) |
| 174 | else: |
| 175 | ignored_names = set() |
| 176 | |
Johannes Gijsbers | e4172ea | 2005-01-08 12:31:29 +0000 | [diff] [blame] | 177 | os.makedirs(dst) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 178 | errors = [] |
Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 179 | for name in names: |
Georg Brandl | e78fbcc | 2008-07-05 10:13:36 +0000 | [diff] [blame] | 180 | if name in ignored_names: |
| 181 | continue |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 182 | srcname = os.path.join(src, name) |
| 183 | dstname = os.path.join(dst, name) |
| 184 | try: |
| 185 | if symlinks and os.path.islink(srcname): |
| 186 | linkto = os.readlink(srcname) |
| 187 | os.symlink(linkto, dstname) |
| 188 | elif os.path.isdir(srcname): |
Georg Brandl | e78fbcc | 2008-07-05 10:13:36 +0000 | [diff] [blame] | 189 | copytree(srcname, dstname, symlinks, ignore) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 190 | else: |
Antoine Pitrou | 1fc0231 | 2009-05-01 20:55:35 +0000 | [diff] [blame] | 191 | # Will raise a SpecialFileError for unsupported file types |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 192 | copy2(srcname, dstname) |
Georg Brandl | a1be88e | 2005-08-31 22:48:45 +0000 | [diff] [blame] | 193 | # catch the Error from the recursive copytree so that we can |
| 194 | # continue with other files |
| 195 | except Error, err: |
| 196 | errors.extend(err.args[0]) |
Antoine Pitrou | 1fc0231 | 2009-05-01 20:55:35 +0000 | [diff] [blame] | 197 | except EnvironmentError, why: |
| 198 | errors.append((srcname, dstname, str(why))) |
Martin v. Löwis | 4e67838 | 2006-07-30 13:00:31 +0000 | [diff] [blame] | 199 | try: |
| 200 | copystat(src, dst) |
Martin v. Löwis | 4e67838 | 2006-07-30 13:00:31 +0000 | [diff] [blame] | 201 | except OSError, why: |
Antoine Pitrou | 9fcd4b3 | 2008-08-11 17:21:36 +0000 | [diff] [blame] | 202 | if WindowsError is not None and isinstance(why, WindowsError): |
| 203 | # Copying file access times may fail on Windows |
| 204 | pass |
| 205 | else: |
| 206 | errors.extend((src, dst, str(why))) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 207 | if errors: |
| 208 | raise Error, errors |
Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 209 | |
Barry Warsaw | 234d9a9 | 2003-01-24 17:36:15 +0000 | [diff] [blame] | 210 | def rmtree(path, ignore_errors=False, onerror=None): |
Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 211 | """Recursively delete a directory tree. |
| 212 | |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 213 | If ignore_errors is set, errors are ignored; otherwise, if onerror |
| 214 | is set, it is called to handle the error with arguments (func, |
| 215 | path, exc_info) where func is os.listdir, os.remove, or os.rmdir; |
| 216 | path is the argument to that function that caused it to fail; and |
| 217 | exc_info is a tuple returned by sys.exc_info(). If ignore_errors |
| 218 | is false and onerror is None, an exception is raised. |
| 219 | |
Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 220 | """ |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 221 | if ignore_errors: |
| 222 | def onerror(*args): |
Barry Warsaw | 234d9a9 | 2003-01-24 17:36:15 +0000 | [diff] [blame] | 223 | pass |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 224 | elif onerror is None: |
| 225 | def onerror(*args): |
| 226 | raise |
Georg Brandl | 5235398 | 2008-01-20 14:17:42 +0000 | [diff] [blame] | 227 | try: |
| 228 | if os.path.islink(path): |
| 229 | # symlinks to directories are forbidden, see bug #1669 |
| 230 | raise OSError("Cannot call rmtree on a symbolic link") |
| 231 | except OSError: |
| 232 | onerror(os.path.islink, path, sys.exc_info()) |
| 233 | # can't continue even if onerror hook returns |
| 234 | return |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 235 | names = [] |
| 236 | try: |
| 237 | names = os.listdir(path) |
| 238 | except os.error, err: |
| 239 | onerror(os.listdir, path, sys.exc_info()) |
| 240 | for name in names: |
| 241 | fullname = os.path.join(path, name) |
| 242 | try: |
| 243 | mode = os.lstat(fullname).st_mode |
| 244 | except os.error: |
| 245 | mode = 0 |
| 246 | if stat.S_ISDIR(mode): |
| 247 | rmtree(fullname, ignore_errors, onerror) |
Barry Warsaw | 234d9a9 | 2003-01-24 17:36:15 +0000 | [diff] [blame] | 248 | else: |
Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 249 | try: |
| 250 | os.remove(fullname) |
| 251 | except os.error, err: |
| 252 | onerror(os.remove, fullname, sys.exc_info()) |
| 253 | try: |
| 254 | os.rmdir(path) |
| 255 | except os.error: |
| 256 | onerror(os.rmdir, path, sys.exc_info()) |
Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 257 | |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 258 | |
Sean Reifscheider | 493894c | 2008-03-18 17:24:12 +0000 | [diff] [blame] | 259 | def _basename(path): |
| 260 | # A basename() variant which first strips the trailing slash, if present. |
| 261 | # Thus we always get the last component of the path, even for directories. |
| 262 | return os.path.basename(path.rstrip(os.path.sep)) |
| 263 | |
| 264 | def move(src, dst): |
| 265 | """Recursively move a file or directory to another location. This is |
| 266 | similar to the Unix "mv" command. |
| 267 | |
| 268 | If the destination is a directory or a symlink to a directory, the source |
| 269 | is moved inside the directory. The destination path must not already |
| 270 | exist. |
| 271 | |
| 272 | If the destination already exists but is not a directory, it may be |
| 273 | overwritten depending on os.rename() semantics. |
| 274 | |
| 275 | If the destination is on our current filesystem, then rename() is used. |
| 276 | Otherwise, src is copied to the destination and then removed. |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 277 | A lot more could be done here... A look at a mv.c shows a lot of |
| 278 | the issues this implementation glosses over. |
| 279 | |
| 280 | """ |
Sean Reifscheider | 493894c | 2008-03-18 17:24:12 +0000 | [diff] [blame] | 281 | real_dst = dst |
| 282 | if os.path.isdir(dst): |
| 283 | real_dst = os.path.join(dst, _basename(src)) |
| 284 | if os.path.exists(real_dst): |
| 285 | raise Error, "Destination path '%s' already exists" % real_dst |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 286 | try: |
Sean Reifscheider | 493894c | 2008-03-18 17:24:12 +0000 | [diff] [blame] | 287 | os.rename(src, real_dst) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 288 | except OSError: |
| 289 | if os.path.isdir(src): |
Benjamin Peterson | 096c3ad | 2009-02-07 19:08:22 +0000 | [diff] [blame] | 290 | if _destinsrc(src, dst): |
Brett Cannon | 1c3fa18 | 2004-06-19 21:11:35 +0000 | [diff] [blame] | 291 | raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst) |
Sean Reifscheider | 493894c | 2008-03-18 17:24:12 +0000 | [diff] [blame] | 292 | copytree(src, real_dst, symlinks=True) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 293 | rmtree(src) |
| 294 | else: |
Sean Reifscheider | 493894c | 2008-03-18 17:24:12 +0000 | [diff] [blame] | 295 | copy2(src, real_dst) |
Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 296 | os.unlink(src) |
Brett Cannon | 1c3fa18 | 2004-06-19 21:11:35 +0000 | [diff] [blame] | 297 | |
Benjamin Peterson | 096c3ad | 2009-02-07 19:08:22 +0000 | [diff] [blame] | 298 | def _destinsrc(src, dst): |
Antoine Pitrou | 707c593 | 2009-01-29 20:19:34 +0000 | [diff] [blame] | 299 | src = abspath(src) |
| 300 | dst = abspath(dst) |
| 301 | if not src.endswith(os.path.sep): |
| 302 | src += os.path.sep |
| 303 | if not dst.endswith(os.path.sep): |
| 304 | dst += os.path.sep |
| 305 | return dst.startswith(src) |
Tarek Ziadé | 48cc8dc | 2010-02-23 05:16:41 +0000 | [diff] [blame] | 306 | |
| 307 | def _get_gid(name): |
| 308 | """Returns a gid, given a group name.""" |
| 309 | if getgrnam is None or name is None: |
| 310 | return None |
| 311 | try: |
| 312 | result = getgrnam(name) |
| 313 | except KeyError: |
| 314 | result = None |
| 315 | if result is not None: |
| 316 | return result[2] |
| 317 | return None |
| 318 | |
| 319 | def _get_uid(name): |
| 320 | """Returns an uid, given a user name.""" |
| 321 | if getpwnam is None or name is None: |
| 322 | return None |
| 323 | try: |
| 324 | result = getpwnam(name) |
| 325 | except KeyError: |
| 326 | result = None |
| 327 | if result is not None: |
| 328 | return result[2] |
| 329 | return None |
| 330 | |
| 331 | def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, |
| 332 | owner=None, group=None, logger=None): |
| 333 | """Create a (possibly compressed) tar file from all the files under |
| 334 | 'base_dir'. |
| 335 | |
| 336 | 'compress' must be "gzip" (the default), "compress", "bzip2", or None. |
| 337 | (compress will be deprecated in Python 3.2) |
| 338 | |
| 339 | 'owner' and 'group' can be used to define an owner and a group for the |
| 340 | archive that is being built. If not provided, the current owner and group |
| 341 | will be used. |
| 342 | |
| 343 | The output tar file will be named 'base_dir' + ".tar", possibly plus |
| 344 | the appropriate compression extension (".gz", ".bz2" or ".Z"). |
| 345 | |
| 346 | Returns the output filename. |
| 347 | """ |
| 348 | tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: '', 'compress': ''} |
| 349 | compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'compress': '.Z'} |
| 350 | |
| 351 | # flags for compression program, each element of list will be an argument |
| 352 | if compress is not None and compress not in compress_ext.keys(): |
| 353 | raise ValueError, \ |
| 354 | ("bad value for 'compress': must be None, 'gzip', 'bzip2' " |
| 355 | "or 'compress'") |
| 356 | |
| 357 | archive_name = base_name + '.tar' |
| 358 | if compress != 'compress': |
| 359 | archive_name += compress_ext.get(compress, '') |
| 360 | |
| 361 | archive_dir = os.path.dirname(archive_name) |
| 362 | if not os.path.exists(archive_dir): |
| 363 | logger.info("creating %s" % archive_dir) |
| 364 | if not dry_run: |
| 365 | os.makedirs(archive_dir) |
| 366 | |
| 367 | |
| 368 | # creating the tarball |
| 369 | import tarfile # late import so Python build itself doesn't break |
| 370 | |
| 371 | if logger is not None: |
| 372 | logger.info('Creating tar archive') |
| 373 | |
| 374 | uid = _get_uid(owner) |
| 375 | gid = _get_gid(group) |
| 376 | |
| 377 | def _set_uid_gid(tarinfo): |
| 378 | if gid is not None: |
| 379 | tarinfo.gid = gid |
| 380 | tarinfo.gname = group |
| 381 | if uid is not None: |
| 382 | tarinfo.uid = uid |
| 383 | tarinfo.uname = owner |
| 384 | return tarinfo |
| 385 | |
| 386 | if not dry_run: |
| 387 | tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress]) |
| 388 | try: |
| 389 | tar.add(base_dir, filter=_set_uid_gid) |
| 390 | finally: |
| 391 | tar.close() |
| 392 | |
| 393 | # compression using `compress` |
| 394 | # XXX this block will be removed in Python 3.2 |
| 395 | if compress == 'compress': |
| 396 | warn("'compress' will be deprecated.", PendingDeprecationWarning) |
| 397 | # the option varies depending on the platform |
| 398 | compressed_name = archive_name + compress_ext[compress] |
| 399 | if sys.platform == 'win32': |
| 400 | cmd = [compress, archive_name, compressed_name] |
| 401 | else: |
| 402 | cmd = [compress, '-f', archive_name] |
| 403 | from distutils.spawn import spawn |
| 404 | spawn(cmd, dry_run=dry_run) |
| 405 | return compressed_name |
| 406 | |
| 407 | return archive_name |
| 408 | |
| 409 | def _call_external_zip(directory, verbose=False): |
| 410 | # XXX see if we want to keep an external call here |
| 411 | if verbose: |
| 412 | zipoptions = "-r" |
| 413 | else: |
| 414 | zipoptions = "-rq" |
| 415 | from distutils.errors import DistutilsExecError |
| 416 | from distutils.spawn import spawn |
| 417 | try: |
| 418 | spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run) |
| 419 | except DistutilsExecError: |
| 420 | # XXX really should distinguish between "couldn't find |
| 421 | # external 'zip' command" and "zip failed". |
| 422 | raise ExecError, \ |
| 423 | ("unable to create zip file '%s': " |
| 424 | "could neither import the 'zipfile' module nor " |
| 425 | "find a standalone zip utility") % zip_filename |
| 426 | |
| 427 | def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): |
| 428 | """Create a zip file from all the files under 'base_dir'. |
| 429 | |
| 430 | The output zip file will be named 'base_dir' + ".zip". Uses either the |
| 431 | "zipfile" Python module (if available) or the InfoZIP "zip" utility |
| 432 | (if installed and found on the default search path). If neither tool is |
| 433 | available, raises ExecError. Returns the name of the output zip |
| 434 | file. |
| 435 | """ |
| 436 | zip_filename = base_name + ".zip" |
| 437 | archive_dir = os.path.dirname(base_name) |
| 438 | |
| 439 | if not os.path.exists(archive_dir): |
| 440 | if logger is not None: |
| 441 | logger.info("creating %s", archive_dir) |
| 442 | if not dry_run: |
| 443 | os.makedirs(archive_dir) |
| 444 | |
| 445 | # If zipfile module is not available, try spawning an external 'zip' |
| 446 | # command. |
| 447 | try: |
| 448 | import zipfile |
| 449 | except ImportError: |
| 450 | zipfile = None |
| 451 | |
| 452 | if zipfile is None: |
| 453 | _call_external_zip(base_dir, verbose) |
| 454 | else: |
| 455 | if logger is not None: |
| 456 | logger.info("creating '%s' and adding '%s' to it", |
| 457 | zip_filename, base_dir) |
| 458 | |
| 459 | if not dry_run: |
| 460 | zip = zipfile.ZipFile(zip_filename, "w", |
| 461 | compression=zipfile.ZIP_DEFLATED) |
| 462 | |
| 463 | for dirpath, dirnames, filenames in os.walk(base_dir): |
| 464 | for name in filenames: |
| 465 | path = os.path.normpath(os.path.join(dirpath, name)) |
| 466 | if os.path.isfile(path): |
| 467 | zip.write(path, path) |
| 468 | if logger is not None: |
| 469 | logger.info("adding '%s'", path) |
| 470 | zip.close() |
| 471 | |
| 472 | return zip_filename |
| 473 | |
| 474 | _ARCHIVE_FORMATS = { |
| 475 | 'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), |
| 476 | 'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"), |
| 477 | 'ztar': (_make_tarball, [('compress', 'compress')], |
| 478 | "compressed tar file"), |
| 479 | 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"), |
| 480 | 'zip': (_make_zipfile, [],"ZIP file") |
| 481 | } |
| 482 | |
| 483 | def get_archive_formats(): |
| 484 | """Returns a list of supported formats for archiving and unarchiving. |
| 485 | |
| 486 | Each element of the returned sequence is a tuple (name, description) |
| 487 | """ |
| 488 | formats = [(name, registry[2]) for name, registry in |
| 489 | _ARCHIVE_FORMATS.items()] |
| 490 | formats.sort() |
| 491 | return formats |
| 492 | |
| 493 | def register_archive_format(name, function, extra_args=None, description=''): |
| 494 | """Registers an archive format. |
| 495 | |
| 496 | name is the name of the format. function is the callable that will be |
| 497 | used to create archives. If provided, extra_args is a sequence of |
| 498 | (name, value) tuples that will be passed as arguments to the callable. |
| 499 | description can be provided to describe the format, and will be returned |
| 500 | by the get_archive_formats() function. |
| 501 | """ |
| 502 | if extra_args is None: |
| 503 | extra_args = [] |
Florent Xicluna | 1f3b4e1 | 2010-03-07 12:14:25 +0000 | [diff] [blame] | 504 | if not isinstance(function, collections.Callable): |
Tarek Ziadé | 48cc8dc | 2010-02-23 05:16:41 +0000 | [diff] [blame] | 505 | raise TypeError('The %s object is not callable' % function) |
| 506 | if not isinstance(extra_args, (tuple, list)): |
| 507 | raise TypeError('extra_args needs to be a sequence') |
| 508 | for element in extra_args: |
| 509 | if not isinstance(element, (tuple, list)) or len(element) !=2 : |
| 510 | raise TypeError('extra_args elements are : (arg_name, value)') |
| 511 | |
| 512 | _ARCHIVE_FORMATS[name] = (function, extra_args, description) |
| 513 | |
| 514 | def unregister_archive_format(name): |
| 515 | del _ARCHIVE_FORMATS[name] |
| 516 | |
| 517 | def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, |
| 518 | dry_run=0, owner=None, group=None, logger=None): |
| 519 | """Create an archive file (eg. zip or tar). |
| 520 | |
| 521 | 'base_name' is the name of the file to create, minus any format-specific |
| 522 | extension; 'format' is the archive format: one of "zip", "tar", "ztar", |
| 523 | or "gztar". |
| 524 | |
| 525 | 'root_dir' is a directory that will be the root directory of the |
| 526 | archive; ie. we typically chdir into 'root_dir' before creating the |
| 527 | archive. 'base_dir' is the directory where we start archiving from; |
| 528 | ie. 'base_dir' will be the common prefix of all files and |
| 529 | directories in the archive. 'root_dir' and 'base_dir' both default |
| 530 | to the current directory. Returns the name of the archive file. |
| 531 | |
| 532 | 'owner' and 'group' are used when creating a tar archive. By default, |
| 533 | uses the current owner and group. |
| 534 | """ |
| 535 | save_cwd = os.getcwd() |
| 536 | if root_dir is not None: |
| 537 | if logger is not None: |
| 538 | logger.debug("changing into '%s'", root_dir) |
| 539 | base_name = os.path.abspath(base_name) |
| 540 | if not dry_run: |
| 541 | os.chdir(root_dir) |
| 542 | |
| 543 | if base_dir is None: |
| 544 | base_dir = os.curdir |
| 545 | |
| 546 | kwargs = {'dry_run': dry_run, 'logger': logger} |
| 547 | |
| 548 | try: |
| 549 | format_info = _ARCHIVE_FORMATS[format] |
| 550 | except KeyError: |
| 551 | raise ValueError, "unknown archive format '%s'" % format |
| 552 | |
| 553 | func = format_info[0] |
| 554 | for arg, val in format_info[1]: |
| 555 | kwargs[arg] = val |
| 556 | |
| 557 | if format != 'zip': |
| 558 | kwargs['owner'] = owner |
| 559 | kwargs['group'] = group |
| 560 | |
| 561 | try: |
| 562 | filename = func(base_name, base_dir, **kwargs) |
| 563 | finally: |
| 564 | if root_dir is not None: |
| 565 | if logger is not None: |
| 566 | logger.debug("changing back to '%s'", save_cwd) |
| 567 | os.chdir(save_cwd) |
| 568 | |
| 569 | return filename |