shutil.py 55 KB

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