shutil.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  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 os.name == 'nt':
  259. stat_func, chmod_func = os.lstat, os.chmod
  260. elif hasattr(os, 'lchmod'):
  261. stat_func, chmod_func = os.lstat, os.lchmod
  262. else:
  263. return
  264. else:
  265. if os.name == 'nt' and os.path.islink(dst):
  266. dst = os.path.realpath(dst, strict=True)
  267. stat_func, chmod_func = _stat, os.chmod
  268. st = stat_func(src)
  269. chmod_func(dst, stat.S_IMODE(st.st_mode))
  270. if hasattr(os, 'listxattr'):
  271. def _copyxattr(src, dst, *, follow_symlinks=True):
  272. """Copy extended filesystem attributes from `src` to `dst`.
  273. Overwrite existing attributes.
  274. If `follow_symlinks` is false, symlinks won't be followed.
  275. """
  276. try:
  277. names = os.listxattr(src, follow_symlinks=follow_symlinks)
  278. except OSError as e:
  279. if e.errno not in (errno.ENOTSUP, errno.ENODATA, errno.EINVAL):
  280. raise
  281. return
  282. for name in names:
  283. try:
  284. value = os.getxattr(src, name, follow_symlinks=follow_symlinks)
  285. os.setxattr(dst, name, value, follow_symlinks=follow_symlinks)
  286. except OSError as e:
  287. if e.errno not in (errno.EPERM, errno.ENOTSUP, errno.ENODATA,
  288. errno.EINVAL, errno.EACCES):
  289. raise
  290. else:
  291. def _copyxattr(*args, **kwargs):
  292. pass
  293. def copystat(src, dst, *, follow_symlinks=True):
  294. """Copy file metadata
  295. Copy the permission bits, last access time, last modification time, and
  296. flags from `src` to `dst`. On Linux, copystat() also copies the "extended
  297. attributes" where possible. The file contents, owner, and group are
  298. unaffected. `src` and `dst` are path-like objects or path names given as
  299. strings.
  300. If the optional flag `follow_symlinks` is not set, symlinks aren't
  301. followed if and only if both `src` and `dst` are symlinks.
  302. """
  303. sys.audit("shutil.copystat", src, dst)
  304. def _nop(*args, ns=None, follow_symlinks=None):
  305. pass
  306. # follow symlinks (aka don't not follow symlinks)
  307. follow = follow_symlinks or not (_islink(src) and os.path.islink(dst))
  308. if follow:
  309. # use the real function if it exists
  310. def lookup(name):
  311. return getattr(os, name, _nop)
  312. else:
  313. # use the real function only if it exists
  314. # *and* it supports follow_symlinks
  315. def lookup(name):
  316. fn = getattr(os, name, _nop)
  317. if fn in os.supports_follow_symlinks:
  318. return fn
  319. return _nop
  320. if isinstance(src, os.DirEntry):
  321. st = src.stat(follow_symlinks=follow)
  322. else:
  323. st = lookup("stat")(src, follow_symlinks=follow)
  324. mode = stat.S_IMODE(st.st_mode)
  325. lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns),
  326. follow_symlinks=follow)
  327. # We must copy extended attributes before the file is (potentially)
  328. # chmod()'ed read-only, otherwise setxattr() will error with -EACCES.
  329. _copyxattr(src, dst, follow_symlinks=follow)
  330. _chmod = lookup("chmod")
  331. if os.name == 'nt':
  332. if follow:
  333. if os.path.islink(dst):
  334. dst = os.path.realpath(dst, strict=True)
  335. else:
  336. def _chmod(*args, **kwargs):
  337. os.chmod(*args)
  338. try:
  339. _chmod(dst, mode, follow_symlinks=follow)
  340. except NotImplementedError:
  341. # if we got a NotImplementedError, it's because
  342. # * follow_symlinks=False,
  343. # * lchown() is unavailable, and
  344. # * either
  345. # * fchownat() is unavailable or
  346. # * fchownat() doesn't implement AT_SYMLINK_NOFOLLOW.
  347. # (it returned ENOSUP.)
  348. # therefore we're out of options--we simply cannot chown the
  349. # symlink. give up, suppress the error.
  350. # (which is what shutil always did in this circumstance.)
  351. pass
  352. if hasattr(st, 'st_flags'):
  353. try:
  354. lookup("chflags")(dst, st.st_flags, follow_symlinks=follow)
  355. except OSError as why:
  356. for err in 'EOPNOTSUPP', 'ENOTSUP':
  357. if hasattr(errno, err) and why.errno == getattr(errno, err):
  358. break
  359. else:
  360. raise
  361. def copy(src, dst, *, follow_symlinks=True):
  362. """Copy data and mode bits ("cp src dst"). Return the file's destination.
  363. The destination may be a directory.
  364. If follow_symlinks is false, symlinks won't be followed. This
  365. resembles GNU's "cp -P src dst".
  366. If source and destination are the same file, a SameFileError will be
  367. raised.
  368. """
  369. if os.path.isdir(dst):
  370. dst = os.path.join(dst, os.path.basename(src))
  371. copyfile(src, dst, follow_symlinks=follow_symlinks)
  372. copymode(src, dst, follow_symlinks=follow_symlinks)
  373. return dst
  374. def copy2(src, dst, *, follow_symlinks=True):
  375. """Copy data and metadata. Return the file's destination.
  376. Metadata is copied with copystat(). Please see the copystat function
  377. for more information.
  378. The destination may be a directory.
  379. If follow_symlinks is false, symlinks won't be followed. This
  380. resembles GNU's "cp -P src dst".
  381. """
  382. if os.path.isdir(dst):
  383. dst = os.path.join(dst, os.path.basename(src))
  384. if hasattr(_winapi, "CopyFile2"):
  385. src_ = os.fsdecode(src)
  386. dst_ = os.fsdecode(dst)
  387. flags = _winapi.COPY_FILE_ALLOW_DECRYPTED_DESTINATION # for compat
  388. if not follow_symlinks:
  389. flags |= _winapi.COPY_FILE_COPY_SYMLINK
  390. try:
  391. _winapi.CopyFile2(src_, dst_, flags)
  392. return dst
  393. except OSError as exc:
  394. if (exc.winerror == _winapi.ERROR_PRIVILEGE_NOT_HELD
  395. and not follow_symlinks):
  396. # Likely encountered a symlink we aren't allowed to create.
  397. # Fall back on the old code
  398. pass
  399. elif exc.winerror == _winapi.ERROR_ACCESS_DENIED:
  400. # Possibly encountered a hidden or readonly file we can't
  401. # overwrite. Fall back on old code
  402. pass
  403. else:
  404. raise
  405. copyfile(src, dst, follow_symlinks=follow_symlinks)
  406. copystat(src, dst, follow_symlinks=follow_symlinks)
  407. return dst
  408. def ignore_patterns(*patterns):
  409. """Function that can be used as copytree() ignore parameter.
  410. Patterns is a sequence of glob-style patterns
  411. that are used to exclude files"""
  412. def _ignore_patterns(path, names):
  413. ignored_names = []
  414. for pattern in patterns:
  415. ignored_names.extend(fnmatch.filter(names, pattern))
  416. return set(ignored_names)
  417. return _ignore_patterns
  418. def _copytree(entries, src, dst, symlinks, ignore, copy_function,
  419. ignore_dangling_symlinks, dirs_exist_ok=False):
  420. if ignore is not None:
  421. ignored_names = ignore(os.fspath(src), [x.name for x in entries])
  422. else:
  423. ignored_names = ()
  424. os.makedirs(dst, exist_ok=dirs_exist_ok)
  425. errors = []
  426. use_srcentry = copy_function is copy2 or copy_function is copy
  427. for srcentry in entries:
  428. if srcentry.name in ignored_names:
  429. continue
  430. srcname = os.path.join(src, srcentry.name)
  431. dstname = os.path.join(dst, srcentry.name)
  432. srcobj = srcentry if use_srcentry else srcname
  433. try:
  434. is_symlink = srcentry.is_symlink()
  435. if is_symlink and os.name == 'nt':
  436. # Special check for directory junctions, which appear as
  437. # symlinks but we want to recurse.
  438. lstat = srcentry.stat(follow_symlinks=False)
  439. if lstat.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT:
  440. is_symlink = False
  441. if is_symlink:
  442. linkto = os.readlink(srcname)
  443. if symlinks:
  444. # We can't just leave it to `copy_function` because legacy
  445. # code with a custom `copy_function` may rely on copytree
  446. # doing the right thing.
  447. os.symlink(linkto, dstname)
  448. copystat(srcobj, dstname, follow_symlinks=not symlinks)
  449. else:
  450. # ignore dangling symlink if the flag is on
  451. if not os.path.exists(linkto) and ignore_dangling_symlinks:
  452. continue
  453. # otherwise let the copy occur. copy2 will raise an error
  454. if srcentry.is_dir():
  455. copytree(srcobj, dstname, symlinks, ignore,
  456. copy_function, ignore_dangling_symlinks,
  457. dirs_exist_ok)
  458. else:
  459. copy_function(srcobj, dstname)
  460. elif srcentry.is_dir():
  461. copytree(srcobj, dstname, symlinks, ignore, copy_function,
  462. ignore_dangling_symlinks, dirs_exist_ok)
  463. else:
  464. # Will raise a SpecialFileError for unsupported file types
  465. copy_function(srcobj, dstname)
  466. # catch the Error from the recursive copytree so that we can
  467. # continue with other files
  468. except Error as err:
  469. errors.extend(err.args[0])
  470. except OSError as why:
  471. errors.append((srcname, dstname, str(why)))
  472. try:
  473. copystat(src, dst)
  474. except OSError as why:
  475. # Copying file access times may fail on Windows
  476. if getattr(why, 'winerror', None) is None:
  477. errors.append((src, dst, str(why)))
  478. if errors:
  479. raise Error(errors)
  480. return dst
  481. def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
  482. ignore_dangling_symlinks=False, dirs_exist_ok=False):
  483. """Recursively copy a directory tree and return the destination directory.
  484. If exception(s) occur, an Error is raised with a list of reasons.
  485. If the optional symlinks flag is true, symbolic links in the
  486. source tree result in symbolic links in the destination tree; if
  487. it is false, the contents of the files pointed to by symbolic
  488. links are copied. If the file pointed to by the symlink doesn't
  489. exist, an exception will be added in the list of errors raised in
  490. an Error exception at the end of the copy process.
  491. You can set the optional ignore_dangling_symlinks flag to true if you
  492. want to silence this exception. Notice that this has no effect on
  493. platforms that don't support os.symlink.
  494. The optional ignore argument is a callable. If given, it
  495. is called with the `src` parameter, which is the directory
  496. being visited by copytree(), and `names` which is the list of
  497. `src` contents, as returned by os.listdir():
  498. callable(src, names) -> ignored_names
  499. Since copytree() is called recursively, the callable will be
  500. called once for each directory that is copied. It returns a
  501. list of names relative to the `src` directory that should
  502. not be copied.
  503. The optional copy_function argument is a callable that will be used
  504. to copy each file. It will be called with the source path and the
  505. destination path as arguments. By default, copy2() is used, but any
  506. function that supports the same signature (like copy()) can be used.
  507. If dirs_exist_ok is false (the default) and `dst` already exists, a
  508. `FileExistsError` is raised. If `dirs_exist_ok` is true, the copying
  509. operation will continue if it encounters existing directories, and files
  510. within the `dst` tree will be overwritten by corresponding files from the
  511. `src` tree.
  512. """
  513. sys.audit("shutil.copytree", src, dst)
  514. with os.scandir(src) as itr:
  515. entries = list(itr)
  516. return _copytree(entries=entries, src=src, dst=dst, symlinks=symlinks,
  517. ignore=ignore, copy_function=copy_function,
  518. ignore_dangling_symlinks=ignore_dangling_symlinks,
  519. dirs_exist_ok=dirs_exist_ok)
  520. if hasattr(os.stat_result, 'st_file_attributes'):
  521. def _rmtree_islink(path):
  522. try:
  523. st = os.lstat(path)
  524. return (stat.S_ISLNK(st.st_mode) or
  525. (st.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
  526. and st.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT))
  527. except OSError:
  528. return False
  529. else:
  530. def _rmtree_islink(path):
  531. return os.path.islink(path)
  532. # version vulnerable to race conditions
  533. def _rmtree_unsafe(path, onexc):
  534. def onerror(err):
  535. onexc(os.scandir, err.filename, err)
  536. results = os.walk(path, topdown=False, onerror=onerror, followlinks=os._walk_symlinks_as_files)
  537. for dirpath, dirnames, filenames in results:
  538. for name in dirnames:
  539. fullname = os.path.join(dirpath, name)
  540. try:
  541. os.rmdir(fullname)
  542. except OSError as err:
  543. onexc(os.rmdir, fullname, err)
  544. for name in filenames:
  545. fullname = os.path.join(dirpath, name)
  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(stack, onexc):
  556. # Each stack item has four elements:
  557. # * func: The first operation to perform: os.lstat, os.close or os.rmdir.
  558. # Walking a directory starts with an os.lstat() to detect symlinks; in
  559. # this case, func is updated before subsequent operations and passed to
  560. # onexc() if an error occurs.
  561. # * dirfd: Open file descriptor, or None if we're processing the top-level
  562. # directory given to rmtree() and the user didn't supply dir_fd.
  563. # * path: Path of file to operate upon. This is passed to onexc() if an
  564. # error occurs.
  565. # * orig_entry: os.DirEntry, or None if we're processing the top-level
  566. # directory given to rmtree(). We used the cached stat() of the entry to
  567. # save a call to os.lstat() when walking subdirectories.
  568. func, dirfd, path, orig_entry = stack.pop()
  569. name = path if orig_entry is None else orig_entry.name
  570. try:
  571. if func is os.close:
  572. os.close(dirfd)
  573. return
  574. if func is os.rmdir:
  575. os.rmdir(name, dir_fd=dirfd)
  576. return
  577. # Note: To guard against symlink races, we use the standard
  578. # lstat()/open()/fstat() trick.
  579. assert func is os.lstat
  580. if orig_entry is None:
  581. orig_st = os.lstat(name, dir_fd=dirfd)
  582. else:
  583. orig_st = orig_entry.stat(follow_symlinks=False)
  584. func = os.open # For error reporting.
  585. topfd = os.open(name, os.O_RDONLY | os.O_NONBLOCK, dir_fd=dirfd)
  586. func = os.path.islink # For error reporting.
  587. try:
  588. if not os.path.samestat(orig_st, os.fstat(topfd)):
  589. # Symlinks to directories are forbidden, see GH-46010.
  590. raise OSError("Cannot call rmtree on a symbolic link")
  591. stack.append((os.rmdir, dirfd, path, orig_entry))
  592. finally:
  593. stack.append((os.close, topfd, path, orig_entry))
  594. func = os.scandir # For error reporting.
  595. with os.scandir(topfd) as scandir_it:
  596. entries = list(scandir_it)
  597. for entry in entries:
  598. fullname = os.path.join(path, entry.name)
  599. try:
  600. if entry.is_dir(follow_symlinks=False):
  601. # Traverse into sub-directory.
  602. stack.append((os.lstat, topfd, fullname, entry))
  603. continue
  604. except OSError:
  605. pass
  606. try:
  607. os.unlink(entry.name, dir_fd=topfd)
  608. except OSError as err:
  609. onexc(os.unlink, fullname, err)
  610. except OSError as err:
  611. err.filename = path
  612. onexc(func, path, err)
  613. _use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <=
  614. os.supports_dir_fd and
  615. os.scandir in os.supports_fd and
  616. os.stat in os.supports_follow_symlinks)
  617. def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None):
  618. """Recursively delete a directory tree.
  619. If dir_fd is not None, it should be a file descriptor open to a directory;
  620. path will then be relative to that directory.
  621. dir_fd may not be implemented on your platform.
  622. If it is unavailable, using it will raise a NotImplementedError.
  623. If ignore_errors is set, errors are ignored; otherwise, if onexc or
  624. onerror is set, it is called to handle the error with arguments (func,
  625. path, exc_info) where func is platform and implementation dependent;
  626. path is the argument to that function that caused it to fail; and
  627. the value of exc_info describes the exception. For onexc it is the
  628. exception instance, and for onerror it is a tuple as returned by
  629. sys.exc_info(). If ignore_errors is false and both onexc and
  630. onerror are None, the exception is reraised.
  631. onerror is deprecated and only remains for backwards compatibility.
  632. If both onerror and onexc are set, onerror is ignored and onexc is used.
  633. """
  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. stack = [(os.lstat, dir_fd, path, None)]
  659. try:
  660. while stack:
  661. _rmtree_safe_fd(stack, onexc)
  662. finally:
  663. # Close any file descriptors still on the stack.
  664. while stack:
  665. func, fd, path, entry = stack.pop()
  666. if func is not os.close:
  667. continue
  668. try:
  669. os.close(fd)
  670. except OSError as err:
  671. onexc(os.close, path, err)
  672. else:
  673. if dir_fd is not None:
  674. raise NotImplementedError("dir_fd unavailable on this platform")
  675. try:
  676. if _rmtree_islink(path):
  677. # symlinks to directories are forbidden, see bug #1669
  678. raise OSError("Cannot call rmtree on a symbolic link")
  679. except OSError as err:
  680. onexc(os.path.islink, path, err)
  681. # can't continue even if onexc hook returns
  682. return
  683. return _rmtree_unsafe(path, onexc)
  684. # Allow introspection of whether or not the hardening against symlink
  685. # attacks is supported on the current platform
  686. rmtree.avoids_symlink_attacks = _use_fd_functions
  687. def _basename(path):
  688. """A basename() variant which first strips the trailing slash, if present.
  689. Thus we always get the last component of the path, even for directories.
  690. path: Union[PathLike, str]
  691. e.g.
  692. >>> os.path.basename('/bar/foo')
  693. 'foo'
  694. >>> os.path.basename('/bar/foo/')
  695. ''
  696. >>> _basename('/bar/foo/')
  697. 'foo'
  698. """
  699. path = os.fspath(path)
  700. sep = os.path.sep + (os.path.altsep or '')
  701. return os.path.basename(path.rstrip(sep))
  702. def move(src, dst, copy_function=copy2):
  703. """Recursively move a file or directory to another location. This is
  704. similar to the Unix "mv" command. Return the file or directory's
  705. destination.
  706. If dst is an existing directory or a symlink to a directory, then src is
  707. moved inside that directory. The destination path in that directory must
  708. not already exist.
  709. If dst already exists but is not a directory, it may be overwritten
  710. depending on os.rename() semantics.
  711. If the destination is on our current filesystem, then rename() is used.
  712. Otherwise, src is copied to the destination and then removed. Symlinks are
  713. recreated under the new name if os.rename() fails because of cross
  714. filesystem renames.
  715. The optional `copy_function` argument is a callable that will be used
  716. to copy the source or it will be delegated to `copytree`.
  717. By default, copy2() is used, but any function that supports the same
  718. signature (like copy()) can be used.
  719. A lot more could be done here... A look at a mv.c shows a lot of
  720. the issues this implementation glosses over.
  721. """
  722. sys.audit("shutil.move", src, dst)
  723. real_dst = dst
  724. if os.path.isdir(dst):
  725. if _samefile(src, dst) and not os.path.islink(src):
  726. # We might be on a case insensitive filesystem,
  727. # perform the rename anyway.
  728. os.rename(src, dst)
  729. return
  730. # Using _basename instead of os.path.basename is important, as we must
  731. # ignore any trailing slash to avoid the basename returning ''
  732. real_dst = os.path.join(dst, _basename(src))
  733. if os.path.exists(real_dst):
  734. raise Error("Destination path '%s' already exists" % real_dst)
  735. try:
  736. os.rename(src, real_dst)
  737. except OSError:
  738. if os.path.islink(src):
  739. linkto = os.readlink(src)
  740. os.symlink(linkto, real_dst)
  741. os.unlink(src)
  742. elif os.path.isdir(src):
  743. if _destinsrc(src, dst):
  744. raise Error("Cannot move a directory '%s' into itself"
  745. " '%s'." % (src, dst))
  746. if (_is_immutable(src)
  747. or (not os.access(src, os.W_OK) and os.listdir(src)
  748. and sys.platform == 'darwin')):
  749. raise PermissionError("Cannot move the non-empty directory "
  750. "'%s': Lacking write permission to '%s'."
  751. % (src, src))
  752. copytree(src, real_dst, copy_function=copy_function,
  753. symlinks=True)
  754. rmtree(src)
  755. else:
  756. copy_function(src, real_dst)
  757. os.unlink(src)
  758. return real_dst
  759. def _destinsrc(src, dst):
  760. src = os.path.abspath(src)
  761. dst = os.path.abspath(dst)
  762. if not src.endswith(os.path.sep):
  763. src += os.path.sep
  764. if not dst.endswith(os.path.sep):
  765. dst += os.path.sep
  766. return dst.startswith(src)
  767. def _is_immutable(src):
  768. st = _stat(src)
  769. immutable_states = [stat.UF_IMMUTABLE, stat.SF_IMMUTABLE]
  770. return hasattr(st, 'st_flags') and st.st_flags in immutable_states
  771. def _get_gid(name):
  772. """Returns a gid, given a group name."""
  773. if name is None:
  774. return None
  775. try:
  776. from grp import getgrnam
  777. except ImportError:
  778. return None
  779. try:
  780. result = getgrnam(name)
  781. except KeyError:
  782. result = None
  783. if result is not None:
  784. return result[2]
  785. return None
  786. def _get_uid(name):
  787. """Returns an uid, given a user name."""
  788. if name is None:
  789. return None
  790. try:
  791. from pwd import getpwnam
  792. except ImportError:
  793. return None
  794. try:
  795. result = getpwnam(name)
  796. except KeyError:
  797. result = None
  798. if result is not None:
  799. return result[2]
  800. return None
  801. def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
  802. owner=None, group=None, logger=None, root_dir=None):
  803. """Create a (possibly compressed) tar file from all the files under
  804. 'base_dir'.
  805. 'compress' must be "gzip" (the default), "bzip2", "xz", or None.
  806. 'owner' and 'group' can be used to define an owner and a group for the
  807. archive that is being built. If not provided, the current owner and group
  808. will be used.
  809. The output tar file will be named 'base_name' + ".tar", possibly plus
  810. the appropriate compression extension (".gz", ".bz2", or ".xz").
  811. Returns the output filename.
  812. """
  813. if compress is None:
  814. tar_compression = ''
  815. elif _ZLIB_SUPPORTED and compress == 'gzip':
  816. tar_compression = 'gz'
  817. elif _BZ2_SUPPORTED and compress == 'bzip2':
  818. tar_compression = 'bz2'
  819. elif _LZMA_SUPPORTED and compress == 'xz':
  820. tar_compression = 'xz'
  821. else:
  822. raise ValueError("bad value for 'compress', or compression format not "
  823. "supported : {0}".format(compress))
  824. import tarfile # late import for breaking circular dependency
  825. compress_ext = '.' + tar_compression if compress else ''
  826. archive_name = base_name + '.tar' + compress_ext
  827. archive_dir = os.path.dirname(archive_name)
  828. if archive_dir and not os.path.exists(archive_dir):
  829. if logger is not None:
  830. logger.info("creating %s", archive_dir)
  831. if not dry_run:
  832. os.makedirs(archive_dir)
  833. # creating the tarball
  834. if logger is not None:
  835. logger.info('Creating tar archive')
  836. uid = _get_uid(owner)
  837. gid = _get_gid(group)
  838. def _set_uid_gid(tarinfo):
  839. if gid is not None:
  840. tarinfo.gid = gid
  841. tarinfo.gname = group
  842. if uid is not None:
  843. tarinfo.uid = uid
  844. tarinfo.uname = owner
  845. return tarinfo
  846. if not dry_run:
  847. tar = tarfile.open(archive_name, 'w|%s' % tar_compression)
  848. arcname = base_dir
  849. if root_dir is not None:
  850. base_dir = os.path.join(root_dir, base_dir)
  851. try:
  852. tar.add(base_dir, arcname, filter=_set_uid_gid)
  853. finally:
  854. tar.close()
  855. if root_dir is not None:
  856. archive_name = os.path.abspath(archive_name)
  857. return archive_name
  858. def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0,
  859. logger=None, owner=None, group=None, root_dir=None):
  860. """Create a zip file from all the files under 'base_dir'.
  861. The output zip file will be named 'base_name' + ".zip". Returns the
  862. name of the output zip file.
  863. """
  864. import zipfile # late import for breaking circular dependency
  865. zip_filename = base_name + ".zip"
  866. archive_dir = os.path.dirname(base_name)
  867. if archive_dir and not os.path.exists(archive_dir):
  868. if logger is not None:
  869. logger.info("creating %s", archive_dir)
  870. if not dry_run:
  871. os.makedirs(archive_dir)
  872. if logger is not None:
  873. logger.info("creating '%s' and adding '%s' to it",
  874. zip_filename, base_dir)
  875. if not dry_run:
  876. with zipfile.ZipFile(zip_filename, "w",
  877. compression=zipfile.ZIP_DEFLATED) as zf:
  878. arcname = os.path.normpath(base_dir)
  879. if root_dir is not None:
  880. base_dir = os.path.join(root_dir, base_dir)
  881. base_dir = os.path.normpath(base_dir)
  882. if arcname != os.curdir:
  883. zf.write(base_dir, arcname)
  884. if logger is not None:
  885. logger.info("adding '%s'", base_dir)
  886. for dirpath, dirnames, filenames in os.walk(base_dir):
  887. arcdirpath = dirpath
  888. if root_dir is not None:
  889. arcdirpath = os.path.relpath(arcdirpath, root_dir)
  890. arcdirpath = os.path.normpath(arcdirpath)
  891. for name in sorted(dirnames):
  892. path = os.path.join(dirpath, name)
  893. arcname = os.path.join(arcdirpath, name)
  894. zf.write(path, arcname)
  895. if logger is not None:
  896. logger.info("adding '%s'", path)
  897. for name in filenames:
  898. path = os.path.join(dirpath, name)
  899. path = os.path.normpath(path)
  900. if os.path.isfile(path):
  901. arcname = os.path.join(arcdirpath, name)
  902. zf.write(path, arcname)
  903. if logger is not None:
  904. logger.info("adding '%s'", path)
  905. if root_dir is not None:
  906. zip_filename = os.path.abspath(zip_filename)
  907. return zip_filename
  908. _make_tarball.supports_root_dir = True
  909. _make_zipfile.supports_root_dir = True
  910. # Maps the name of the archive format to a tuple containing:
  911. # * the archiving function
  912. # * extra keyword arguments
  913. # * description
  914. _ARCHIVE_FORMATS = {
  915. 'tar': (_make_tarball, [('compress', None)],
  916. "uncompressed tar file"),
  917. }
  918. if _ZLIB_SUPPORTED:
  919. _ARCHIVE_FORMATS['gztar'] = (_make_tarball, [('compress', 'gzip')],
  920. "gzip'ed tar-file")
  921. _ARCHIVE_FORMATS['zip'] = (_make_zipfile, [], "ZIP file")
  922. if _BZ2_SUPPORTED:
  923. _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
  924. "bzip2'ed tar-file")
  925. if _LZMA_SUPPORTED:
  926. _ARCHIVE_FORMATS['xztar'] = (_make_tarball, [('compress', 'xz')],
  927. "xz'ed tar-file")
  928. def get_archive_formats():
  929. """Returns a list of supported formats for archiving and unarchiving.
  930. Each element of the returned sequence is a tuple (name, description)
  931. """
  932. formats = [(name, registry[2]) for name, registry in
  933. _ARCHIVE_FORMATS.items()]
  934. formats.sort()
  935. return formats
  936. def register_archive_format(name, function, extra_args=None, description=''):
  937. """Registers an archive format.
  938. name is the name of the format. function is the callable that will be
  939. used to create archives. If provided, extra_args is a sequence of
  940. (name, value) tuples that will be passed as arguments to the callable.
  941. description can be provided to describe the format, and will be returned
  942. by the get_archive_formats() function.
  943. """
  944. if extra_args is None:
  945. extra_args = []
  946. if not callable(function):
  947. raise TypeError('The %s object is not callable' % function)
  948. if not isinstance(extra_args, (tuple, list)):
  949. raise TypeError('extra_args needs to be a sequence')
  950. for element in extra_args:
  951. if not isinstance(element, (tuple, list)) or len(element) !=2:
  952. raise TypeError('extra_args elements are : (arg_name, value)')
  953. _ARCHIVE_FORMATS[name] = (function, extra_args, description)
  954. def unregister_archive_format(name):
  955. del _ARCHIVE_FORMATS[name]
  956. def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
  957. dry_run=0, owner=None, group=None, logger=None):
  958. """Create an archive file (eg. zip or tar).
  959. 'base_name' is the name of the file to create, minus any format-specific
  960. extension; 'format' is the archive format: one of "zip", "tar", "gztar",
  961. "bztar", or "xztar". Or any other registered format.
  962. 'root_dir' is a directory that will be the root directory of the
  963. archive; ie. we typically chdir into 'root_dir' before creating the
  964. archive. 'base_dir' is the directory where we start archiving from;
  965. ie. 'base_dir' will be the common prefix of all files and
  966. directories in the archive. 'root_dir' and 'base_dir' both default
  967. to the current directory. Returns the name of the archive file.
  968. 'owner' and 'group' are used when creating a tar archive. By default,
  969. uses the current owner and group.
  970. """
  971. sys.audit("shutil.make_archive", base_name, format, root_dir, base_dir)
  972. try:
  973. format_info = _ARCHIVE_FORMATS[format]
  974. except KeyError:
  975. raise ValueError("unknown archive format '%s'" % format) from None
  976. kwargs = {'dry_run': dry_run, 'logger': logger,
  977. 'owner': owner, 'group': group}
  978. func = format_info[0]
  979. for arg, val in format_info[1]:
  980. kwargs[arg] = val
  981. if base_dir is None:
  982. base_dir = os.curdir
  983. supports_root_dir = getattr(func, 'supports_root_dir', False)
  984. save_cwd = None
  985. if root_dir is not None:
  986. stmd = os.stat(root_dir).st_mode
  987. if not stat.S_ISDIR(stmd):
  988. raise NotADirectoryError(errno.ENOTDIR, 'Not a directory', root_dir)
  989. if supports_root_dir:
  990. # Support path-like base_name here for backwards-compatibility.
  991. base_name = os.fspath(base_name)
  992. kwargs['root_dir'] = root_dir
  993. else:
  994. save_cwd = os.getcwd()
  995. if logger is not None:
  996. logger.debug("changing into '%s'", root_dir)
  997. base_name = os.path.abspath(base_name)
  998. if not dry_run:
  999. os.chdir(root_dir)
  1000. try:
  1001. filename = func(base_name, base_dir, **kwargs)
  1002. finally:
  1003. if save_cwd is not None:
  1004. if logger is not None:
  1005. logger.debug("changing back to '%s'", save_cwd)
  1006. os.chdir(save_cwd)
  1007. return filename
  1008. def get_unpack_formats():
  1009. """Returns a list of supported formats for unpacking.
  1010. Each element of the returned sequence is a tuple
  1011. (name, extensions, description)
  1012. """
  1013. formats = [(name, info[0], info[3]) for name, info in
  1014. _UNPACK_FORMATS.items()]
  1015. formats.sort()
  1016. return formats
  1017. def _check_unpack_options(extensions, function, extra_args):
  1018. """Checks what gets registered as an unpacker."""
  1019. # first make sure no other unpacker is registered for this extension
  1020. existing_extensions = {}
  1021. for name, info in _UNPACK_FORMATS.items():
  1022. for ext in info[0]:
  1023. existing_extensions[ext] = name
  1024. for extension in extensions:
  1025. if extension in existing_extensions:
  1026. msg = '%s is already registered for "%s"'
  1027. raise RegistryError(msg % (extension,
  1028. existing_extensions[extension]))
  1029. if not callable(function):
  1030. raise TypeError('The registered function must be a callable')
  1031. def register_unpack_format(name, extensions, function, extra_args=None,
  1032. description=''):
  1033. """Registers an unpack format.
  1034. `name` is the name of the format. `extensions` is a list of extensions
  1035. corresponding to the format.
  1036. `function` is the callable that will be
  1037. used to unpack archives. The callable will receive archives to unpack.
  1038. If it's unable to handle an archive, it needs to raise a ReadError
  1039. exception.
  1040. If provided, `extra_args` is a sequence of
  1041. (name, value) tuples that will be passed as arguments to the callable.
  1042. description can be provided to describe the format, and will be returned
  1043. by the get_unpack_formats() function.
  1044. """
  1045. if extra_args is None:
  1046. extra_args = []
  1047. _check_unpack_options(extensions, function, extra_args)
  1048. _UNPACK_FORMATS[name] = extensions, function, extra_args, description
  1049. def unregister_unpack_format(name):
  1050. """Removes the pack format from the registry."""
  1051. del _UNPACK_FORMATS[name]
  1052. def _ensure_directory(path):
  1053. """Ensure that the parent directory of `path` exists"""
  1054. dirname = os.path.dirname(path)
  1055. if not os.path.isdir(dirname):
  1056. os.makedirs(dirname)
  1057. def _unpack_zipfile(filename, extract_dir):
  1058. """Unpack zip `filename` to `extract_dir`
  1059. """
  1060. import zipfile # late import for breaking circular dependency
  1061. if not zipfile.is_zipfile(filename):
  1062. raise ReadError("%s is not a zip file" % filename)
  1063. zip = zipfile.ZipFile(filename)
  1064. try:
  1065. for info in zip.infolist():
  1066. name = info.filename
  1067. # don't extract absolute paths or ones with .. in them
  1068. if name.startswith('/') or '..' in name:
  1069. continue
  1070. targetpath = os.path.join(extract_dir, *name.split('/'))
  1071. if not targetpath:
  1072. continue
  1073. _ensure_directory(targetpath)
  1074. if not name.endswith('/'):
  1075. # file
  1076. with zip.open(name, 'r') as source, \
  1077. open(targetpath, 'wb') as target:
  1078. copyfileobj(source, target)
  1079. finally:
  1080. zip.close()
  1081. def _unpack_tarfile(filename, extract_dir, *, filter=None):
  1082. """Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir`
  1083. """
  1084. import tarfile # late import for breaking circular dependency
  1085. try:
  1086. tarobj = tarfile.open(filename)
  1087. except tarfile.TarError:
  1088. raise ReadError(
  1089. "%s is not a compressed or uncompressed tar file" % filename)
  1090. try:
  1091. tarobj.extractall(extract_dir, filter=filter)
  1092. finally:
  1093. tarobj.close()
  1094. # Maps the name of the unpack format to a tuple containing:
  1095. # * extensions
  1096. # * the unpacking function
  1097. # * extra keyword arguments
  1098. # * description
  1099. _UNPACK_FORMATS = {
  1100. 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"),
  1101. 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file"),
  1102. }
  1103. if _ZLIB_SUPPORTED:
  1104. _UNPACK_FORMATS['gztar'] = (['.tar.gz', '.tgz'], _unpack_tarfile, [],
  1105. "gzip'ed tar-file")
  1106. if _BZ2_SUPPORTED:
  1107. _UNPACK_FORMATS['bztar'] = (['.tar.bz2', '.tbz2'], _unpack_tarfile, [],
  1108. "bzip2'ed tar-file")
  1109. if _LZMA_SUPPORTED:
  1110. _UNPACK_FORMATS['xztar'] = (['.tar.xz', '.txz'], _unpack_tarfile, [],
  1111. "xz'ed tar-file")
  1112. def _find_unpack_format(filename):
  1113. for name, info in _UNPACK_FORMATS.items():
  1114. for extension in info[0]:
  1115. if filename.endswith(extension):
  1116. return name
  1117. return None
  1118. def unpack_archive(filename, extract_dir=None, format=None, *, filter=None):
  1119. """Unpack an archive.
  1120. `filename` is the name of the archive.
  1121. `extract_dir` is the name of the target directory, where the archive
  1122. is unpacked. If not provided, the current working directory is used.
  1123. `format` is the archive format: one of "zip", "tar", "gztar", "bztar",
  1124. or "xztar". Or any other registered format. If not provided,
  1125. unpack_archive will use the filename extension and see if an unpacker
  1126. was registered for that extension.
  1127. In case none is found, a ValueError is raised.
  1128. If `filter` is given, it is passed to the underlying
  1129. extraction function.
  1130. """
  1131. sys.audit("shutil.unpack_archive", filename, extract_dir, format)
  1132. if extract_dir is None:
  1133. extract_dir = os.getcwd()
  1134. extract_dir = os.fspath(extract_dir)
  1135. filename = os.fspath(filename)
  1136. if filter is None:
  1137. filter_kwargs = {}
  1138. else:
  1139. filter_kwargs = {'filter': filter}
  1140. if format is not None:
  1141. try:
  1142. format_info = _UNPACK_FORMATS[format]
  1143. except KeyError:
  1144. raise ValueError("Unknown unpack format '{0}'".format(format)) from None
  1145. func = format_info[1]
  1146. func(filename, extract_dir, **dict(format_info[2]), **filter_kwargs)
  1147. else:
  1148. # we need to look at the registered unpackers supported extensions
  1149. format = _find_unpack_format(filename)
  1150. if format is None:
  1151. raise ReadError("Unknown archive format '{0}'".format(filename))
  1152. func = _UNPACK_FORMATS[format][1]
  1153. kwargs = dict(_UNPACK_FORMATS[format][2]) | filter_kwargs
  1154. func(filename, extract_dir, **kwargs)
  1155. if hasattr(os, 'statvfs'):
  1156. __all__.append('disk_usage')
  1157. _ntuple_diskusage = collections.namedtuple('usage', 'total used free')
  1158. _ntuple_diskusage.total.__doc__ = 'Total space in bytes'
  1159. _ntuple_diskusage.used.__doc__ = 'Used space in bytes'
  1160. _ntuple_diskusage.free.__doc__ = 'Free space in bytes'
  1161. def disk_usage(path):
  1162. """Return disk usage statistics about the given path.
  1163. Returned value is a named tuple with attributes 'total', 'used' and
  1164. 'free', which are the amount of total, used and free space, in bytes.
  1165. """
  1166. st = os.statvfs(path)
  1167. free = st.f_bavail * st.f_frsize
  1168. total = st.f_blocks * st.f_frsize
  1169. used = (st.f_blocks - st.f_bfree) * st.f_frsize
  1170. return _ntuple_diskusage(total, used, free)
  1171. elif _WINDOWS:
  1172. __all__.append('disk_usage')
  1173. _ntuple_diskusage = collections.namedtuple('usage', 'total used free')
  1174. def disk_usage(path):
  1175. """Return disk usage statistics about the given path.
  1176. Returned values is a named tuple with attributes 'total', 'used' and
  1177. 'free', which are the amount of total, used and free space, in bytes.
  1178. """
  1179. total, free = nt._getdiskusage(path)
  1180. used = total - free
  1181. return _ntuple_diskusage(total, used, free)
  1182. def chown(path, user=None, group=None):
  1183. """Change owner user and group of the given path.
  1184. user and group can be the uid/gid or the user/group names, and in that case,
  1185. they are converted to their respective uid/gid.
  1186. """
  1187. sys.audit('shutil.chown', path, user, group)
  1188. if user is None and group is None:
  1189. raise ValueError("user and/or group must be set")
  1190. _user = user
  1191. _group = group
  1192. # -1 means don't change it
  1193. if user is None:
  1194. _user = -1
  1195. # user can either be an int (the uid) or a string (the system username)
  1196. elif isinstance(user, str):
  1197. _user = _get_uid(user)
  1198. if _user is None:
  1199. raise LookupError("no such user: {!r}".format(user))
  1200. if group is None:
  1201. _group = -1
  1202. elif not isinstance(group, int):
  1203. _group = _get_gid(group)
  1204. if _group is None:
  1205. raise LookupError("no such group: {!r}".format(group))
  1206. os.chown(path, _user, _group)
  1207. def get_terminal_size(fallback=(80, 24)):
  1208. """Get the size of the terminal window.
  1209. For each of the two dimensions, the environment variable, COLUMNS
  1210. and LINES respectively, is checked. If the variable is defined and
  1211. the value is a positive integer, it is used.
  1212. When COLUMNS or LINES is not defined, which is the common case,
  1213. the terminal connected to sys.__stdout__ is queried
  1214. by invoking os.get_terminal_size.
  1215. If the terminal size cannot be successfully queried, either because
  1216. the system doesn't support querying, or because we are not
  1217. connected to a terminal, the value given in fallback parameter
  1218. is used. Fallback defaults to (80, 24) which is the default
  1219. size used by many terminal emulators.
  1220. The value returned is a named tuple of type os.terminal_size.
  1221. """
  1222. # columns, lines are the working values
  1223. try:
  1224. columns = int(os.environ['COLUMNS'])
  1225. except (KeyError, ValueError):
  1226. columns = 0
  1227. try:
  1228. lines = int(os.environ['LINES'])
  1229. except (KeyError, ValueError):
  1230. lines = 0
  1231. # only query if necessary
  1232. if columns <= 0 or lines <= 0:
  1233. try:
  1234. size = os.get_terminal_size(sys.__stdout__.fileno())
  1235. except (AttributeError, ValueError, OSError):
  1236. # stdout is None, closed, detached, or not a terminal, or
  1237. # os.get_terminal_size() is unsupported
  1238. size = os.terminal_size(fallback)
  1239. if columns <= 0:
  1240. columns = size.columns or fallback[0]
  1241. if lines <= 0:
  1242. lines = size.lines or fallback[1]
  1243. return os.terminal_size((columns, lines))
  1244. # Check that a given file can be accessed with the correct mode.
  1245. # Additionally check that `file` is not a directory, as on Windows
  1246. # directories pass the os.access check.
  1247. def _access_check(fn, mode):
  1248. return (os.path.exists(fn) and os.access(fn, mode)
  1249. and not os.path.isdir(fn))
  1250. def _win_path_needs_curdir(cmd, mode):
  1251. """
  1252. On Windows, we can use NeedCurrentDirectoryForExePath to figure out
  1253. if we should add the cwd to PATH when searching for executables if
  1254. the mode is executable.
  1255. """
  1256. return (not (mode & os.X_OK)) or _winapi.NeedCurrentDirectoryForExePath(
  1257. os.fsdecode(cmd))
  1258. def which(cmd, mode=os.F_OK | os.X_OK, path=None):
  1259. """Given a command, mode, and a PATH string, return the path which
  1260. conforms to the given mode on the PATH, or None if there is no such
  1261. file.
  1262. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  1263. of os.environ.get("PATH"), or can be overridden with a custom search
  1264. path.
  1265. """
  1266. use_bytes = isinstance(cmd, bytes)
  1267. # If we're given a path with a directory part, look it up directly rather
  1268. # than referring to PATH directories. This includes checking relative to
  1269. # the current directory, e.g. ./script
  1270. dirname, cmd = os.path.split(cmd)
  1271. if dirname:
  1272. path = [dirname]
  1273. else:
  1274. if path is None:
  1275. path = os.environ.get("PATH", None)
  1276. if path is None:
  1277. try:
  1278. path = os.confstr("CS_PATH")
  1279. except (AttributeError, ValueError):
  1280. # os.confstr() or CS_PATH is not available
  1281. path = os.defpath
  1282. # bpo-35755: Don't use os.defpath if the PATH environment variable
  1283. # is set to an empty string
  1284. # PATH='' doesn't match, whereas PATH=':' looks in the current
  1285. # directory
  1286. if not path:
  1287. return None
  1288. if use_bytes:
  1289. path = os.fsencode(path)
  1290. path = path.split(os.fsencode(os.pathsep))
  1291. else:
  1292. path = os.fsdecode(path)
  1293. path = path.split(os.pathsep)
  1294. if sys.platform == "win32" and _win_path_needs_curdir(cmd, mode):
  1295. curdir = os.curdir
  1296. if use_bytes:
  1297. curdir = os.fsencode(curdir)
  1298. path.insert(0, curdir)
  1299. if sys.platform == "win32":
  1300. # PATHEXT is necessary to check on Windows.
  1301. pathext_source = os.getenv("PATHEXT") or _WIN_DEFAULT_PATHEXT
  1302. pathext = [ext for ext in pathext_source.split(os.pathsep) if ext]
  1303. if use_bytes:
  1304. pathext = [os.fsencode(ext) for ext in pathext]
  1305. files = ([cmd] + [cmd + ext for ext in pathext])
  1306. # gh-109590. If we are looking for an executable, we need to look
  1307. # for a PATHEXT match. The first cmd is the direct match
  1308. # (e.g. python.exe instead of python)
  1309. # Check that direct match first if and only if the extension is in PATHEXT
  1310. # Otherwise check it last
  1311. suffix = os.path.splitext(files[0])[1].upper()
  1312. if mode & os.X_OK and not any(suffix == ext.upper() for ext in pathext):
  1313. files.append(files.pop(0))
  1314. else:
  1315. # On other platforms you don't have things like PATHEXT to tell you
  1316. # what file suffixes are executable, so just pass on cmd as-is.
  1317. files = [cmd]
  1318. seen = set()
  1319. for dir in path:
  1320. normdir = os.path.normcase(dir)
  1321. if not normdir in seen:
  1322. seen.add(normdir)
  1323. for thefile in files:
  1324. name = os.path.join(dir, thefile)
  1325. if _access_check(name, mode):
  1326. return name
  1327. return None