shutil.py 49 KB

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