logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

shutil.py (52248B)


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