dir_util.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. # XXX what's the better way to handle verbosity? print as we create
  28. # each directory in the path (the current behaviour), or only announce
  29. # the creation of the whole path? (quite easy to do the latter since
  30. # we're not using a recursive algorithm)
  31. name = os.path.normpath(name)
  32. created_dirs = []
  33. if os.path.isdir(name) or name == '':
  34. return created_dirs
  35. if _path_created.get(os.path.abspath(name)):
  36. return created_dirs
  37. (head, tail) = os.path.split(name)
  38. tails = [tail] # stack of lone dirs to create
  39. while head and tail and not os.path.isdir(head):
  40. (head, tail) = os.path.split(head)
  41. tails.insert(0, tail) # push next higher dir onto stack
  42. # now 'head' contains the deepest directory that already exists
  43. # (that is, the child of 'head' in 'name' is the highest directory
  44. # that does *not* exist)
  45. for d in tails:
  46. #print "head = %s, d = %s: " % (head, d),
  47. head = os.path.join(head, d)
  48. abs_head = os.path.abspath(head)
  49. if _path_created.get(abs_head):
  50. continue
  51. if verbose >= 1:
  52. log.info("creating %s", head)
  53. if not dry_run:
  54. try:
  55. os.mkdir(head, mode)
  56. except OSError as exc:
  57. if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
  58. raise DistutilsFileError(
  59. "could not create '%s': %s" % (head, exc.args[-1]))
  60. created_dirs.append(head)
  61. _path_created[abs_head] = 1
  62. return created_dirs
  63. def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):
  64. """Create all the empty directories under 'base_dir' needed to put 'files'
  65. there.
  66. 'base_dir' is just the name of a directory which doesn't necessarily
  67. exist yet; 'files' is a list of filenames to be interpreted relative to
  68. 'base_dir'. 'base_dir' + the directory portion of every file in 'files'
  69. will be created if it doesn't already exist. 'mode', 'verbose' and
  70. 'dry_run' flags are as for 'mkpath()'.
  71. """
  72. # First get the list of directories to create
  73. need_dir = set()
  74. for file in files:
  75. need_dir.add(os.path.join(base_dir, os.path.dirname(file)))
  76. # Now create them
  77. for dir in sorted(need_dir):
  78. mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
  79. def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
  80. preserve_symlinks=0, update=0, verbose=1, dry_run=0):
  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. from distutils.file_util import copy_file
  99. if not dry_run and not os.path.isdir(src):
  100. raise DistutilsFileError(
  101. "cannot copy tree '%s': not a directory" % src)
  102. try:
  103. names = os.listdir(src)
  104. except OSError as e:
  105. if dry_run:
  106. names = []
  107. else:
  108. raise DistutilsFileError(
  109. "error listing files in '%s': %s" % (src, e.strerror))
  110. if not dry_run:
  111. mkpath(dst, verbose=verbose)
  112. outputs = []
  113. for n in names:
  114. src_name = os.path.join(src, n)
  115. dst_name = os.path.join(dst, n)
  116. if n.startswith('.nfs'):
  117. # skip NFS rename files
  118. continue
  119. if preserve_symlinks and os.path.islink(src_name):
  120. link_dest = os.readlink(src_name)
  121. if verbose >= 1:
  122. log.info("linking %s -> %s", dst_name, link_dest)
  123. if not dry_run:
  124. os.symlink(link_dest, dst_name)
  125. outputs.append(dst_name)
  126. elif os.path.isdir(src_name):
  127. outputs.extend(
  128. copy_tree(src_name, dst_name, preserve_mode,
  129. preserve_times, preserve_symlinks, update,
  130. verbose=verbose, dry_run=dry_run))
  131. else:
  132. copy_file(src_name, dst_name, preserve_mode,
  133. preserve_times, update, verbose=verbose,
  134. dry_run=dry_run)
  135. outputs.append(dst_name)
  136. return outputs
  137. def _build_cmdtuple(path, cmdtuples):
  138. """Helper for remove_tree()."""
  139. for f in os.listdir(path):
  140. real_f = os.path.join(path,f)
  141. if os.path.isdir(real_f) and not os.path.islink(real_f):
  142. _build_cmdtuple(real_f, cmdtuples)
  143. else:
  144. cmdtuples.append((os.remove, real_f))
  145. cmdtuples.append((os.rmdir, path))
  146. def remove_tree(directory, verbose=1, dry_run=0):
  147. """Recursively remove an entire directory tree.
  148. Any errors are ignored (apart from being reported to stdout if 'verbose'
  149. is true).
  150. """
  151. global _path_created
  152. if verbose >= 1:
  153. log.info("removing '%s' (and everything under it)", directory)
  154. if dry_run:
  155. return
  156. cmdtuples = []
  157. _build_cmdtuple(directory, cmdtuples)
  158. for cmd in cmdtuples:
  159. try:
  160. cmd[0](cmd[1])
  161. # remove dir from cache if it's already there
  162. abspath = os.path.abspath(cmd[1])
  163. if abspath in _path_created:
  164. del _path_created[abspath]
  165. except OSError as exc:
  166. log.warn("error removing %s: %s", directory, exc)
  167. def ensure_relative(path):
  168. """Take the full path 'path', and make it a relative path.
  169. This is useful to make 'path' the second argument to os.path.join().
  170. """
  171. drive, path = os.path.splitdrive(path)
  172. if path[0:1] == os.sep:
  173. path = drive + path[1:]
  174. return path