dir_util.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. """distutils.dir_util
  2. Utility functions for manipulating directories and directory trees."""
  3. import functools
  4. import itertools
  5. import os
  6. import pathlib
  7. from . import file_util
  8. from ._log import log
  9. from .errors import DistutilsFileError, DistutilsInternalError
  10. class SkipRepeatAbsolutePaths(set):
  11. """
  12. Cache for mkpath.
  13. In addition to cheapening redundant calls, eliminates redundant
  14. "creating /foo/bar/baz" messages in dry-run mode.
  15. """
  16. def __init__(self):
  17. SkipRepeatAbsolutePaths.instance = self
  18. @classmethod
  19. def clear(cls):
  20. super(cls, cls.instance).clear()
  21. def wrap(self, func):
  22. @functools.wraps(func)
  23. def wrapper(path, *args, **kwargs):
  24. if path.absolute() in self:
  25. return
  26. result = func(path, *args, **kwargs)
  27. self.add(path.absolute())
  28. return result
  29. return wrapper
  30. # Python 3.8 compatibility
  31. wrapper = SkipRepeatAbsolutePaths().wrap
  32. @functools.singledispatch
  33. @wrapper
  34. def mkpath(name: pathlib.Path, mode=0o777, verbose=True, dry_run=False) -> None:
  35. """Create a directory and any missing ancestor directories.
  36. If the directory already exists (or if 'name' is the empty string, which
  37. means the current directory, which of course exists), then do nothing.
  38. Raise DistutilsFileError if unable to create some directory along the way
  39. (eg. some sub-path exists, but is a file rather than a directory).
  40. If 'verbose' is true, log the directory created.
  41. """
  42. if verbose and not name.is_dir():
  43. log.info("creating %s", name)
  44. try:
  45. dry_run or name.mkdir(mode=mode, parents=True, exist_ok=True)
  46. except OSError as exc:
  47. raise DistutilsFileError(f"could not create '{name}': {exc.args[-1]}")
  48. @mkpath.register
  49. def _(name: str, *args, **kwargs):
  50. return mkpath(pathlib.Path(name), *args, **kwargs)
  51. @mkpath.register
  52. def _(name: None, *args, **kwargs):
  53. """
  54. Detect a common bug -- name is None.
  55. """
  56. raise DistutilsInternalError(f"mkpath: 'name' must be a string (got {name!r})")
  57. def create_tree(base_dir, files, mode=0o777, verbose=True, dry_run=False):
  58. """Create all the empty directories under 'base_dir' needed to put 'files'
  59. there.
  60. 'base_dir' is just the name of a directory which doesn't necessarily
  61. exist yet; 'files' is a list of filenames to be interpreted relative to
  62. 'base_dir'. 'base_dir' + the directory portion of every file in 'files'
  63. will be created if it doesn't already exist. 'mode', 'verbose' and
  64. 'dry_run' flags are as for 'mkpath()'.
  65. """
  66. # First get the list of directories to create
  67. need_dir = set(os.path.join(base_dir, os.path.dirname(file)) for file in files)
  68. # Now create them
  69. for dir in sorted(need_dir):
  70. mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
  71. def copy_tree(
  72. src,
  73. dst,
  74. preserve_mode=True,
  75. preserve_times=True,
  76. preserve_symlinks=False,
  77. update=False,
  78. verbose=True,
  79. dry_run=False,
  80. ):
  81. """Copy an entire directory tree 'src' to a new location 'dst'.
  82. Both 'src' and 'dst' must be directory names. If 'src' is not a
  83. directory, raise DistutilsFileError. If 'dst' does not exist, it is
  84. created with 'mkpath()'. The end result of the copy is that every
  85. file in 'src' is copied to 'dst', and directories under 'src' are
  86. recursively copied to 'dst'. Return the list of files that were
  87. copied or might have been copied, using their output name. The
  88. return value is unaffected by 'update' or 'dry_run': it is simply
  89. the list of all files under 'src', with the names changed to be
  90. under 'dst'.
  91. 'preserve_mode' and 'preserve_times' are the same as for
  92. 'copy_file'; note that they only apply to regular files, not to
  93. directories. If 'preserve_symlinks' is true, symlinks will be
  94. copied as symlinks (on platforms that support them!); otherwise
  95. (the default), the destination of the symlink will be copied.
  96. 'update' and 'verbose' are the same as for 'copy_file'.
  97. """
  98. if not dry_run and not os.path.isdir(src):
  99. raise DistutilsFileError(f"cannot copy tree '{src}': not a directory")
  100. try:
  101. names = os.listdir(src)
  102. except OSError as e:
  103. if dry_run:
  104. names = []
  105. else:
  106. raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}")
  107. if not dry_run:
  108. mkpath(dst, verbose=verbose)
  109. copy_one = functools.partial(
  110. _copy_one,
  111. src=src,
  112. dst=dst,
  113. preserve_symlinks=preserve_symlinks,
  114. verbose=verbose,
  115. dry_run=dry_run,
  116. preserve_mode=preserve_mode,
  117. preserve_times=preserve_times,
  118. update=update,
  119. )
  120. return list(itertools.chain.from_iterable(map(copy_one, names)))
  121. def _copy_one(
  122. name,
  123. *,
  124. src,
  125. dst,
  126. preserve_symlinks,
  127. verbose,
  128. dry_run,
  129. preserve_mode,
  130. preserve_times,
  131. update,
  132. ):
  133. src_name = os.path.join(src, name)
  134. dst_name = os.path.join(dst, name)
  135. if name.startswith('.nfs'):
  136. # skip NFS rename files
  137. return
  138. if preserve_symlinks and os.path.islink(src_name):
  139. link_dest = os.readlink(src_name)
  140. if verbose >= 1:
  141. log.info("linking %s -> %s", dst_name, link_dest)
  142. if not dry_run:
  143. os.symlink(link_dest, dst_name)
  144. yield dst_name
  145. elif os.path.isdir(src_name):
  146. yield from copy_tree(
  147. src_name,
  148. dst_name,
  149. preserve_mode,
  150. preserve_times,
  151. preserve_symlinks,
  152. update,
  153. verbose=verbose,
  154. dry_run=dry_run,
  155. )
  156. else:
  157. file_util.copy_file(
  158. src_name,
  159. dst_name,
  160. preserve_mode,
  161. preserve_times,
  162. update,
  163. verbose=verbose,
  164. dry_run=dry_run,
  165. )
  166. yield dst_name
  167. def _build_cmdtuple(path, cmdtuples):
  168. """Helper for remove_tree()."""
  169. for f in os.listdir(path):
  170. real_f = os.path.join(path, f)
  171. if os.path.isdir(real_f) and not os.path.islink(real_f):
  172. _build_cmdtuple(real_f, cmdtuples)
  173. else:
  174. cmdtuples.append((os.remove, real_f))
  175. cmdtuples.append((os.rmdir, path))
  176. def remove_tree(directory, verbose=True, dry_run=False):
  177. """Recursively remove an entire directory tree.
  178. Any errors are ignored (apart from being reported to stdout if 'verbose'
  179. is true).
  180. """
  181. if verbose >= 1:
  182. log.info("removing '%s' (and everything under it)", directory)
  183. if dry_run:
  184. return
  185. cmdtuples = []
  186. _build_cmdtuple(directory, cmdtuples)
  187. for cmd in cmdtuples:
  188. try:
  189. cmd[0](cmd[1])
  190. # Clear the cache
  191. SkipRepeatAbsolutePaths.clear()
  192. except OSError as exc:
  193. log.warning("error removing %s: %s", directory, exc)
  194. def ensure_relative(path):
  195. """Take the full path 'path', and make it a relative path.
  196. This is useful to make 'path' the second argument to os.path.join().
  197. """
  198. drive, path = os.path.splitdrive(path)
  199. if path[0:1] == os.sep:
  200. path = drive + path[1:]
  201. return path