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