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