shutil.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  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 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. try:
  535. with os.scandir(path) as scandir_it:
  536. entries = list(scandir_it)
  537. except OSError as err:
  538. onexc(os.scandir, path, err)
  539. entries = []
  540. for entry in entries:
  541. fullname = entry.path
  542. try:
  543. is_dir = entry.is_dir(follow_symlinks=False)
  544. except OSError:
  545. is_dir = False
  546. if is_dir and not entry.is_junction():
  547. try:
  548. if entry.is_symlink():
  549. # This can only happen if someone replaces
  550. # a directory with a symlink after the call to
  551. # os.scandir or entry.is_dir above.
  552. raise OSError("Cannot call rmtree on a symbolic link")
  553. except OSError as err:
  554. onexc(os.path.islink, fullname, err)
  555. continue
  556. _rmtree_unsafe(fullname, onexc)
  557. else:
  558. try:
  559. os.unlink(fullname)
  560. except OSError as err:
  561. onexc(os.unlink, fullname, err)
  562. try:
  563. os.rmdir(path)
  564. except OSError as err:
  565. onexc(os.rmdir, path, err)
  566. # Version using fd-based APIs to protect against races
  567. def _rmtree_safe_fd(topfd, path, onexc):
  568. try:
  569. with os.scandir(topfd) as scandir_it:
  570. entries = list(scandir_it)
  571. except OSError as err:
  572. err.filename = path
  573. onexc(os.scandir, path, err)
  574. return
  575. for entry in entries:
  576. fullname = os.path.join(path, entry.name)
  577. try:
  578. is_dir = entry.is_dir(follow_symlinks=False)
  579. except OSError:
  580. is_dir = False
  581. else:
  582. if is_dir:
  583. try:
  584. orig_st = entry.stat(follow_symlinks=False)
  585. is_dir = stat.S_ISDIR(orig_st.st_mode)
  586. except OSError as err:
  587. onexc(os.lstat, fullname, err)
  588. continue
  589. if is_dir:
  590. try:
  591. dirfd = os.open(entry.name, os.O_RDONLY, dir_fd=topfd)
  592. dirfd_closed = False
  593. except OSError as err:
  594. onexc(os.open, fullname, err)
  595. else:
  596. try:
  597. if os.path.samestat(orig_st, os.fstat(dirfd)):
  598. _rmtree_safe_fd(dirfd, fullname, onexc)
  599. try:
  600. os.close(dirfd)
  601. except OSError as err:
  602. # close() should not be retried after an error.
  603. dirfd_closed = True
  604. onexc(os.close, fullname, err)
  605. dirfd_closed = True
  606. try:
  607. os.rmdir(entry.name, dir_fd=topfd)
  608. except OSError as err:
  609. onexc(os.rmdir, fullname, err)
  610. else:
  611. try:
  612. # This can only happen if someone replaces
  613. # a directory with a symlink after the call to
  614. # os.scandir or stat.S_ISDIR above.
  615. raise OSError("Cannot call rmtree on a symbolic "
  616. "link")
  617. except OSError as err:
  618. onexc(os.path.islink, fullname, err)
  619. finally:
  620. if not dirfd_closed:
  621. try:
  622. os.close(dirfd)
  623. except OSError as err:
  624. onexc(os.close, fullname, err)
  625. else:
  626. try:
  627. os.unlink(entry.name, dir_fd=topfd)
  628. except OSError as err:
  629. onexc(os.unlink, fullname, err)
  630. _use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <=
  631. os.supports_dir_fd and
  632. os.scandir in os.supports_fd and
  633. os.stat in os.supports_follow_symlinks)
  634. def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None):
  635. """Recursively delete a directory tree.
  636. If dir_fd is not None, it should be a file descriptor open to a directory;
  637. path will then be relative to that directory.
  638. dir_fd may not be implemented on your platform.
  639. If it is unavailable, using it will raise a NotImplementedError.
  640. If ignore_errors is set, errors are ignored; otherwise, if onexc or
  641. onerror is set, it is called to handle the error with arguments (func,
  642. path, exc_info) where func is platform and implementation dependent;
  643. path is the argument to that function that caused it to fail; and
  644. the value of exc_info describes the exception. For onexc it is the
  645. exception instance, and for onerror it is a tuple as returned by
  646. sys.exc_info(). If ignore_errors is false and both onexc and
  647. onerror are None, the exception is reraised.
  648. onerror is deprecated and only remains for backwards compatibility.
  649. If both onerror and onexc are set, onerror is ignored and onexc is used.
  650. """
  651. sys.audit("shutil.rmtree", path, dir_fd)
  652. if ignore_errors:
  653. def onexc(*args):
  654. pass
  655. elif onerror is None and onexc is None:
  656. def onexc(*args):
  657. raise
  658. elif onexc is None:
  659. if onerror is None:
  660. def onexc(*args):
  661. raise
  662. else:
  663. # delegate to onerror
  664. def onexc(*args):
  665. func, path, exc = args
  666. if exc is None:
  667. exc_info = None, None, None
  668. else:
  669. exc_info = type(exc), exc, exc.__traceback__
  670. return onerror(func, path, exc_info)
  671. if _use_fd_functions:
  672. # While the unsafe rmtree works fine on bytes, the fd based does not.
  673. if isinstance(path, bytes):
  674. path = os.fsdecode(path)
  675. # Note: To guard against symlink races, we use the standard
  676. # lstat()/open()/fstat() trick.
  677. try:
  678. orig_st = os.lstat(path, dir_fd=dir_fd)
  679. except Exception as err:
  680. onexc(os.lstat, path, err)
  681. return
  682. try:
  683. fd = os.open(path, os.O_RDONLY, dir_fd=dir_fd)
  684. fd_closed = False
  685. except Exception as err:
  686. onexc(os.open, path, err)
  687. return
  688. try:
  689. if os.path.samestat(orig_st, os.fstat(fd)):
  690. _rmtree_safe_fd(fd, path, onexc)
  691. try:
  692. os.close(fd)
  693. except OSError as err:
  694. # close() should not be retried after an error.
  695. fd_closed = True
  696. onexc(os.close, path, err)
  697. fd_closed = True
  698. try:
  699. os.rmdir(path, dir_fd=dir_fd)
  700. except OSError as err:
  701. onexc(os.rmdir, path, err)
  702. else:
  703. try:
  704. # symlinks to directories are forbidden, see bug #1669
  705. raise OSError("Cannot call rmtree on a symbolic link")
  706. except OSError as err:
  707. onexc(os.path.islink, path, err)
  708. finally:
  709. if not fd_closed:
  710. try:
  711. os.close(fd)
  712. except OSError as err:
  713. onexc(os.close, path, err)
  714. else:
  715. if dir_fd is not None:
  716. raise NotImplementedError("dir_fd unavailable on this platform")
  717. try:
  718. if _rmtree_islink(path):
  719. # symlinks to directories are forbidden, see bug #1669
  720. raise OSError("Cannot call rmtree on a symbolic link")
  721. except OSError as err:
  722. onexc(os.path.islink, path, err)
  723. # can't continue even if onexc hook returns
  724. return
  725. return _rmtree_unsafe(path, onexc)
  726. # Allow introspection of whether or not the hardening against symlink
  727. # attacks is supported on the current platform
  728. rmtree.avoids_symlink_attacks = _use_fd_functions
  729. def _basename(path):
  730. """A basename() variant which first strips the trailing slash, if present.
  731. Thus we always get the last component of the path, even for directories.
  732. path: Union[PathLike, str]
  733. e.g.
  734. >>> os.path.basename('/bar/foo')
  735. 'foo'
  736. >>> os.path.basename('/bar/foo/')
  737. ''
  738. >>> _basename('/bar/foo/')
  739. 'foo'
  740. """
  741. path = os.fspath(path)
  742. sep = os.path.sep + (os.path.altsep or '')
  743. return os.path.basename(path.rstrip(sep))
  744. def move(src, dst, copy_function=copy2):
  745. """Recursively move a file or directory to another location. This is
  746. similar to the Unix "mv" command. Return the file or directory's
  747. destination.
  748. If dst is an existing directory or a symlink to a directory, then src is
  749. moved inside that directory. The destination path in that directory must
  750. not already exist.
  751. If dst already exists but is not a directory, it may be overwritten
  752. depending on os.rename() semantics.
  753. If the destination is on our current filesystem, then rename() is used.
  754. Otherwise, src is copied to the destination and then removed. Symlinks are
  755. recreated under the new name if os.rename() fails because of cross
  756. filesystem renames.
  757. The optional `copy_function` argument is a callable that will be used
  758. to copy the source or it will be delegated to `copytree`.
  759. By default, copy2() is used, but any function that supports the same
  760. signature (like copy()) can be used.
  761. A lot more could be done here... A look at a mv.c shows a lot of
  762. the issues this implementation glosses over.
  763. """
  764. sys.audit("shutil.move", src, dst)
  765. real_dst = dst
  766. if os.path.isdir(dst):
  767. if _samefile(src, dst) and not os.path.islink(src):
  768. # We might be on a case insensitive filesystem,
  769. # perform the rename anyway.
  770. os.rename(src, dst)
  771. return
  772. # Using _basename instead of os.path.basename is important, as we must
  773. # ignore any trailing slash to avoid the basename returning ''
  774. real_dst = os.path.join(dst, _basename(src))
  775. if os.path.exists(real_dst):
  776. raise Error("Destination path '%s' already exists" % real_dst)
  777. try:
  778. os.rename(src, real_dst)
  779. except OSError:
  780. if os.path.islink(src):
  781. linkto = os.readlink(src)
  782. os.symlink(linkto, real_dst)
  783. os.unlink(src)
  784. elif os.path.isdir(src):
  785. if _destinsrc(src, dst):
  786. raise Error("Cannot move a directory '%s' into itself"
  787. " '%s'." % (src, dst))
  788. if (_is_immutable(src)
  789. or (not os.access(src, os.W_OK) and os.listdir(src)
  790. and sys.platform == 'darwin')):
  791. raise PermissionError("Cannot move the non-empty directory "
  792. "'%s': Lacking write permission to '%s'."
  793. % (src, src))
  794. copytree(src, real_dst, copy_function=copy_function,
  795. symlinks=True)
  796. rmtree(src)
  797. else:
  798. copy_function(src, real_dst)
  799. os.unlink(src)
  800. return real_dst
  801. def _destinsrc(src, dst):
  802. src = os.path.abspath(src)
  803. dst = os.path.abspath(dst)
  804. if not src.endswith(os.path.sep):
  805. src += os.path.sep
  806. if not dst.endswith(os.path.sep):
  807. dst += os.path.sep
  808. return dst.startswith(src)
  809. def _is_immutable(src):
  810. st = _stat(src)
  811. immutable_states = [stat.UF_IMMUTABLE, stat.SF_IMMUTABLE]
  812. return hasattr(st, 'st_flags') and st.st_flags in immutable_states
  813. def _get_gid(name):
  814. """Returns a gid, given a group name."""
  815. if name is None:
  816. return None
  817. try:
  818. from grp import getgrnam
  819. except ImportError:
  820. return None
  821. try:
  822. result = getgrnam(name)
  823. except KeyError:
  824. result = None
  825. if result is not None:
  826. return result[2]
  827. return None
  828. def _get_uid(name):
  829. """Returns an uid, given a user name."""
  830. if name is None:
  831. return None
  832. try:
  833. from pwd import getpwnam
  834. except ImportError:
  835. return None
  836. try:
  837. result = getpwnam(name)
  838. except KeyError:
  839. result = None
  840. if result is not None:
  841. return result[2]
  842. return None
  843. def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
  844. owner=None, group=None, logger=None, root_dir=None):
  845. """Create a (possibly compressed) tar file from all the files under
  846. 'base_dir'.
  847. 'compress' must be "gzip" (the default), "bzip2", "xz", or None.
  848. 'owner' and 'group' can be used to define an owner and a group for the
  849. archive that is being built. If not provided, the current owner and group
  850. will be used.
  851. The output tar file will be named 'base_name' + ".tar", possibly plus
  852. the appropriate compression extension (".gz", ".bz2", or ".xz").
  853. Returns the output filename.
  854. """
  855. if compress is None:
  856. tar_compression = ''
  857. elif _ZLIB_SUPPORTED and compress == 'gzip':
  858. tar_compression = 'gz'
  859. elif _BZ2_SUPPORTED and compress == 'bzip2':
  860. tar_compression = 'bz2'
  861. elif _LZMA_SUPPORTED and compress == 'xz':
  862. tar_compression = 'xz'
  863. else:
  864. raise ValueError("bad value for 'compress', or compression format not "
  865. "supported : {0}".format(compress))
  866. import tarfile # late import for breaking circular dependency
  867. compress_ext = '.' + tar_compression if compress else ''
  868. archive_name = base_name + '.tar' + compress_ext
  869. archive_dir = os.path.dirname(archive_name)
  870. if archive_dir and not os.path.exists(archive_dir):
  871. if logger is not None:
  872. logger.info("creating %s", archive_dir)
  873. if not dry_run:
  874. os.makedirs(archive_dir)
  875. # creating the tarball
  876. if logger is not None:
  877. logger.info('Creating tar archive')
  878. uid = _get_uid(owner)
  879. gid = _get_gid(group)
  880. def _set_uid_gid(tarinfo):
  881. if gid is not None:
  882. tarinfo.gid = gid
  883. tarinfo.gname = group
  884. if uid is not None:
  885. tarinfo.uid = uid
  886. tarinfo.uname = owner
  887. return tarinfo
  888. if not dry_run:
  889. tar = tarfile.open(archive_name, 'w|%s' % tar_compression)
  890. arcname = base_dir
  891. if root_dir is not None:
  892. base_dir = os.path.join(root_dir, base_dir)
  893. try:
  894. tar.add(base_dir, arcname, filter=_set_uid_gid)
  895. finally:
  896. tar.close()
  897. if root_dir is not None:
  898. archive_name = os.path.abspath(archive_name)
  899. return archive_name
  900. def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0,
  901. logger=None, owner=None, group=None, root_dir=None):
  902. """Create a zip file from all the files under 'base_dir'.
  903. The output zip file will be named 'base_name' + ".zip". Returns the
  904. name of the output zip file.
  905. """
  906. import zipfile # late import for breaking circular dependency
  907. zip_filename = base_name + ".zip"
  908. archive_dir = os.path.dirname(base_name)
  909. if archive_dir and not os.path.exists(archive_dir):
  910. if logger is not None:
  911. logger.info("creating %s", archive_dir)
  912. if not dry_run:
  913. os.makedirs(archive_dir)
  914. if logger is not None:
  915. logger.info("creating '%s' and adding '%s' to it",
  916. zip_filename, base_dir)
  917. if not dry_run:
  918. with zipfile.ZipFile(zip_filename, "w",
  919. compression=zipfile.ZIP_DEFLATED) as zf:
  920. arcname = os.path.normpath(base_dir)
  921. if root_dir is not None:
  922. base_dir = os.path.join(root_dir, base_dir)
  923. base_dir = os.path.normpath(base_dir)
  924. if arcname != os.curdir:
  925. zf.write(base_dir, arcname)
  926. if logger is not None:
  927. logger.info("adding '%s'", base_dir)
  928. for dirpath, dirnames, filenames in os.walk(base_dir):
  929. arcdirpath = dirpath
  930. if root_dir is not None:
  931. arcdirpath = os.path.relpath(arcdirpath, root_dir)
  932. arcdirpath = os.path.normpath(arcdirpath)
  933. for name in sorted(dirnames):
  934. path = os.path.join(dirpath, name)
  935. arcname = os.path.join(arcdirpath, name)
  936. zf.write(path, arcname)
  937. if logger is not None:
  938. logger.info("adding '%s'", path)
  939. for name in filenames:
  940. path = os.path.join(dirpath, name)
  941. path = os.path.normpath(path)
  942. if os.path.isfile(path):
  943. arcname = os.path.join(arcdirpath, name)
  944. zf.write(path, arcname)
  945. if logger is not None:
  946. logger.info("adding '%s'", path)
  947. if root_dir is not None:
  948. zip_filename = os.path.abspath(zip_filename)
  949. return zip_filename
  950. _make_tarball.supports_root_dir = True
  951. _make_zipfile.supports_root_dir = True
  952. # Maps the name of the archive format to a tuple containing:
  953. # * the archiving function
  954. # * extra keyword arguments
  955. # * description
  956. _ARCHIVE_FORMATS = {
  957. 'tar': (_make_tarball, [('compress', None)],
  958. "uncompressed tar file"),
  959. }
  960. if _ZLIB_SUPPORTED:
  961. _ARCHIVE_FORMATS['gztar'] = (_make_tarball, [('compress', 'gzip')],
  962. "gzip'ed tar-file")
  963. _ARCHIVE_FORMATS['zip'] = (_make_zipfile, [], "ZIP file")
  964. if _BZ2_SUPPORTED:
  965. _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
  966. "bzip2'ed tar-file")
  967. if _LZMA_SUPPORTED:
  968. _ARCHIVE_FORMATS['xztar'] = (_make_tarball, [('compress', 'xz')],
  969. "xz'ed tar-file")
  970. def get_archive_formats():
  971. """Returns a list of supported formats for archiving and unarchiving.
  972. Each element of the returned sequence is a tuple (name, description)
  973. """
  974. formats = [(name, registry[2]) for name, registry in
  975. _ARCHIVE_FORMATS.items()]
  976. formats.sort()
  977. return formats
  978. def register_archive_format(name, function, extra_args=None, description=''):
  979. """Registers an archive format.
  980. name is the name of the format. function is the callable that will be
  981. used to create archives. If provided, extra_args is a sequence of
  982. (name, value) tuples that will be passed as arguments to the callable.
  983. description can be provided to describe the format, and will be returned
  984. by the get_archive_formats() function.
  985. """
  986. if extra_args is None:
  987. extra_args = []
  988. if not callable(function):
  989. raise TypeError('The %s object is not callable' % function)
  990. if not isinstance(extra_args, (tuple, list)):
  991. raise TypeError('extra_args needs to be a sequence')
  992. for element in extra_args:
  993. if not isinstance(element, (tuple, list)) or len(element) !=2:
  994. raise TypeError('extra_args elements are : (arg_name, value)')
  995. _ARCHIVE_FORMATS[name] = (function, extra_args, description)
  996. def unregister_archive_format(name):
  997. del _ARCHIVE_FORMATS[name]
  998. def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
  999. dry_run=0, owner=None, group=None, logger=None):
  1000. """Create an archive file (eg. zip or tar).
  1001. 'base_name' is the name of the file to create, minus any format-specific
  1002. extension; 'format' is the archive format: one of "zip", "tar", "gztar",
  1003. "bztar", or "xztar". Or any other registered format.
  1004. 'root_dir' is a directory that will be the root directory of the
  1005. archive; ie. we typically chdir into 'root_dir' before creating the
  1006. archive. 'base_dir' is the directory where we start archiving from;
  1007. ie. 'base_dir' will be the common prefix of all files and
  1008. directories in the archive. 'root_dir' and 'base_dir' both default
  1009. to the current directory. Returns the name of the archive file.
  1010. 'owner' and 'group' are used when creating a tar archive. By default,
  1011. uses the current owner and group.
  1012. """
  1013. sys.audit("shutil.make_archive", base_name, format, root_dir, base_dir)
  1014. try:
  1015. format_info = _ARCHIVE_FORMATS[format]
  1016. except KeyError:
  1017. raise ValueError("unknown archive format '%s'" % format) from None
  1018. kwargs = {'dry_run': dry_run, 'logger': logger,
  1019. 'owner': owner, 'group': group}
  1020. func = format_info[0]
  1021. for arg, val in format_info[1]:
  1022. kwargs[arg] = val
  1023. if base_dir is None:
  1024. base_dir = os.curdir
  1025. supports_root_dir = getattr(func, 'supports_root_dir', False)
  1026. save_cwd = None
  1027. if root_dir is not None:
  1028. stmd = os.stat(root_dir).st_mode
  1029. if not stat.S_ISDIR(stmd):
  1030. raise NotADirectoryError(errno.ENOTDIR, 'Not a directory', root_dir)
  1031. if supports_root_dir:
  1032. # Support path-like base_name here for backwards-compatibility.
  1033. base_name = os.fspath(base_name)
  1034. kwargs['root_dir'] = root_dir
  1035. else:
  1036. save_cwd = os.getcwd()
  1037. if logger is not None:
  1038. logger.debug("changing into '%s'", root_dir)
  1039. base_name = os.path.abspath(base_name)
  1040. if not dry_run:
  1041. os.chdir(root_dir)
  1042. try:
  1043. filename = func(base_name, base_dir, **kwargs)
  1044. finally:
  1045. if save_cwd is not None:
  1046. if logger is not None:
  1047. logger.debug("changing back to '%s'", save_cwd)
  1048. os.chdir(save_cwd)
  1049. return filename
  1050. def get_unpack_formats():
  1051. """Returns a list of supported formats for unpacking.
  1052. Each element of the returned sequence is a tuple
  1053. (name, extensions, description)
  1054. """
  1055. formats = [(name, info[0], info[3]) for name, info in
  1056. _UNPACK_FORMATS.items()]
  1057. formats.sort()
  1058. return formats
  1059. def _check_unpack_options(extensions, function, extra_args):
  1060. """Checks what gets registered as an unpacker."""
  1061. # first make sure no other unpacker is registered for this extension
  1062. existing_extensions = {}
  1063. for name, info in _UNPACK_FORMATS.items():
  1064. for ext in info[0]:
  1065. existing_extensions[ext] = name
  1066. for extension in extensions:
  1067. if extension in existing_extensions:
  1068. msg = '%s is already registered for "%s"'
  1069. raise RegistryError(msg % (extension,
  1070. existing_extensions[extension]))
  1071. if not callable(function):
  1072. raise TypeError('The registered function must be a callable')
  1073. def register_unpack_format(name, extensions, function, extra_args=None,
  1074. description=''):
  1075. """Registers an unpack format.
  1076. `name` is the name of the format. `extensions` is a list of extensions
  1077. corresponding to the format.
  1078. `function` is the callable that will be
  1079. used to unpack archives. The callable will receive archives to unpack.
  1080. If it's unable to handle an archive, it needs to raise a ReadError
  1081. exception.
  1082. If provided, `extra_args` is a sequence of
  1083. (name, value) tuples that will be passed as arguments to the callable.
  1084. description can be provided to describe the format, and will be returned
  1085. by the get_unpack_formats() function.
  1086. """
  1087. if extra_args is None:
  1088. extra_args = []
  1089. _check_unpack_options(extensions, function, extra_args)
  1090. _UNPACK_FORMATS[name] = extensions, function, extra_args, description
  1091. def unregister_unpack_format(name):
  1092. """Removes the pack format from the registry."""
  1093. del _UNPACK_FORMATS[name]
  1094. def _ensure_directory(path):
  1095. """Ensure that the parent directory of `path` exists"""
  1096. dirname = os.path.dirname(path)
  1097. if not os.path.isdir(dirname):
  1098. os.makedirs(dirname)
  1099. def _unpack_zipfile(filename, extract_dir):
  1100. """Unpack zip `filename` to `extract_dir`
  1101. """
  1102. import zipfile # late import for breaking circular dependency
  1103. if not zipfile.is_zipfile(filename):
  1104. raise ReadError("%s is not a zip file" % filename)
  1105. zip = zipfile.ZipFile(filename)
  1106. try:
  1107. for info in zip.infolist():
  1108. name = info.filename
  1109. # don't extract absolute paths or ones with .. in them
  1110. if name.startswith('/') or '..' in name:
  1111. continue
  1112. targetpath = os.path.join(extract_dir, *name.split('/'))
  1113. if not targetpath:
  1114. continue
  1115. _ensure_directory(targetpath)
  1116. if not name.endswith('/'):
  1117. # file
  1118. with zip.open(name, 'r') as source, \
  1119. open(targetpath, 'wb') as target:
  1120. copyfileobj(source, target)
  1121. finally:
  1122. zip.close()
  1123. def _unpack_tarfile(filename, extract_dir, *, filter=None):
  1124. """Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir`
  1125. """
  1126. import tarfile # late import for breaking circular dependency
  1127. try:
  1128. tarobj = tarfile.open(filename)
  1129. except tarfile.TarError:
  1130. raise ReadError(
  1131. "%s is not a compressed or uncompressed tar file" % filename)
  1132. try:
  1133. tarobj.extractall(extract_dir, filter=filter)
  1134. finally:
  1135. tarobj.close()
  1136. # Maps the name of the unpack format to a tuple containing:
  1137. # * extensions
  1138. # * the unpacking function
  1139. # * extra keyword arguments
  1140. # * description
  1141. _UNPACK_FORMATS = {
  1142. 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"),
  1143. 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file"),
  1144. }
  1145. if _ZLIB_SUPPORTED:
  1146. _UNPACK_FORMATS['gztar'] = (['.tar.gz', '.tgz'], _unpack_tarfile, [],
  1147. "gzip'ed tar-file")
  1148. if _BZ2_SUPPORTED:
  1149. _UNPACK_FORMATS['bztar'] = (['.tar.bz2', '.tbz2'], _unpack_tarfile, [],
  1150. "bzip2'ed tar-file")
  1151. if _LZMA_SUPPORTED:
  1152. _UNPACK_FORMATS['xztar'] = (['.tar.xz', '.txz'], _unpack_tarfile, [],
  1153. "xz'ed tar-file")
  1154. def _find_unpack_format(filename):
  1155. for name, info in _UNPACK_FORMATS.items():
  1156. for extension in info[0]:
  1157. if filename.endswith(extension):
  1158. return name
  1159. return None
  1160. def unpack_archive(filename, extract_dir=None, format=None, *, filter=None):
  1161. """Unpack an archive.
  1162. `filename` is the name of the archive.
  1163. `extract_dir` is the name of the target directory, where the archive
  1164. is unpacked. If not provided, the current working directory is used.
  1165. `format` is the archive format: one of "zip", "tar", "gztar", "bztar",
  1166. or "xztar". Or any other registered format. If not provided,
  1167. unpack_archive will use the filename extension and see if an unpacker
  1168. was registered for that extension.
  1169. In case none is found, a ValueError is raised.
  1170. If `filter` is given, it is passed to the underlying
  1171. extraction function.
  1172. """
  1173. sys.audit("shutil.unpack_archive", filename, extract_dir, format)
  1174. if extract_dir is None:
  1175. extract_dir = os.getcwd()
  1176. extract_dir = os.fspath(extract_dir)
  1177. filename = os.fspath(filename)
  1178. if filter is None:
  1179. filter_kwargs = {}
  1180. else:
  1181. filter_kwargs = {'filter': filter}
  1182. if format is not None:
  1183. try:
  1184. format_info = _UNPACK_FORMATS[format]
  1185. except KeyError:
  1186. raise ValueError("Unknown unpack format '{0}'".format(format)) from None
  1187. func = format_info[1]
  1188. func(filename, extract_dir, **dict(format_info[2]), **filter_kwargs)
  1189. else:
  1190. # we need to look at the registered unpackers supported extensions
  1191. format = _find_unpack_format(filename)
  1192. if format is None:
  1193. raise ReadError("Unknown archive format '{0}'".format(filename))
  1194. func = _UNPACK_FORMATS[format][1]
  1195. kwargs = dict(_UNPACK_FORMATS[format][2]) | filter_kwargs
  1196. func(filename, extract_dir, **kwargs)
  1197. if hasattr(os, 'statvfs'):
  1198. __all__.append('disk_usage')
  1199. _ntuple_diskusage = collections.namedtuple('usage', 'total used free')
  1200. _ntuple_diskusage.total.__doc__ = 'Total space in bytes'
  1201. _ntuple_diskusage.used.__doc__ = 'Used space in bytes'
  1202. _ntuple_diskusage.free.__doc__ = 'Free space in bytes'
  1203. def disk_usage(path):
  1204. """Return disk usage statistics about the given path.
  1205. Returned value is a named tuple with attributes 'total', 'used' and
  1206. 'free', which are the amount of total, used and free space, in bytes.
  1207. """
  1208. st = os.statvfs(path)
  1209. free = st.f_bavail * st.f_frsize
  1210. total = st.f_blocks * st.f_frsize
  1211. used = (st.f_blocks - st.f_bfree) * st.f_frsize
  1212. return _ntuple_diskusage(total, used, free)
  1213. elif _WINDOWS:
  1214. __all__.append('disk_usage')
  1215. _ntuple_diskusage = collections.namedtuple('usage', 'total used free')
  1216. def disk_usage(path):
  1217. """Return disk usage statistics about the given path.
  1218. Returned values is a named tuple with attributes 'total', 'used' and
  1219. 'free', which are the amount of total, used and free space, in bytes.
  1220. """
  1221. total, free = nt._getdiskusage(path)
  1222. used = total - free
  1223. return _ntuple_diskusage(total, used, free)
  1224. def chown(path, user=None, group=None):
  1225. """Change owner user and group of the given path.
  1226. user and group can be the uid/gid or the user/group names, and in that case,
  1227. they are converted to their respective uid/gid.
  1228. """
  1229. sys.audit('shutil.chown', path, user, group)
  1230. if user is None and group is None:
  1231. raise ValueError("user and/or group must be set")
  1232. _user = user
  1233. _group = group
  1234. # -1 means don't change it
  1235. if user is None:
  1236. _user = -1
  1237. # user can either be an int (the uid) or a string (the system username)
  1238. elif isinstance(user, str):
  1239. _user = _get_uid(user)
  1240. if _user is None:
  1241. raise LookupError("no such user: {!r}".format(user))
  1242. if group is None:
  1243. _group = -1
  1244. elif not isinstance(group, int):
  1245. _group = _get_gid(group)
  1246. if _group is None:
  1247. raise LookupError("no such group: {!r}".format(group))
  1248. os.chown(path, _user, _group)
  1249. def get_terminal_size(fallback=(80, 24)):
  1250. """Get the size of the terminal window.
  1251. For each of the two dimensions, the environment variable, COLUMNS
  1252. and LINES respectively, is checked. If the variable is defined and
  1253. the value is a positive integer, it is used.
  1254. When COLUMNS or LINES is not defined, which is the common case,
  1255. the terminal connected to sys.__stdout__ is queried
  1256. by invoking os.get_terminal_size.
  1257. If the terminal size cannot be successfully queried, either because
  1258. the system doesn't support querying, or because we are not
  1259. connected to a terminal, the value given in fallback parameter
  1260. is used. Fallback defaults to (80, 24) which is the default
  1261. size used by many terminal emulators.
  1262. The value returned is a named tuple of type os.terminal_size.
  1263. """
  1264. # columns, lines are the working values
  1265. try:
  1266. columns = int(os.environ['COLUMNS'])
  1267. except (KeyError, ValueError):
  1268. columns = 0
  1269. try:
  1270. lines = int(os.environ['LINES'])
  1271. except (KeyError, ValueError):
  1272. lines = 0
  1273. # only query if necessary
  1274. if columns <= 0 or lines <= 0:
  1275. try:
  1276. size = os.get_terminal_size(sys.__stdout__.fileno())
  1277. except (AttributeError, ValueError, OSError):
  1278. # stdout is None, closed, detached, or not a terminal, or
  1279. # os.get_terminal_size() is unsupported
  1280. size = os.terminal_size(fallback)
  1281. if columns <= 0:
  1282. columns = size.columns or fallback[0]
  1283. if lines <= 0:
  1284. lines = size.lines or fallback[1]
  1285. return os.terminal_size((columns, lines))
  1286. # Check that a given file can be accessed with the correct mode.
  1287. # Additionally check that `file` is not a directory, as on Windows
  1288. # directories pass the os.access check.
  1289. def _access_check(fn, mode):
  1290. return (os.path.exists(fn) and os.access(fn, mode)
  1291. and not os.path.isdir(fn))
  1292. def _win_path_needs_curdir(cmd, mode):
  1293. """
  1294. On Windows, we can use NeedCurrentDirectoryForExePath to figure out
  1295. if we should add the cwd to PATH when searching for executables if
  1296. the mode is executable.
  1297. """
  1298. return (not (mode & os.X_OK)) or _winapi.NeedCurrentDirectoryForExePath(
  1299. os.fsdecode(cmd))
  1300. def which(cmd, mode=os.F_OK | os.X_OK, path=None):
  1301. """Given a command, mode, and a PATH string, return the path which
  1302. conforms to the given mode on the PATH, or None if there is no such
  1303. file.
  1304. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  1305. of os.environ.get("PATH"), or can be overridden with a custom search
  1306. path.
  1307. """
  1308. use_bytes = isinstance(cmd, bytes)
  1309. # If we're given a path with a directory part, look it up directly rather
  1310. # than referring to PATH directories. This includes checking relative to
  1311. # the current directory, e.g. ./script
  1312. dirname, cmd = os.path.split(cmd)
  1313. if dirname:
  1314. path = [dirname]
  1315. else:
  1316. if path is None:
  1317. path = os.environ.get("PATH", None)
  1318. if path is None:
  1319. try:
  1320. path = os.confstr("CS_PATH")
  1321. except (AttributeError, ValueError):
  1322. # os.confstr() or CS_PATH is not available
  1323. path = os.defpath
  1324. # bpo-35755: Don't use os.defpath if the PATH environment variable
  1325. # is set to an empty string
  1326. # PATH='' doesn't match, whereas PATH=':' looks in the current
  1327. # directory
  1328. if not path:
  1329. return None
  1330. if use_bytes:
  1331. path = os.fsencode(path)
  1332. path = path.split(os.fsencode(os.pathsep))
  1333. else:
  1334. path = os.fsdecode(path)
  1335. path = path.split(os.pathsep)
  1336. if sys.platform == "win32" and _win_path_needs_curdir(cmd, mode):
  1337. curdir = os.curdir
  1338. if use_bytes:
  1339. curdir = os.fsencode(curdir)
  1340. path.insert(0, curdir)
  1341. if sys.platform == "win32":
  1342. # PATHEXT is necessary to check on Windows.
  1343. pathext_source = os.getenv("PATHEXT") or _WIN_DEFAULT_PATHEXT
  1344. pathext = [ext for ext in pathext_source.split(os.pathsep) if ext]
  1345. if use_bytes:
  1346. pathext = [os.fsencode(ext) for ext in pathext]
  1347. files = ([cmd] + [cmd + ext for ext in pathext])
  1348. # gh-109590. If we are looking for an executable, we need to look
  1349. # for a PATHEXT match. The first cmd is the direct match
  1350. # (e.g. python.exe instead of python)
  1351. # Check that direct match first if and only if the extension is in PATHEXT
  1352. # Otherwise check it last
  1353. suffix = os.path.splitext(files[0])[1].upper()
  1354. if mode & os.X_OK and not any(suffix == ext.upper() for ext in pathext):
  1355. files.append(files.pop(0))
  1356. else:
  1357. # On other platforms you don't have things like PATHEXT to tell you
  1358. # what file suffixes are executable, so just pass on cmd as-is.
  1359. files = [cmd]
  1360. seen = set()
  1361. for dir in path:
  1362. normdir = os.path.normcase(dir)
  1363. if not normdir in seen:
  1364. seen.add(normdir)
  1365. for thefile in files:
  1366. name = os.path.join(dir, thefile)
  1367. if _access_check(name, mode):
  1368. return name
  1369. return None