shutil.py 52 KB

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