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