shutil.py 41 KB

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