| 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 |
| Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 10 | import fnmatch |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 11 | import collections |
| Antoine Pitrou | 910bd51 | 2010-03-22 20:11:09 +0000 | [diff] [blame] | 12 | import errno |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 13 | import tarfile |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 14 | |
| 15 | try: |
| Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 16 | import bz2 |
| Florent Xicluna | 54540ec | 2011-11-04 08:29:17 +0100 | [diff] [blame] | 17 | del bz2 |
| Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 18 | _BZ2_SUPPORTED = True |
| Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 19 | except ImportError: |
| Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 20 | _BZ2_SUPPORTED = False |
| 21 | |
| 22 | try: |
| Serhiy Storchaka | 1121377 | 2014-08-06 18:50:19 +0300 | [diff] [blame] | 23 | import lzma |
| 24 | del lzma |
| 25 | _LZMA_SUPPORTED = True |
| 26 | except ImportError: |
| 27 | _LZMA_SUPPORTED = False |
| 28 | |
| 29 | try: |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 30 | from pwd import getpwnam |
| Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 31 | except ImportError: |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 32 | getpwnam = None |
| 33 | |
| 34 | try: |
| 35 | from grp import getgrnam |
| Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 36 | except ImportError: |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 37 | getgrnam = None |
| Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 38 | |
| Tarek Ziadé | c339978 | 2010-02-23 05:39:18 +0000 | [diff] [blame] | 39 | __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", |
| 40 | "copytree", "move", "rmtree", "Error", "SpecialFileError", |
| 41 | "ExecError", "make_archive", "get_archive_formats", |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 42 | "register_archive_format", "unregister_archive_format", |
| 43 | "get_unpack_formats", "register_unpack_format", |
| Éric Araujo | c5efe65 | 2011-08-21 14:30:00 +0200 | [diff] [blame] | 44 | "unregister_unpack_format", "unpack_archive", |
| Brian Curtin | c57a345 | 2012-06-22 16:00:30 -0500 | [diff] [blame] | 45 | "ignore_patterns", "chown", "which"] |
| Éric Araujo | e4d5b8e | 2011-08-08 16:51:11 +0200 | [diff] [blame] | 46 | # disk_usage is added later, if available on the platform |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 47 | |
| Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 48 | class Error(OSError): |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 49 | pass |
| Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 50 | |
| Hynek Schlawack | 4865376 | 2012-10-07 12:49:58 +0200 | [diff] [blame] | 51 | class SameFileError(Error): |
| 52 | """Raised when source and destination are the same file.""" |
| 53 | |
| Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 54 | class SpecialFileError(OSError): |
| Antoine Pitrou | 7fff096 | 2009-05-01 21:09:44 +0000 | [diff] [blame] | 55 | """Raised when trying to do a kind of operation (e.g. copying) which is |
| 56 | not supported on a special file (e.g. a named pipe)""" |
| 57 | |
| Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 58 | class ExecError(OSError): |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 59 | """Raised when a command could not be executed""" |
| 60 | |
| Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 61 | class ReadError(OSError): |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 62 | """Raised when an archive cannot be read""" |
| 63 | |
| 64 | class RegistryError(Exception): |
| Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 65 | """Raised when a registry operation with the archiving |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 66 | and unpacking registeries fails""" |
| 67 | |
| 68 | |
| Greg Stein | 42bb8b3 | 2000-07-12 09:55:30 +0000 | [diff] [blame] | 69 | def copyfileobj(fsrc, fdst, length=16*1024): |
| 70 | """copy data from file-like object fsrc to file-like object fdst""" |
| 71 | while 1: |
| 72 | buf = fsrc.read(length) |
| 73 | if not buf: |
| 74 | break |
| 75 | fdst.write(buf) |
| 76 | |
| Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 77 | def _samefile(src, dst): |
| 78 | # Macintosh, Unix. |
| Tarek Ziadé | 1eab9cc | 2010-04-19 21:19:57 +0000 | [diff] [blame] | 79 | if hasattr(os.path, 'samefile'): |
| Johannes Gijsbers | f9a098e | 2004-08-14 14:51:01 +0000 | [diff] [blame] | 80 | try: |
| 81 | return os.path.samefile(src, dst) |
| 82 | except OSError: |
| 83 | return False |
| Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 84 | |
| 85 | # All other platforms: check for same pathname. |
| 86 | return (os.path.normcase(os.path.abspath(src)) == |
| 87 | os.path.normcase(os.path.abspath(dst))) |
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 88 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 89 | def copyfile(src, dst, *, follow_symlinks=True): |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 90 | """Copy data from src to dst. |
| 91 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 92 | If follow_symlinks is not set and src is a symbolic link, a new |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 93 | symlink will be created instead of copying the file it points to. |
| 94 | |
| 95 | """ |
| Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 96 | if _samefile(src, dst): |
| Hynek Schlawack | 4865376 | 2012-10-07 12:49:58 +0200 | [diff] [blame] | 97 | raise SameFileError("{!r} and {!r} are the same file".format(src, dst)) |
| Johannes Gijsbers | 46f1459 | 2004-08-14 13:30:02 +0000 | [diff] [blame] | 98 | |
| Antoine Pitrou | 7fff096 | 2009-05-01 21:09:44 +0000 | [diff] [blame] | 99 | for fn in [src, dst]: |
| 100 | try: |
| 101 | st = os.stat(fn) |
| 102 | except OSError: |
| 103 | # File most likely does not exist |
| 104 | pass |
| Benjamin Peterson | c0d98aa | 2009-06-05 19:13:27 +0000 | [diff] [blame] | 105 | else: |
| 106 | # XXX What about other special files? (sockets, devices...) |
| 107 | if stat.S_ISFIFO(st.st_mode): |
| 108 | raise SpecialFileError("`%s` is a named pipe" % fn) |
| Tarek Ziadé | b01142b | 2010-05-05 22:43:04 +0000 | [diff] [blame] | 109 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 110 | if not follow_symlinks and os.path.islink(src): |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 111 | os.symlink(os.readlink(src), dst) |
| 112 | else: |
| 113 | with open(src, 'rb') as fsrc: |
| 114 | with open(dst, 'wb') as fdst: |
| 115 | copyfileobj(fsrc, fdst) |
| Brian Curtin | 0d0a1de | 2012-06-18 18:41:07 -0500 | [diff] [blame] | 116 | return dst |
| Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 117 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 118 | def copymode(src, dst, *, follow_symlinks=True): |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 119 | """Copy mode bits from src to dst. |
| Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 120 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 121 | If follow_symlinks is not set, symlinks aren't followed if and only |
| 122 | if both `src` and `dst` are symlinks. If `lchmod` isn't available |
| 123 | (e.g. Linux) this method does nothing. |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 124 | |
| 125 | """ |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 126 | if not follow_symlinks and os.path.islink(src) and os.path.islink(dst): |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 127 | if hasattr(os, 'lchmod'): |
| 128 | stat_func, chmod_func = os.lstat, os.lchmod |
| 129 | else: |
| 130 | return |
| 131 | elif hasattr(os, 'chmod'): |
| 132 | stat_func, chmod_func = os.stat, os.chmod |
| 133 | else: |
| 134 | return |
| 135 | |
| 136 | st = stat_func(src) |
| 137 | chmod_func(dst, stat.S_IMODE(st.st_mode)) |
| 138 | |
| Larry Hastings | ad5ae04 | 2012-07-14 17:55:11 -0700 | [diff] [blame] | 139 | if hasattr(os, 'listxattr'): |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 140 | def _copyxattr(src, dst, *, follow_symlinks=True): |
| Larry Hastings | ad5ae04 | 2012-07-14 17:55:11 -0700 | [diff] [blame] | 141 | """Copy extended filesystem attributes from `src` to `dst`. |
| 142 | |
| 143 | Overwrite existing attributes. |
| 144 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 145 | If `follow_symlinks` is false, symlinks won't be followed. |
| Larry Hastings | ad5ae04 | 2012-07-14 17:55:11 -0700 | [diff] [blame] | 146 | |
| 147 | """ |
| 148 | |
| Hynek Schlawack | 0beab05 | 2013-02-05 08:22:44 +0100 | [diff] [blame] | 149 | try: |
| 150 | names = os.listxattr(src, follow_symlinks=follow_symlinks) |
| 151 | except OSError as e: |
| 152 | if e.errno not in (errno.ENOTSUP, errno.ENODATA): |
| 153 | raise |
| 154 | return |
| 155 | for name in names: |
| Larry Hastings | ad5ae04 | 2012-07-14 17:55:11 -0700 | [diff] [blame] | 156 | try: |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 157 | value = os.getxattr(src, name, follow_symlinks=follow_symlinks) |
| 158 | os.setxattr(dst, name, value, follow_symlinks=follow_symlinks) |
| Larry Hastings | ad5ae04 | 2012-07-14 17:55:11 -0700 | [diff] [blame] | 159 | except OSError as e: |
| 160 | if e.errno not in (errno.EPERM, errno.ENOTSUP, errno.ENODATA): |
| 161 | raise |
| 162 | else: |
| 163 | def _copyxattr(*args, **kwargs): |
| 164 | pass |
| 165 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 166 | def copystat(src, dst, *, follow_symlinks=True): |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 167 | """Copy all stat info (mode bits, atime, mtime, flags) from src to dst. |
| 168 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 169 | If the optional flag `follow_symlinks` is not set, symlinks aren't followed if and |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 170 | only if both `src` and `dst` are symlinks. |
| 171 | |
| 172 | """ |
| Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 173 | def _nop(*args, ns=None, follow_symlinks=None): |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 174 | pass |
| 175 | |
| Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 176 | # follow symlinks (aka don't not follow symlinks) |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 177 | follow = follow_symlinks or not (os.path.islink(src) and os.path.islink(dst)) |
| Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 178 | if follow: |
| 179 | # use the real function if it exists |
| 180 | def lookup(name): |
| 181 | return getattr(os, name, _nop) |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 182 | else: |
| Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 183 | # use the real function only if it exists |
| 184 | # *and* it supports follow_symlinks |
| 185 | def lookup(name): |
| 186 | fn = getattr(os, name, _nop) |
| 187 | if fn in os.supports_follow_symlinks: |
| 188 | return fn |
| 189 | return _nop |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 190 | |
| Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 191 | st = lookup("stat")(src, follow_symlinks=follow) |
| Walter Dörwald | 294bbf3 | 2002-06-06 09:48:13 +0000 | [diff] [blame] | 192 | mode = stat.S_IMODE(st.st_mode) |
| Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 193 | lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns), |
| 194 | follow_symlinks=follow) |
| 195 | try: |
| 196 | lookup("chmod")(dst, mode, follow_symlinks=follow) |
| 197 | except NotImplementedError: |
| 198 | # if we got a NotImplementedError, it's because |
| 199 | # * follow_symlinks=False, |
| 200 | # * lchown() is unavailable, and |
| 201 | # * either |
| Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 202 | # * fchownat() is unavailable or |
| Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 203 | # * fchownat() doesn't implement AT_SYMLINK_NOFOLLOW. |
| 204 | # (it returned ENOSUP.) |
| 205 | # therefore we're out of options--we simply cannot chown the |
| 206 | # symlink. give up, suppress the error. |
| 207 | # (which is what shutil always did in this circumstance.) |
| 208 | pass |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 209 | if hasattr(st, 'st_flags'): |
| Antoine Pitrou | 910bd51 | 2010-03-22 20:11:09 +0000 | [diff] [blame] | 210 | try: |
| Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 211 | lookup("chflags")(dst, st.st_flags, follow_symlinks=follow) |
| Antoine Pitrou | 910bd51 | 2010-03-22 20:11:09 +0000 | [diff] [blame] | 212 | except OSError as why: |
| Ned Deily | baf7571 | 2012-05-10 17:05:19 -0700 | [diff] [blame] | 213 | for err in 'EOPNOTSUPP', 'ENOTSUP': |
| 214 | if hasattr(errno, err) and why.errno == getattr(errno, err): |
| 215 | break |
| 216 | else: |
| Antoine Pitrou | 910bd51 | 2010-03-22 20:11:09 +0000 | [diff] [blame] | 217 | raise |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 218 | _copyxattr(src, dst, follow_symlinks=follow) |
| Antoine Pitrou | 424246f | 2012-05-12 19:02:01 +0200 | [diff] [blame] | 219 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 220 | def copy(src, dst, *, follow_symlinks=True): |
| Brian Curtin | 0d0a1de | 2012-06-18 18:41:07 -0500 | [diff] [blame] | 221 | """Copy data and mode bits ("cp src dst"). Return the file's destination. |
| Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 222 | |
| Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 223 | The destination may be a directory. |
| 224 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 225 | If follow_symlinks is false, symlinks won't be followed. This |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 226 | resembles GNU's "cp -P src dst". |
| 227 | |
| Hynek Schlawack | 4865376 | 2012-10-07 12:49:58 +0200 | [diff] [blame] | 228 | If source and destination are the same file, a SameFileError will be |
| 229 | raised. |
| 230 | |
| Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 231 | """ |
| Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 232 | if os.path.isdir(dst): |
| Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 233 | dst = os.path.join(dst, os.path.basename(src)) |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 234 | copyfile(src, dst, follow_symlinks=follow_symlinks) |
| 235 | copymode(src, dst, follow_symlinks=follow_symlinks) |
| Brian Curtin | 0d0a1de | 2012-06-18 18:41:07 -0500 | [diff] [blame] | 236 | return dst |
| Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 237 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 238 | def copy2(src, dst, *, follow_symlinks=True): |
| Brian Curtin | 0d0a1de | 2012-06-18 18:41:07 -0500 | [diff] [blame] | 239 | """Copy data and all stat info ("cp -p src dst"). Return the file's |
| 240 | destination." |
| Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 241 | |
| 242 | The destination may be a directory. |
| 243 | |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 244 | If follow_symlinks is false, symlinks won't be followed. This |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 245 | resembles GNU's "cp -P src dst". |
| 246 | |
| Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 247 | """ |
| Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 248 | if os.path.isdir(dst): |
| Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 249 | dst = os.path.join(dst, os.path.basename(src)) |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 250 | copyfile(src, dst, follow_symlinks=follow_symlinks) |
| 251 | copystat(src, dst, follow_symlinks=follow_symlinks) |
| Brian Curtin | 0d0a1de | 2012-06-18 18:41:07 -0500 | [diff] [blame] | 252 | return dst |
| Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 253 | |
| Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 254 | def ignore_patterns(*patterns): |
| 255 | """Function that can be used as copytree() ignore parameter. |
| Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 256 | |
| Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 257 | Patterns is a sequence of glob-style patterns |
| 258 | that are used to exclude files""" |
| 259 | def _ignore_patterns(path, names): |
| 260 | ignored_names = [] |
| 261 | for pattern in patterns: |
| 262 | ignored_names.extend(fnmatch.filter(names, pattern)) |
| 263 | return set(ignored_names) |
| 264 | return _ignore_patterns |
| 265 | |
| Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 266 | def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, |
| 267 | ignore_dangling_symlinks=False): |
| Tarek Ziadé | 5340db3 | 2010-04-19 22:30:51 +0000 | [diff] [blame] | 268 | """Recursively copy a directory tree. |
| Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 269 | |
| 270 | The destination directory must not already exist. |
| Neal Norwitz | a4c93b6 | 2003-02-23 21:36:32 +0000 | [diff] [blame] | 271 | 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] | 272 | |
| 273 | If the optional symlinks flag is true, symbolic links in the |
| 274 | source tree result in symbolic links in the destination tree; if |
| 275 | it is false, the contents of the files pointed to by symbolic |
| Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 276 | links are copied. If the file pointed by the symlink doesn't |
| 277 | exist, an exception will be added in the list of errors raised in |
| 278 | an Error exception at the end of the copy process. |
| 279 | |
| 280 | 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] | 281 | want to silence this exception. Notice that this has no effect on |
| 282 | platforms that don't support os.symlink. |
| Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 283 | |
| Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 284 | The optional ignore argument is a callable. If given, it |
| 285 | is called with the `src` parameter, which is the directory |
| 286 | being visited by copytree(), and `names` which is the list of |
| 287 | `src` contents, as returned by os.listdir(): |
| 288 | |
| 289 | callable(src, names) -> ignored_names |
| 290 | |
| 291 | Since copytree() is called recursively, the callable will be |
| 292 | called once for each directory that is copied. It returns a |
| 293 | list of names relative to the `src` directory that should |
| 294 | not be copied. |
| 295 | |
| Tarek Ziadé | 5340db3 | 2010-04-19 22:30:51 +0000 | [diff] [blame] | 296 | The optional copy_function argument is a callable that will be used |
| 297 | to copy each file. It will be called with the source path and the |
| 298 | destination path as arguments. By default, copy2() is used, but any |
| 299 | function that supports the same signature (like copy()) can be used. |
| Guido van Rossum | 9d0a3df | 1997-04-29 14:45:19 +0000 | [diff] [blame] | 300 | |
| 301 | """ |
| Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 302 | names = os.listdir(src) |
| Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 303 | if ignore is not None: |
| 304 | ignored_names = ignore(src, names) |
| 305 | else: |
| 306 | ignored_names = set() |
| 307 | |
| Johannes Gijsbers | e4172ea | 2005-01-08 12:31:29 +0000 | [diff] [blame] | 308 | os.makedirs(dst) |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 309 | errors = [] |
| Guido van Rossum | a2baf46 | 1997-04-29 14:06:46 +0000 | [diff] [blame] | 310 | for name in names: |
| Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 311 | if name in ignored_names: |
| 312 | continue |
| Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 313 | srcname = os.path.join(src, name) |
| 314 | dstname = os.path.join(dst, name) |
| 315 | try: |
| Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 316 | if os.path.islink(srcname): |
| Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 317 | linkto = os.readlink(srcname) |
| Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 318 | if symlinks: |
| Antoine Pitrou | 78091e6 | 2011-12-29 18:54:15 +0100 | [diff] [blame] | 319 | # We can't just leave it to `copy_function` because legacy |
| 320 | # code with a custom `copy_function` may rely on copytree |
| 321 | # doing the right thing. |
| Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 322 | os.symlink(linkto, dstname) |
| Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 323 | copystat(srcname, dstname, follow_symlinks=not symlinks) |
| Tarek Ziadé | fb43751 | 2010-04-20 08:57:33 +0000 | [diff] [blame] | 324 | else: |
| 325 | # ignore dangling symlink if the flag is on |
| 326 | if not os.path.exists(linkto) and ignore_dangling_symlinks: |
| 327 | continue |
| 328 | # otherwise let the copy occurs. copy2 will raise an error |
| 329 | copy_function(srcname, dstname) |
| Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 330 | elif os.path.isdir(srcname): |
| Tarek Ziadé | 5340db3 | 2010-04-19 22:30:51 +0000 | [diff] [blame] | 331 | copytree(srcname, dstname, symlinks, ignore, copy_function) |
| Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 332 | else: |
| Antoine Pitrou | 7fff096 | 2009-05-01 21:09:44 +0000 | [diff] [blame] | 333 | # Will raise a SpecialFileError for unsupported file types |
| Tarek Ziadé | 5340db3 | 2010-04-19 22:30:51 +0000 | [diff] [blame] | 334 | copy_function(srcname, dstname) |
| Georg Brandl | a1be88e | 2005-08-31 22:48:45 +0000 | [diff] [blame] | 335 | # catch the Error from the recursive copytree so that we can |
| 336 | # continue with other files |
| Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 337 | except Error as err: |
| Georg Brandl | a1be88e | 2005-08-31 22:48:45 +0000 | [diff] [blame] | 338 | errors.extend(err.args[0]) |
| Andrew Svetlov | 3438fa4 | 2012-12-17 23:35:18 +0200 | [diff] [blame] | 339 | except OSError as why: |
| Antoine Pitrou | 7fff096 | 2009-05-01 21:09:44 +0000 | [diff] [blame] | 340 | errors.append((srcname, dstname, str(why))) |
| Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 341 | try: |
| 342 | copystat(src, dst) |
| Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 343 | except OSError as why: |
| Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 344 | # Copying file access times may fail on Windows |
| 345 | if why.winerror is None: |
| Georg Brandl | c8076df | 2012-08-25 10:11:57 +0200 | [diff] [blame] | 346 | errors.append((src, dst, str(why))) |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 347 | if errors: |
| Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 348 | raise Error(errors) |
| Brian Curtin | 0d0a1de | 2012-06-18 18:41:07 -0500 | [diff] [blame] | 349 | return dst |
| Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 350 | |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 351 | # version vulnerable to race conditions |
| 352 | def _rmtree_unsafe(path, onerror): |
| Christian Heimes | 9bd667a | 2008-01-20 15:14:11 +0000 | [diff] [blame] | 353 | try: |
| 354 | if os.path.islink(path): |
| 355 | # symlinks to directories are forbidden, see bug #1669 |
| 356 | raise OSError("Cannot call rmtree on a symbolic link") |
| 357 | except OSError: |
| 358 | onerror(os.path.islink, path, sys.exc_info()) |
| 359 | # can't continue even if onerror hook returns |
| 360 | return |
| Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 361 | names = [] |
| 362 | try: |
| 363 | names = os.listdir(path) |
| Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 364 | except OSError: |
| Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 365 | onerror(os.listdir, path, sys.exc_info()) |
| 366 | for name in names: |
| 367 | fullname = os.path.join(path, name) |
| 368 | try: |
| 369 | mode = os.lstat(fullname).st_mode |
| Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 370 | except OSError: |
| Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 371 | mode = 0 |
| 372 | if stat.S_ISDIR(mode): |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 373 | _rmtree_unsafe(fullname, onerror) |
| Barry Warsaw | 234d9a9 | 2003-01-24 17:36:15 +0000 | [diff] [blame] | 374 | else: |
| Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 375 | try: |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 376 | os.unlink(fullname) |
| Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 377 | except OSError: |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 378 | onerror(os.unlink, fullname, sys.exc_info()) |
| Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 379 | try: |
| 380 | os.rmdir(path) |
| Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 381 | except OSError: |
| Johannes Gijsbers | ef5ffc4 | 2004-10-31 12:05:31 +0000 | [diff] [blame] | 382 | onerror(os.rmdir, path, sys.exc_info()) |
| Guido van Rossum | d767329 | 1998-02-06 21:38:09 +0000 | [diff] [blame] | 383 | |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 384 | # Version using fd-based APIs to protect against races |
| 385 | def _rmtree_safe_fd(topfd, path, onerror): |
| 386 | names = [] |
| 387 | try: |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 388 | names = os.listdir(topfd) |
| Hynek Schlawack | b550110 | 2012-12-10 09:11:25 +0100 | [diff] [blame] | 389 | except OSError as err: |
| 390 | err.filename = path |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 391 | onerror(os.listdir, path, sys.exc_info()) |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 392 | for name in names: |
| 393 | fullname = os.path.join(path, name) |
| 394 | try: |
| Hynek Schlawack | a75cd1c | 2012-06-28 12:07:29 +0200 | [diff] [blame] | 395 | orig_st = os.stat(name, dir_fd=topfd, follow_symlinks=False) |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 396 | mode = orig_st.st_mode |
| Hynek Schlawack | b550110 | 2012-12-10 09:11:25 +0100 | [diff] [blame] | 397 | except OSError: |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 398 | mode = 0 |
| 399 | if stat.S_ISDIR(mode): |
| 400 | try: |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 401 | dirfd = os.open(name, os.O_RDONLY, dir_fd=topfd) |
| Hynek Schlawack | b550110 | 2012-12-10 09:11:25 +0100 | [diff] [blame] | 402 | except OSError: |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 403 | onerror(os.open, fullname, sys.exc_info()) |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 404 | else: |
| 405 | try: |
| 406 | if os.path.samestat(orig_st, os.fstat(dirfd)): |
| 407 | _rmtree_safe_fd(dirfd, fullname, onerror) |
| Hynek Schlawack | 9f558cc | 2012-06-28 15:30:47 +0200 | [diff] [blame] | 408 | try: |
| 409 | os.rmdir(name, dir_fd=topfd) |
| Hynek Schlawack | b550110 | 2012-12-10 09:11:25 +0100 | [diff] [blame] | 410 | except OSError: |
| Hynek Schlawack | 9f558cc | 2012-06-28 15:30:47 +0200 | [diff] [blame] | 411 | onerror(os.rmdir, fullname, sys.exc_info()) |
| Hynek Schlawack | b550110 | 2012-12-10 09:11:25 +0100 | [diff] [blame] | 412 | else: |
| 413 | try: |
| 414 | # This can only happen if someone replaces |
| 415 | # a directory with a symlink after the call to |
| 416 | # stat.S_ISDIR above. |
| 417 | raise OSError("Cannot call rmtree on a symbolic " |
| 418 | "link") |
| 419 | except OSError: |
| 420 | onerror(os.path.islink, fullname, sys.exc_info()) |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 421 | finally: |
| 422 | os.close(dirfd) |
| 423 | else: |
| 424 | try: |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 425 | os.unlink(name, dir_fd=topfd) |
| Hynek Schlawack | b550110 | 2012-12-10 09:11:25 +0100 | [diff] [blame] | 426 | except OSError: |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 427 | onerror(os.unlink, fullname, sys.exc_info()) |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 428 | |
| Hynek Schlawack | d0f6e0a | 2012-06-29 08:28:20 +0200 | [diff] [blame] | 429 | _use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <= |
| 430 | os.supports_dir_fd and |
| 431 | os.listdir in os.supports_fd and |
| 432 | os.stat in os.supports_follow_symlinks) |
| Nick Coghlan | 5b0eca1 | 2012-06-24 16:43:06 +1000 | [diff] [blame] | 433 | |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 434 | def rmtree(path, ignore_errors=False, onerror=None): |
| 435 | """Recursively delete a directory tree. |
| 436 | |
| 437 | If ignore_errors is set, errors are ignored; otherwise, if onerror |
| 438 | is set, it is called to handle the error with arguments (func, |
| Hynek Schlawack | 2100b42 | 2012-06-23 20:28:32 +0200 | [diff] [blame] | 439 | path, exc_info) where func is platform and implementation dependent; |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 440 | path is the argument to that function that caused it to fail; and |
| 441 | exc_info is a tuple returned by sys.exc_info(). If ignore_errors |
| 442 | is false and onerror is None, an exception is raised. |
| 443 | |
| 444 | """ |
| 445 | if ignore_errors: |
| 446 | def onerror(*args): |
| 447 | pass |
| 448 | elif onerror is None: |
| 449 | def onerror(*args): |
| 450 | raise |
| 451 | if _use_fd_functions: |
| Hynek Schlawack | 3b52778 | 2012-06-25 13:27:31 +0200 | [diff] [blame] | 452 | # While the unsafe rmtree works fine on bytes, the fd based does not. |
| 453 | if isinstance(path, bytes): |
| 454 | path = os.fsdecode(path) |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 455 | # Note: To guard against symlink races, we use the standard |
| 456 | # lstat()/open()/fstat() trick. |
| 457 | try: |
| 458 | orig_st = os.lstat(path) |
| 459 | except Exception: |
| 460 | onerror(os.lstat, path, sys.exc_info()) |
| 461 | return |
| 462 | try: |
| 463 | fd = os.open(path, os.O_RDONLY) |
| 464 | except Exception: |
| 465 | onerror(os.lstat, path, sys.exc_info()) |
| 466 | return |
| 467 | try: |
| Hynek Schlawack | b550110 | 2012-12-10 09:11:25 +0100 | [diff] [blame] | 468 | if os.path.samestat(orig_st, os.fstat(fd)): |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 469 | _rmtree_safe_fd(fd, path, onerror) |
| Hynek Schlawack | 9f558cc | 2012-06-28 15:30:47 +0200 | [diff] [blame] | 470 | try: |
| 471 | os.rmdir(path) |
| Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 472 | except OSError: |
| Hynek Schlawack | 9f558cc | 2012-06-28 15:30:47 +0200 | [diff] [blame] | 473 | onerror(os.rmdir, path, sys.exc_info()) |
| Hynek Schlawack | a75cd1c | 2012-06-28 12:07:29 +0200 | [diff] [blame] | 474 | else: |
| Hynek Schlawack | b550110 | 2012-12-10 09:11:25 +0100 | [diff] [blame] | 475 | try: |
| 476 | # symlinks to directories are forbidden, see bug #1669 |
| 477 | raise OSError("Cannot call rmtree on a symbolic link") |
| 478 | except OSError: |
| 479 | onerror(os.path.islink, path, sys.exc_info()) |
| Hynek Schlawack | 67be92b | 2012-06-23 17:58:42 +0200 | [diff] [blame] | 480 | finally: |
| 481 | os.close(fd) |
| 482 | else: |
| 483 | return _rmtree_unsafe(path, onerror) |
| 484 | |
| Nick Coghlan | 5b0eca1 | 2012-06-24 16:43:06 +1000 | [diff] [blame] | 485 | # Allow introspection of whether or not the hardening against symlink |
| 486 | # attacks is supported on the current platform |
| 487 | rmtree.avoids_symlink_attacks = _use_fd_functions |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 488 | |
| Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 489 | def _basename(path): |
| 490 | # A basename() variant which first strips the trailing slash, if present. |
| 491 | # Thus we always get the last component of the path, even for directories. |
| Serhiy Storchaka | 3a308b9 | 2014-02-11 10:30:59 +0200 | [diff] [blame] | 492 | sep = os.path.sep + (os.path.altsep or '') |
| 493 | return os.path.basename(path.rstrip(sep)) |
| Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 494 | |
| R David Murray | 6ffface | 2014-06-11 14:40:13 -0400 | [diff] [blame] | 495 | def move(src, dst, copy_function=copy2): |
| Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 496 | """Recursively move a file or directory to another location. This is |
| Brian Curtin | 0d0a1de | 2012-06-18 18:41:07 -0500 | [diff] [blame] | 497 | similar to the Unix "mv" command. Return the file or directory's |
| 498 | destination. |
| Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 499 | |
| 500 | If the destination is a directory or a symlink to a directory, the source |
| 501 | is moved inside the directory. The destination path must not already |
| 502 | exist. |
| 503 | |
| 504 | If the destination already exists but is not a directory, it may be |
| 505 | overwritten depending on os.rename() semantics. |
| 506 | |
| 507 | If the destination is on our current filesystem, then rename() is used. |
| Antoine Pitrou | 0a08d7a | 2012-01-06 20:16:19 +0100 | [diff] [blame] | 508 | Otherwise, src is copied to the destination and then removed. Symlinks are |
| 509 | recreated under the new name if os.rename() fails because of cross |
| 510 | filesystem renames. |
| 511 | |
| R David Murray | 6ffface | 2014-06-11 14:40:13 -0400 | [diff] [blame] | 512 | The optional `copy_function` argument is a callable that will be used |
| 513 | to copy the source or it will be delegated to `copytree`. |
| 514 | By default, copy2() is used, but any function that supports the same |
| 515 | signature (like copy()) can be used. |
| 516 | |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 517 | A lot more could be done here... A look at a mv.c shows a lot of |
| 518 | the issues this implementation glosses over. |
| 519 | |
| 520 | """ |
| Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 521 | real_dst = dst |
| 522 | if os.path.isdir(dst): |
| Ronald Oussoren | f51738b | 2011-05-06 10:23:04 +0200 | [diff] [blame] | 523 | if _samefile(src, dst): |
| 524 | # We might be on a case insensitive filesystem, |
| 525 | # perform the rename anyway. |
| 526 | os.rename(src, dst) |
| 527 | return |
| 528 | |
| Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 529 | real_dst = os.path.join(dst, _basename(src)) |
| 530 | if os.path.exists(real_dst): |
| 531 | raise Error("Destination path '%s' already exists" % real_dst) |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 532 | try: |
| Christian Heimes | ada8c3b | 2008-03-18 18:26:33 +0000 | [diff] [blame] | 533 | os.rename(src, real_dst) |
| Éric Araujo | cfcc977 | 2011-08-10 20:54:33 +0200 | [diff] [blame] | 534 | except OSError: |
| Antoine Pitrou | 0a08d7a | 2012-01-06 20:16:19 +0100 | [diff] [blame] | 535 | if os.path.islink(src): |
| 536 | linkto = os.readlink(src) |
| 537 | os.symlink(linkto, real_dst) |
| 538 | os.unlink(src) |
| 539 | elif os.path.isdir(src): |
| Benjamin Peterson | 247a9b8 | 2009-02-20 04:09:19 +0000 | [diff] [blame] | 540 | if _destinsrc(src, dst): |
| R David Murray | 6ffface | 2014-06-11 14:40:13 -0400 | [diff] [blame] | 541 | raise Error("Cannot move a directory '%s' into itself" |
| 542 | " '%s'." % (src, dst)) |
| 543 | copytree(src, real_dst, copy_function=copy_function, |
| 544 | symlinks=True) |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 545 | rmtree(src) |
| 546 | else: |
| R David Murray | 6ffface | 2014-06-11 14:40:13 -0400 | [diff] [blame] | 547 | copy_function(src, real_dst) |
| Martin v. Löwis | e9ce0b0 | 2002-10-07 13:23:24 +0000 | [diff] [blame] | 548 | os.unlink(src) |
| Brian Curtin | 0d0a1de | 2012-06-18 18:41:07 -0500 | [diff] [blame] | 549 | return real_dst |
| Brett Cannon | 1c3fa18 | 2004-06-19 21:11:35 +0000 | [diff] [blame] | 550 | |
| Benjamin Peterson | 247a9b8 | 2009-02-20 04:09:19 +0000 | [diff] [blame] | 551 | def _destinsrc(src, dst): |
| Berker Peksag | 3715da5 | 2014-09-18 05:11:15 +0300 | [diff] [blame] | 552 | src = os.path.abspath(src) |
| 553 | dst = os.path.abspath(dst) |
| Antoine Pitrou | 0dcc3cd | 2009-01-29 20:26:59 +0000 | [diff] [blame] | 554 | if not src.endswith(os.path.sep): |
| 555 | src += os.path.sep |
| 556 | if not dst.endswith(os.path.sep): |
| 557 | dst += os.path.sep |
| 558 | return dst.startswith(src) |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 559 | |
| 560 | def _get_gid(name): |
| 561 | """Returns a gid, given a group name.""" |
| 562 | if getgrnam is None or name is None: |
| 563 | return None |
| 564 | try: |
| 565 | result = getgrnam(name) |
| 566 | except KeyError: |
| 567 | result = None |
| 568 | if result is not None: |
| 569 | return result[2] |
| 570 | return None |
| 571 | |
| 572 | def _get_uid(name): |
| 573 | """Returns an uid, given a user name.""" |
| 574 | if getpwnam is None or name is None: |
| 575 | return None |
| 576 | try: |
| 577 | result = getpwnam(name) |
| 578 | except KeyError: |
| 579 | result = None |
| 580 | if result is not None: |
| 581 | return result[2] |
| 582 | return None |
| 583 | |
| 584 | def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, |
| 585 | owner=None, group=None, logger=None): |
| 586 | """Create a (possibly compressed) tar file from all the files under |
| 587 | 'base_dir'. |
| 588 | |
| Serhiy Storchaka | 1121377 | 2014-08-06 18:50:19 +0300 | [diff] [blame] | 589 | 'compress' must be "gzip" (the default), "bzip2", "xz", or None. |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 590 | |
| 591 | 'owner' and 'group' can be used to define an owner and a group for the |
| 592 | archive that is being built. If not provided, the current owner and group |
| 593 | will be used. |
| 594 | |
| Éric Araujo | 4433a5f | 2010-12-15 20:26:30 +0000 | [diff] [blame] | 595 | The output tar file will be named 'base_name' + ".tar", possibly plus |
| Serhiy Storchaka | 1121377 | 2014-08-06 18:50:19 +0300 | [diff] [blame] | 596 | the appropriate compression extension (".gz", ".bz2", or ".xz"). |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 597 | |
| 598 | Returns the output filename. |
| 599 | """ |
| Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 600 | tar_compression = {'gzip': 'gz', None: ''} |
| 601 | compress_ext = {'gzip': '.gz'} |
| 602 | |
| 603 | if _BZ2_SUPPORTED: |
| 604 | tar_compression['bzip2'] = 'bz2' |
| 605 | compress_ext['bzip2'] = '.bz2' |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 606 | |
| Serhiy Storchaka | 1121377 | 2014-08-06 18:50:19 +0300 | [diff] [blame] | 607 | if _LZMA_SUPPORTED: |
| 608 | tar_compression['xz'] = 'xz' |
| 609 | compress_ext['xz'] = '.xz' |
| 610 | |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 611 | # flags for compression program, each element of list will be an argument |
| Éric Araujo | c1b7e7f | 2011-09-18 23:12:30 +0200 | [diff] [blame] | 612 | if compress is not None and compress not in compress_ext: |
| Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 613 | raise ValueError("bad value for 'compress', or compression format not " |
| 614 | "supported : {0}".format(compress)) |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 615 | |
| Tarek Ziadé | 5e2be87 | 2010-04-20 21:40:47 +0000 | [diff] [blame] | 616 | archive_name = base_name + '.tar' + compress_ext.get(compress, '') |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 617 | archive_dir = os.path.dirname(archive_name) |
| Tarek Ziadé | 5e2be87 | 2010-04-20 21:40:47 +0000 | [diff] [blame] | 618 | |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 619 | if not os.path.exists(archive_dir): |
| Éric Araujo | ac4e58e | 2011-01-29 20:32:11 +0000 | [diff] [blame] | 620 | if logger is not None: |
| Éric Araujo | 43a7ee1 | 2011-08-19 02:55:11 +0200 | [diff] [blame] | 621 | logger.info("creating %s", archive_dir) |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 622 | if not dry_run: |
| 623 | os.makedirs(archive_dir) |
| 624 | |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 625 | # creating the tarball |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 626 | if logger is not None: |
| 627 | logger.info('Creating tar archive') |
| 628 | |
| 629 | uid = _get_uid(owner) |
| 630 | gid = _get_gid(group) |
| 631 | |
| 632 | def _set_uid_gid(tarinfo): |
| 633 | if gid is not None: |
| 634 | tarinfo.gid = gid |
| 635 | tarinfo.gname = group |
| 636 | if uid is not None: |
| 637 | tarinfo.uid = uid |
| 638 | tarinfo.uname = owner |
| 639 | return tarinfo |
| 640 | |
| 641 | if not dry_run: |
| 642 | tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress]) |
| 643 | try: |
| 644 | tar.add(base_dir, filter=_set_uid_gid) |
| 645 | finally: |
| 646 | tar.close() |
| 647 | |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 648 | return archive_name |
| 649 | |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 650 | def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): |
| 651 | """Create a zip file from all the files under 'base_dir'. |
| 652 | |
| Éric Araujo | 4433a5f | 2010-12-15 20:26:30 +0000 | [diff] [blame] | 653 | 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] | 654 | "zipfile" Python module (if available) or the InfoZIP "zip" utility |
| 655 | (if installed and found on the default search path). If neither tool is |
| 656 | available, raises ExecError. Returns the name of the output zip |
| 657 | file. |
| 658 | """ |
| Andrew Kuchling | a0934b2 | 2014-03-20 16:11:16 -0400 | [diff] [blame] | 659 | import zipfile |
| 660 | |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 661 | zip_filename = base_name + ".zip" |
| 662 | archive_dir = os.path.dirname(base_name) |
| 663 | |
| 664 | if not os.path.exists(archive_dir): |
| 665 | if logger is not None: |
| 666 | logger.info("creating %s", archive_dir) |
| 667 | if not dry_run: |
| 668 | os.makedirs(archive_dir) |
| 669 | |
| Andrew Kuchling | a0934b2 | 2014-03-20 16:11:16 -0400 | [diff] [blame] | 670 | if logger is not None: |
| 671 | logger.info("creating '%s' and adding '%s' to it", |
| 672 | zip_filename, base_dir) |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 673 | |
| Andrew Kuchling | a0934b2 | 2014-03-20 16:11:16 -0400 | [diff] [blame] | 674 | if not dry_run: |
| 675 | with zipfile.ZipFile(zip_filename, "w", |
| 676 | compression=zipfile.ZIP_DEFLATED) as zf: |
| 677 | for dirpath, dirnames, filenames in os.walk(base_dir): |
| 678 | for name in filenames: |
| 679 | path = os.path.normpath(os.path.join(dirpath, name)) |
| 680 | if os.path.isfile(path): |
| 681 | zf.write(path, path) |
| 682 | if logger is not None: |
| 683 | logger.info("adding '%s'", path) |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 684 | |
| 685 | return zip_filename |
| 686 | |
| 687 | _ARCHIVE_FORMATS = { |
| 688 | 'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 689 | 'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"), |
| Éric Araujo | c1b7e7f | 2011-09-18 23:12:30 +0200 | [diff] [blame] | 690 | 'zip': (_make_zipfile, [], "ZIP file") |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 691 | } |
| 692 | |
| Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 693 | if _BZ2_SUPPORTED: |
| 694 | _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')], |
| 695 | "bzip2'ed tar-file") |
| 696 | |
| Serhiy Storchaka | 1121377 | 2014-08-06 18:50:19 +0300 | [diff] [blame] | 697 | if _LZMA_SUPPORTED: |
| 698 | _ARCHIVE_FORMATS['xztar'] = (_make_tarball, [('compress', 'xz')], |
| 699 | "xz'ed tar-file") |
| 700 | |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 701 | def get_archive_formats(): |
| 702 | """Returns a list of supported formats for archiving and unarchiving. |
| 703 | |
| 704 | Each element of the returned sequence is a tuple (name, description) |
| 705 | """ |
| 706 | formats = [(name, registry[2]) for name, registry in |
| 707 | _ARCHIVE_FORMATS.items()] |
| 708 | formats.sort() |
| 709 | return formats |
| 710 | |
| 711 | def register_archive_format(name, function, extra_args=None, description=''): |
| 712 | """Registers an archive format. |
| 713 | |
| 714 | name is the name of the format. function is the callable that will be |
| 715 | used to create archives. If provided, extra_args is a sequence of |
| 716 | (name, value) tuples that will be passed as arguments to the callable. |
| 717 | description can be provided to describe the format, and will be returned |
| 718 | by the get_archive_formats() function. |
| 719 | """ |
| 720 | if extra_args is None: |
| 721 | extra_args = [] |
| Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 722 | if not callable(function): |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 723 | raise TypeError('The %s object is not callable' % function) |
| 724 | if not isinstance(extra_args, (tuple, list)): |
| 725 | raise TypeError('extra_args needs to be a sequence') |
| 726 | for element in extra_args: |
| Éric Araujo | c1b7e7f | 2011-09-18 23:12:30 +0200 | [diff] [blame] | 727 | if not isinstance(element, (tuple, list)) or len(element) !=2: |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 728 | raise TypeError('extra_args elements are : (arg_name, value)') |
| 729 | |
| 730 | _ARCHIVE_FORMATS[name] = (function, extra_args, description) |
| 731 | |
| 732 | def unregister_archive_format(name): |
| 733 | del _ARCHIVE_FORMATS[name] |
| 734 | |
| 735 | def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, |
| 736 | dry_run=0, owner=None, group=None, logger=None): |
| 737 | """Create an archive file (eg. zip or tar). |
| 738 | |
| 739 | '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] | 740 | extension; 'format' is the archive format: one of "zip", "tar", "bztar" |
| 741 | or "gztar". |
| Tarek Ziadé | 396fad7 | 2010-02-23 05:30:31 +0000 | [diff] [blame] | 742 | |
| 743 | 'root_dir' is a directory that will be the root directory of the |
| 744 | archive; ie. we typically chdir into 'root_dir' before creating the |
| 745 | archive. 'base_dir' is the directory where we start archiving from; |
| 746 | ie. 'base_dir' will be the common prefix of all files and |
| 747 | directories in the archive. 'root_dir' and 'base_dir' both default |
| 748 | to the current directory. Returns the name of the archive file. |
| 749 | |
| 750 | 'owner' and 'group' are used when creating a tar archive. By default, |
| 751 | uses the current owner and group. |
| 752 | """ |
| 753 | save_cwd = os.getcwd() |
| 754 | if root_dir is not None: |
| 755 | if logger is not None: |
| 756 | logger.debug("changing into '%s'", root_dir) |
| 757 | base_name = os.path.abspath(base_name) |
| 758 | if not dry_run: |
| 759 | os.chdir(root_dir) |
| 760 | |
| 761 | if base_dir is None: |
| 762 | base_dir = os.curdir |
| 763 | |
| 764 | kwargs = {'dry_run': dry_run, 'logger': logger} |
| 765 | |
| 766 | try: |
| 767 | format_info = _ARCHIVE_FORMATS[format] |
| 768 | except KeyError: |
| 769 | raise ValueError("unknown archive format '%s'" % format) |
| 770 | |
| 771 | func = format_info[0] |
| 772 | for arg, val in format_info[1]: |
| 773 | kwargs[arg] = val |
| 774 | |
| 775 | if format != 'zip': |
| 776 | kwargs['owner'] = owner |
| 777 | kwargs['group'] = group |
| 778 | |
| 779 | try: |
| 780 | filename = func(base_name, base_dir, **kwargs) |
| 781 | finally: |
| 782 | if root_dir is not None: |
| 783 | if logger is not None: |
| 784 | logger.debug("changing back to '%s'", save_cwd) |
| 785 | os.chdir(save_cwd) |
| 786 | |
| 787 | return filename |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 788 | |
| 789 | |
| 790 | def get_unpack_formats(): |
| 791 | """Returns a list of supported formats for unpacking. |
| 792 | |
| 793 | Each element of the returned sequence is a tuple |
| 794 | (name, extensions, description) |
| 795 | """ |
| 796 | formats = [(name, info[0], info[3]) for name, info in |
| 797 | _UNPACK_FORMATS.items()] |
| 798 | formats.sort() |
| 799 | return formats |
| 800 | |
| 801 | def _check_unpack_options(extensions, function, extra_args): |
| 802 | """Checks what gets registered as an unpacker.""" |
| 803 | # first make sure no other unpacker is registered for this extension |
| 804 | existing_extensions = {} |
| 805 | for name, info in _UNPACK_FORMATS.items(): |
| 806 | for ext in info[0]: |
| 807 | existing_extensions[ext] = name |
| 808 | |
| 809 | for extension in extensions: |
| 810 | if extension in existing_extensions: |
| 811 | msg = '%s is already registered for "%s"' |
| 812 | raise RegistryError(msg % (extension, |
| 813 | existing_extensions[extension])) |
| 814 | |
| Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 815 | if not callable(function): |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 816 | raise TypeError('The registered function must be a callable') |
| 817 | |
| 818 | |
| 819 | def register_unpack_format(name, extensions, function, extra_args=None, |
| 820 | description=''): |
| 821 | """Registers an unpack format. |
| 822 | |
| 823 | `name` is the name of the format. `extensions` is a list of extensions |
| 824 | corresponding to the format. |
| 825 | |
| 826 | `function` is the callable that will be |
| 827 | used to unpack archives. The callable will receive archives to unpack. |
| 828 | If it's unable to handle an archive, it needs to raise a ReadError |
| 829 | exception. |
| 830 | |
| 831 | If provided, `extra_args` is a sequence of |
| 832 | (name, value) tuples that will be passed as arguments to the callable. |
| 833 | description can be provided to describe the format, and will be returned |
| 834 | by the get_unpack_formats() function. |
| 835 | """ |
| 836 | if extra_args is None: |
| 837 | extra_args = [] |
| 838 | _check_unpack_options(extensions, function, extra_args) |
| 839 | _UNPACK_FORMATS[name] = extensions, function, extra_args, description |
| 840 | |
| 841 | def unregister_unpack_format(name): |
| 842 | """Removes the pack format from the registery.""" |
| 843 | del _UNPACK_FORMATS[name] |
| 844 | |
| 845 | def _ensure_directory(path): |
| 846 | """Ensure that the parent directory of `path` exists""" |
| 847 | dirname = os.path.dirname(path) |
| 848 | if not os.path.isdir(dirname): |
| 849 | os.makedirs(dirname) |
| 850 | |
| 851 | def _unpack_zipfile(filename, extract_dir): |
| 852 | """Unpack zip `filename` to `extract_dir` |
| 853 | """ |
| 854 | try: |
| 855 | import zipfile |
| Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 856 | except ImportError: |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 857 | raise ReadError('zlib not supported, cannot unpack this archive.') |
| 858 | |
| 859 | if not zipfile.is_zipfile(filename): |
| 860 | raise ReadError("%s is not a zip file" % filename) |
| 861 | |
| 862 | zip = zipfile.ZipFile(filename) |
| 863 | try: |
| 864 | for info in zip.infolist(): |
| 865 | name = info.filename |
| 866 | |
| 867 | # don't extract absolute paths or ones with .. in them |
| 868 | if name.startswith('/') or '..' in name: |
| 869 | continue |
| 870 | |
| 871 | target = os.path.join(extract_dir, *name.split('/')) |
| 872 | if not target: |
| 873 | continue |
| 874 | |
| 875 | _ensure_directory(target) |
| 876 | if not name.endswith('/'): |
| 877 | # file |
| 878 | data = zip.read(info.filename) |
| Éric Araujo | c1b7e7f | 2011-09-18 23:12:30 +0200 | [diff] [blame] | 879 | f = open(target, 'wb') |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 880 | try: |
| 881 | f.write(data) |
| 882 | finally: |
| 883 | f.close() |
| 884 | del data |
| 885 | finally: |
| 886 | zip.close() |
| 887 | |
| 888 | def _unpack_tarfile(filename, extract_dir): |
| Serhiy Storchaka | 1121377 | 2014-08-06 18:50:19 +0300 | [diff] [blame] | 889 | """Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir` |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 890 | """ |
| 891 | try: |
| 892 | tarobj = tarfile.open(filename) |
| 893 | except tarfile.TarError: |
| 894 | raise ReadError( |
| 895 | "%s is not a compressed or uncompressed tar file" % filename) |
| 896 | try: |
| 897 | tarobj.extractall(extract_dir) |
| 898 | finally: |
| 899 | tarobj.close() |
| 900 | |
| 901 | _UNPACK_FORMATS = { |
| 902 | 'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"), |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 903 | 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"), |
| 904 | 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file") |
| 905 | } |
| 906 | |
| Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 907 | if _BZ2_SUPPORTED: |
| Serhiy Storchaka | 1121377 | 2014-08-06 18:50:19 +0300 | [diff] [blame] | 908 | _UNPACK_FORMATS['bztar'] = (['.tar.bz2', '.tbz2'], _unpack_tarfile, [], |
| Tarek Ziadé | ffa155a | 2010-04-29 13:34:35 +0000 | [diff] [blame] | 909 | "bzip2'ed tar-file") |
| 910 | |
| Serhiy Storchaka | 1121377 | 2014-08-06 18:50:19 +0300 | [diff] [blame] | 911 | if _LZMA_SUPPORTED: |
| 912 | _UNPACK_FORMATS['xztar'] = (['.tar.xz', '.txz'], _unpack_tarfile, [], |
| 913 | "xz'ed tar-file") |
| 914 | |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 915 | def _find_unpack_format(filename): |
| 916 | for name, info in _UNPACK_FORMATS.items(): |
| 917 | for extension in info[0]: |
| 918 | if filename.endswith(extension): |
| 919 | return name |
| 920 | return None |
| 921 | |
| 922 | def unpack_archive(filename, extract_dir=None, format=None): |
| 923 | """Unpack an archive. |
| 924 | |
| 925 | `filename` is the name of the archive. |
| 926 | |
| 927 | `extract_dir` is the name of the target directory, where the archive |
| 928 | is unpacked. If not provided, the current working directory is used. |
| 929 | |
| 930 | `format` is the archive format: one of "zip", "tar", or "gztar". Or any |
| 931 | other registered format. If not provided, unpack_archive will use the |
| 932 | filename extension and see if an unpacker was registered for that |
| 933 | extension. |
| 934 | |
| 935 | In case none is found, a ValueError is raised. |
| 936 | """ |
| 937 | if extract_dir is None: |
| 938 | extract_dir = os.getcwd() |
| 939 | |
| 940 | if format is not None: |
| 941 | try: |
| 942 | format_info = _UNPACK_FORMATS[format] |
| 943 | except KeyError: |
| 944 | raise ValueError("Unknown unpack format '{0}'".format(format)) |
| 945 | |
| Nick Coghlan | abf202d | 2011-03-16 13:52:20 -0400 | [diff] [blame] | 946 | func = format_info[1] |
| 947 | func(filename, extract_dir, **dict(format_info[2])) |
| Tarek Ziadé | 6ac9172 | 2010-04-28 17:51:36 +0000 | [diff] [blame] | 948 | else: |
| 949 | # we need to look at the registered unpackers supported extensions |
| 950 | format = _find_unpack_format(filename) |
| 951 | if format is None: |
| 952 | raise ReadError("Unknown archive format '{0}'".format(filename)) |
| 953 | |
| 954 | func = _UNPACK_FORMATS[format][1] |
| 955 | kwargs = dict(_UNPACK_FORMATS[format][2]) |
| 956 | func(filename, extract_dir, **kwargs) |
| Giampaolo Rodola' | 210e7ca | 2011-07-01 13:55:36 +0200 | [diff] [blame] | 957 | |
| Éric Araujo | e4d5b8e | 2011-08-08 16:51:11 +0200 | [diff] [blame] | 958 | |
| 959 | if hasattr(os, 'statvfs'): |
| 960 | |
| 961 | __all__.append('disk_usage') |
| 962 | _ntuple_diskusage = collections.namedtuple('usage', 'total used free') |
| Giampaolo Rodola' | 210e7ca | 2011-07-01 13:55:36 +0200 | [diff] [blame] | 963 | |
| 964 | def disk_usage(path): |
| Éric Araujo | e4d5b8e | 2011-08-08 16:51:11 +0200 | [diff] [blame] | 965 | """Return disk usage statistics about the given path. |
| 966 | |
| Sandro Tosi | f8ae4fa | 2012-04-23 20:07:15 +0200 | [diff] [blame] | 967 | Returned value is a named tuple with attributes 'total', 'used' and |
| Éric Araujo | e4d5b8e | 2011-08-08 16:51:11 +0200 | [diff] [blame] | 968 | 'free', which are the amount of total, used and free space, in bytes. |
| Giampaolo Rodola' | 210e7ca | 2011-07-01 13:55:36 +0200 | [diff] [blame] | 969 | """ |
| Éric Araujo | e4d5b8e | 2011-08-08 16:51:11 +0200 | [diff] [blame] | 970 | st = os.statvfs(path) |
| 971 | free = st.f_bavail * st.f_frsize |
| 972 | total = st.f_blocks * st.f_frsize |
| 973 | used = (st.f_blocks - st.f_bfree) * st.f_frsize |
| 974 | return _ntuple_diskusage(total, used, free) |
| 975 | |
| 976 | elif os.name == 'nt': |
| 977 | |
| 978 | import nt |
| 979 | __all__.append('disk_usage') |
| 980 | _ntuple_diskusage = collections.namedtuple('usage', 'total used free') |
| 981 | |
| 982 | def disk_usage(path): |
| 983 | """Return disk usage statistics about the given path. |
| 984 | |
| Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 985 | Returned values is a named tuple with attributes 'total', 'used' and |
| Éric Araujo | e4d5b8e | 2011-08-08 16:51:11 +0200 | [diff] [blame] | 986 | 'free', which are the amount of total, used and free space, in bytes. |
| 987 | """ |
| 988 | total, free = nt._getdiskusage(path) |
| 989 | used = total - free |
| Giampaolo Rodola' | 210e7ca | 2011-07-01 13:55:36 +0200 | [diff] [blame] | 990 | return _ntuple_diskusage(total, used, free) |
| Sandro Tosi | d902a14 | 2011-08-22 23:28:27 +0200 | [diff] [blame] | 991 | |
| Éric Araujo | 0ac4a5d | 2011-09-01 08:31:51 +0200 | [diff] [blame] | 992 | |
| Sandro Tosi | d902a14 | 2011-08-22 23:28:27 +0200 | [diff] [blame] | 993 | def chown(path, user=None, group=None): |
| 994 | """Change owner user and group of the given path. |
| 995 | |
| 996 | user and group can be the uid/gid or the user/group names, and in that case, |
| 997 | they are converted to their respective uid/gid. |
| 998 | """ |
| 999 | |
| 1000 | if user is None and group is None: |
| 1001 | raise ValueError("user and/or group must be set") |
| 1002 | |
| 1003 | _user = user |
| 1004 | _group = group |
| 1005 | |
| 1006 | # -1 means don't change it |
| 1007 | if user is None: |
| 1008 | _user = -1 |
| 1009 | # user can either be an int (the uid) or a string (the system username) |
| 1010 | elif isinstance(user, str): |
| 1011 | _user = _get_uid(user) |
| 1012 | if _user is None: |
| 1013 | raise LookupError("no such user: {!r}".format(user)) |
| 1014 | |
| 1015 | if group is None: |
| 1016 | _group = -1 |
| 1017 | elif not isinstance(group, int): |
| 1018 | _group = _get_gid(group) |
| 1019 | if _group is None: |
| 1020 | raise LookupError("no such group: {!r}".format(group)) |
| 1021 | |
| 1022 | os.chown(path, _user, _group) |
| Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 1023 | |
| 1024 | def get_terminal_size(fallback=(80, 24)): |
| 1025 | """Get the size of the terminal window. |
| 1026 | |
| 1027 | For each of the two dimensions, the environment variable, COLUMNS |
| 1028 | and LINES respectively, is checked. If the variable is defined and |
| 1029 | the value is a positive integer, it is used. |
| 1030 | |
| 1031 | When COLUMNS or LINES is not defined, which is the common case, |
| 1032 | the terminal connected to sys.__stdout__ is queried |
| 1033 | by invoking os.get_terminal_size. |
| 1034 | |
| 1035 | If the terminal size cannot be successfully queried, either because |
| 1036 | the system doesn't support querying, or because we are not |
| 1037 | connected to a terminal, the value given in fallback parameter |
| 1038 | is used. Fallback defaults to (80, 24) which is the default |
| 1039 | size used by many terminal emulators. |
| 1040 | |
| 1041 | The value returned is a named tuple of type os.terminal_size. |
| 1042 | """ |
| 1043 | # columns, lines are the working values |
| 1044 | try: |
| 1045 | columns = int(os.environ['COLUMNS']) |
| 1046 | except (KeyError, ValueError): |
| 1047 | columns = 0 |
| 1048 | |
| 1049 | try: |
| 1050 | lines = int(os.environ['LINES']) |
| 1051 | except (KeyError, ValueError): |
| 1052 | lines = 0 |
| 1053 | |
| 1054 | # only query if necessary |
| 1055 | if columns <= 0 or lines <= 0: |
| 1056 | try: |
| 1057 | size = os.get_terminal_size(sys.__stdout__.fileno()) |
| 1058 | except (NameError, OSError): |
| 1059 | size = os.terminal_size(fallback) |
| 1060 | if columns <= 0: |
| 1061 | columns = size.columns |
| 1062 | if lines <= 0: |
| 1063 | lines = size.lines |
| 1064 | |
| 1065 | return os.terminal_size((columns, lines)) |
| Brian Curtin | c57a345 | 2012-06-22 16:00:30 -0500 | [diff] [blame] | 1066 | |
| 1067 | def which(cmd, mode=os.F_OK | os.X_OK, path=None): |
| Brian Curtin | dc00f1e | 2012-06-22 22:49:12 -0500 | [diff] [blame] | 1068 | """Given a command, mode, and a PATH string, return the path which |
| Philip Jenvey | 88bc0d2 | 2012-06-23 15:54:38 -0700 | [diff] [blame] | 1069 | conforms to the given mode on the PATH, or None if there is no such |
| 1070 | file. |
| 1071 | |
| 1072 | `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result |
| 1073 | of os.environ.get("PATH"), or can be overridden with a custom search |
| 1074 | path. |
| 1075 | |
| 1076 | """ |
| Victor Stinner | 1d006a2 | 2013-12-16 23:39:40 +0100 | [diff] [blame] | 1077 | # Check that a given file can be accessed with the correct mode. |
| 1078 | # Additionally check that `file` is not a directory, as on Windows |
| 1079 | # directories pass the os.access check. |
| 1080 | def _access_check(fn, mode): |
| 1081 | return (os.path.exists(fn) and os.access(fn, mode) |
| 1082 | and not os.path.isdir(fn)) |
| 1083 | |
| Serhiy Storchaka | 8bea200 | 2013-01-23 10:44:21 +0200 | [diff] [blame] | 1084 | # If we're given a path with a directory part, look it up directly rather |
| 1085 | # than referring to PATH directories. This includes checking relative to the |
| 1086 | # current directory, e.g. ./script |
| 1087 | if os.path.dirname(cmd): |
| 1088 | if _access_check(cmd, mode): |
| 1089 | return cmd |
| 1090 | return None |
| Brian Curtin | c57a345 | 2012-06-22 16:00:30 -0500 | [diff] [blame] | 1091 | |
| Barry Warsaw | 618738b | 2013-04-16 11:05:03 -0400 | [diff] [blame] | 1092 | if path is None: |
| 1093 | path = os.environ.get("PATH", os.defpath) |
| 1094 | if not path: |
| 1095 | return None |
| Victor Stinner | 1d006a2 | 2013-12-16 23:39:40 +0100 | [diff] [blame] | 1096 | path = path.split(os.pathsep) |
| Brian Curtin | c57a345 | 2012-06-22 16:00:30 -0500 | [diff] [blame] | 1097 | |
| 1098 | if sys.platform == "win32": |
| 1099 | # The current directory takes precedence on Windows. |
| 1100 | if not os.curdir in path: |
| 1101 | path.insert(0, os.curdir) |
| 1102 | |
| 1103 | # PATHEXT is necessary to check on Windows. |
| 1104 | pathext = os.environ.get("PATHEXT", "").split(os.pathsep) |
| 1105 | # See if the given file matches any of the expected path extensions. |
| 1106 | # This will allow us to short circuit when given "python.exe". |
| Philip Jenvey | 88bc0d2 | 2012-06-23 15:54:38 -0700 | [diff] [blame] | 1107 | # If it does match, only test that one, otherwise we have to try |
| 1108 | # others. |
| Serhiy Storchaka | 014791f | 2013-01-21 15:00:27 +0200 | [diff] [blame] | 1109 | if any(cmd.lower().endswith(ext.lower()) for ext in pathext): |
| 1110 | files = [cmd] |
| 1111 | else: |
| 1112 | files = [cmd + ext for ext in pathext] |
| Brian Curtin | c57a345 | 2012-06-22 16:00:30 -0500 | [diff] [blame] | 1113 | else: |
| 1114 | # On other platforms you don't have things like PATHEXT to tell you |
| 1115 | # what file suffixes are executable, so just pass on cmd as-is. |
| 1116 | files = [cmd] |
| 1117 | |
| 1118 | seen = set() |
| 1119 | for dir in path: |
| Serhiy Storchaka | 014791f | 2013-01-21 15:00:27 +0200 | [diff] [blame] | 1120 | normdir = os.path.normcase(dir) |
| 1121 | if not normdir in seen: |
| 1122 | seen.add(normdir) |
| Brian Curtin | c57a345 | 2012-06-22 16:00:30 -0500 | [diff] [blame] | 1123 | for thefile in files: |
| 1124 | name = os.path.join(dir, thefile) |
| 1125 | if _access_check(name, mode): |
| 1126 | return name |
| 1127 | return None |