dir_util.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """distutils.dir_util
  2. Utility functions for manipulating directories and directory trees."""
  3. import os
  4. import errno
  5. from distutils.errors import DistutilsFileError, DistutilsInternalError
  6. from distutils import log
  7. # cache for by mkpath() -- in addition to cheapening redundant calls,
  8. # eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
  9. _path_created = {}
  10. # I don't use os.makedirs because a) it's new to Python 1.5.2, and
  11. # b) it blows up if the directory already exists (I want to silently
  12. # succeed in that case).
  13. def mkpath(name, mode=0o777, verbose=1, dry_run=0):
  14. """Create a directory and any missing ancestor directories.
  15. If the directory already exists (or if 'name' is the empty string, which
  16. means the current directory, which of course exists), then do nothing.
  17. Raise DistutilsFileError if unable to create some directory along the way
  18. (eg. some sub-path exists, but is a file rather than a directory).
  19. If 'verbose' is true, print a one-line summary of each mkdir to stdout.
  20. Return the list of directories actually created.
  21. """
  22. global _path_created
  23. # Detect a common bug -- name is None
  24. if not isinstance(name, str):
  25. raise DistutilsInternalError(
  26. "mkpath: 'name' must be a string (got %r)" % (name,)
  27. )
  28. # XXX what's the better way to handle verbosity? print as we create
  29. # each directory in the path (the current behaviour), or only announce
  30. # the creation of the whole path? (quite easy to do the latter since
  31. # we're not using a recursive algorithm)
  32. name = os.path.normpath(name)
  33. created_dirs = []
  34. if os.path.isdir(name) or name == '':
  35. return created_dirs
  36. if _path_created.get(os.path.abspath(name)):
  37. return created_dirs
  38. (head, tail) = os.path.split(name)
  39. tails = [tail] # stack of lone dirs to create
  40. while head and tail and not os.path.isdir(head):
  41. (head, tail) = os.path.split(head)
  42. tails.insert(0, tail) # push next higher dir onto stack
  43. # now 'head' contains the deepest directory that already exists
  44. # (that is, the child of 'head' in 'name' is the highest directory
  45. # that does *not* exist)
  46. for d in tails:
  47. # print "head = %s, d = %s: " % (head, d),
  48. head = os.path.join(head, d)
  49. abs_head = os.path.abspath(head)
  50. if _path_created.get(abs_head):
  51. continue
  52. if verbose >= 1:
  53. log.info("creating %s", head)
  54. if not dry_run:
  55. try:
  56. os.mkdir(head, mode)
  57. except OSError as exc:
  58. if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
  59. raise DistutilsFileError(
  60. "could not create '%s': %s" % (head, exc.args[-1])
  61. )
  62. created_dirs.append(head)
  63. _path_created[abs_head] = 1
  64. return created_dirs
  65. def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):
  66. """Create all the empty directories under 'base_dir' needed to put 'files'
  67. there.
  68. 'base_dir' is just the name of a directory which doesn't necessarily
  69. exist yet; 'files' is a list of filenames to be interpreted relative to
  70. 'base_dir'. 'base_dir' + the directory portion of every file in 'files'
  71. will be created if it doesn't already exist. 'mode', 'verbose' and
  72. 'dry_run' flags are as for 'mkpath()'.
  73. """
  74. # First get the list of directories to create
  75. need_dir = set()
  76. for file in files:
  77. need_dir.add(os.path.join(base_dir, os.path.dirname(file)))
  78. # Now create them
  79. for dir in sorted(need_dir):
  80. mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
  81. def copy_tree(
  82. src,
  83. dst,
  84. preserve_mode=1,
  85. preserve_times=1,
  86. preserve_symlinks=0,
  87. update=0,
  88. verbose=1,
  89. dry_run=0,
  90. ):
  91. """Copy an entire directory tree 'src' to a new location 'dst'.
  92. Both 'src' and 'dst' must be directory names. If 'src' is not a
  93. directory, raise DistutilsFileError. If 'dst' does not exist, it is
  94. created with 'mkpath()'. The end result of the copy is that every
  95. file in 'src' is copied to 'dst', and directories under 'src' are
  96. recursively copied to 'dst'. Return the list of files that were
  97. copied or might have been copied, using their output name. The
  98. return value is unaffected by 'update' or 'dry_run': it is simply
  99. the list of all files under 'src', with the names changed to be
  100. under 'dst'.
  101. 'preserve_mode' and 'preserve_times' are the same as for
  102. 'copy_file'; note that they only apply to regular files, not to
  103. directories. If 'preserve_symlinks' is true, symlinks will be
  104. copied as symlinks (on platforms that support them!); otherwise
  105. (the default), the destination of the symlink will be copied.
  106. 'update' and 'verbose' are the same as for 'copy_file'.
  107. """
  108. from distutils.file_util import copy_file
  109. if not dry_run and not os.path.isdir(src):
  110. raise DistutilsFileError("cannot copy tree '%s': not a directory" % src)
  111. try:
  112. names = os.listdir(src)
  113. except OSError as e:
  114. if dry_run:
  115. names = []
  116. else:
  117. raise DistutilsFileError(
  118. "error listing files in '%s': %s" % (src, e.strerror)
  119. )
  120. if not dry_run:
  121. mkpath(dst, verbose=verbose)
  122. outputs = []
  123. for n in names:
  124. src_name = os.path.join(src, n)
  125. dst_name = os.path.join(dst, n)
  126. if n.startswith('.nfs'):
  127. # skip NFS rename files
  128. continue
  129. if preserve_symlinks and os.path.islink(src_name):
  130. link_dest = os.readlink(src_name)
  131. if verbose >= 1:
  132. log.info("linking %s -> %s", dst_name, link_dest)
  133. if not dry_run:
  134. os.symlink(link_dest, dst_name)
  135. outputs.append(dst_name)
  136. elif os.path.isdir(src_name):
  137. outputs.extend(
  138. copy_tree(
  139. src_name,
  140. dst_name,
  141. preserve_mode,
  142. preserve_times,
  143. preserve_symlinks,
  144. update,
  145. verbose=verbose,
  146. dry_run=dry_run,
  147. )
  148. )
  149. else:
  150. copy_file(
  151. src_name,
  152. dst_name,
  153. preserve_mode,
  154. preserve_times,
  155. update,
  156. verbose=verbose,
  157. dry_run=dry_run,
  158. )
  159. outputs.append(dst_name)
  160. return outputs
  161. def _build_cmdtuple(path, cmdtuples):
  162. """Helper for remove_tree()."""
  163. for f in os.listdir(path):
  164. real_f = os.path.join(path, f)
  165. if os.path.isdir(real_f) and not os.path.islink(real_f):
  166. _build_cmdtuple(real_f, cmdtuples)
  167. else:
  168. cmdtuples.append((os.remove, real_f))
  169. cmdtuples.append((os.rmdir, path))
  170. def remove_tree(directory, verbose=1, dry_run=0):
  171. """Recursively remove an entire directory tree.
  172. Any errors are ignored (apart from being reported to stdout if 'verbose'
  173. is true).
  174. """
  175. global _path_created
  176. if verbose >= 1:
  177. log.info("removing '%s' (and everything under it)", directory)
  178. if dry_run:
  179. return
  180. cmdtuples = []
  181. _build_cmdtuple(directory, cmdtuples)
  182. for cmd in cmdtuples:
  183. try:
  184. cmd[0](cmd[1])
  185. # remove dir from cache if it's already there
  186. abspath = os.path.abspath(cmd[1])
  187. if abspath in _path_created:
  188. del _path_created[abspath]
  189. except OSError as exc:
  190. log.warn("error removing %s: %s", directory, exc)
  191. def ensure_relative(path):
  192. """Take the full path 'path', and make it a relative path.
  193. This is useful to make 'path' the second argument to os.path.join().
  194. """
  195. drive, path = os.path.splitdrive(path)
  196. if path[0:1] == os.sep:
  197. path = drive + path[1:]
  198. return path