Debian Codegraph @

lib-python/3/shutil.py

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