dir_util.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. """distutils.dir_util
  2. Utility functions for manipulating directories and directory trees."""
  3. __revision__ = "$Id$"
  4. import os
  5. import errno
  6. from distutils.errors import DistutilsFileError, DistutilsInternalError
  7. from distutils import log
  8. # cache for by mkpath() -- in addition to cheapening redundant calls,
  9. # eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
  10. _path_created = {}
  11. # I don't use os.makedirs because a) it's new to Python 1.5.2, and
  12. # b) it blows up if the directory already exists (I want to silently
  13. # succeed in that case).
  14. def mkpath(name, mode=0777, verbose=1, dry_run=0):
  15. """Create a directory and any missing ancestor directories.
  16. If the directory already exists (or if 'name' is the empty string, which
  17. means the current directory, which of course exists), then do nothing.
  18. Raise DistutilsFileError if unable to create some directory along the way
  19. (eg. some sub-path exists, but is a file rather than a directory).
  20. If 'verbose' is true, print a one-line summary of each mkdir to stdout.
  21. Return the list of directories actually created.
  22. """
  23. global _path_created
  24. # Detect a common bug -- name is None
  25. if not isinstance(name, basestring):
  26. raise DistutilsInternalError, \
  27. "mkpath: 'name' must be a string (got %r)" % (name,)
  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, 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. created_dirs.append(head)
  62. _path_created[abs_head] = 1
  63. return created_dirs
  64. def create_tree(base_dir, files, mode=0777, verbose=1, dry_run=0):
  65. """Create all the empty directories under 'base_dir' needed to put 'files'
  66. there.
  67. 'base_dir' is just the name of a directory which doesn't necessarily
  68. exist yet; 'files' is a list of filenames to be interpreted relative to
  69. 'base_dir'. 'base_dir' + the directory portion of every file in 'files'
  70. will be created if it doesn't already exist. 'mode', 'verbose' and
  71. 'dry_run' flags are as for 'mkpath()'.
  72. """
  73. # First get the list of directories to create
  74. need_dir = {}
  75. for file in files:
  76. need_dir[os.path.join(base_dir, os.path.dirname(file))] = 1
  77. need_dirs = need_dir.keys()
  78. need_dirs.sort()
  79. # Now create them
  80. for dir in need_dirs:
  81. mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
  82. def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
  83. preserve_symlinks=0, update=0, verbose=1, dry_run=0):
  84. """Copy an entire directory tree 'src' to a new location 'dst'.
  85. Both 'src' and 'dst' must be directory names. If 'src' is not a
  86. directory, raise DistutilsFileError. If 'dst' does not exist, it is
  87. created with 'mkpath()'. The end result of the copy is that every
  88. file in 'src' is copied to 'dst', and directories under 'src' are
  89. recursively copied to 'dst'. Return the list of files that were
  90. copied or might have been copied, using their output name. The
  91. return value is unaffected by 'update' or 'dry_run': it is simply
  92. the list of all files under 'src', with the names changed to be
  93. under 'dst'.
  94. 'preserve_mode' and 'preserve_times' are the same as for
  95. 'copy_file'; note that they only apply to regular files, not to
  96. directories. If 'preserve_symlinks' is true, symlinks will be
  97. copied as symlinks (on platforms that support them!); otherwise
  98. (the default), the destination of the symlink will be copied.
  99. 'update' and 'verbose' are the same as for 'copy_file'.
  100. """
  101. from distutils.file_util import copy_file
  102. if not dry_run and not os.path.isdir(src):
  103. raise DistutilsFileError, \
  104. "cannot copy tree '%s': not a directory" % src
  105. try:
  106. names = os.listdir(src)
  107. except os.error, (errno, errstr):
  108. if dry_run:
  109. names = []
  110. else:
  111. raise DistutilsFileError, \
  112. "error listing files in '%s': %s" % (src, errstr)
  113. if not dry_run:
  114. mkpath(dst, verbose=verbose)
  115. outputs = []
  116. for n in names:
  117. src_name = os.path.join(src, n)
  118. dst_name = os.path.join(dst, n)
  119. if n.startswith('.nfs'):
  120. # skip NFS rename files
  121. continue
  122. if preserve_symlinks and os.path.islink(src_name):
  123. link_dest = os.readlink(src_name)
  124. if verbose >= 1:
  125. log.info("linking %s -> %s", dst_name, link_dest)
  126. if not dry_run:
  127. os.symlink(link_dest, dst_name)
  128. outputs.append(dst_name)
  129. elif os.path.isdir(src_name):
  130. outputs.extend(
  131. copy_tree(src_name, dst_name, preserve_mode,
  132. preserve_times, preserve_symlinks, update,
  133. verbose=verbose, dry_run=dry_run))
  134. else:
  135. copy_file(src_name, dst_name, preserve_mode,
  136. preserve_times, update, verbose=verbose,
  137. dry_run=dry_run)
  138. outputs.append(dst_name)
  139. return outputs
  140. def _build_cmdtuple(path, cmdtuples):
  141. """Helper for remove_tree()."""
  142. for f in os.listdir(path):
  143. real_f = os.path.join(path,f)
  144. if os.path.isdir(real_f) and not os.path.islink(real_f):
  145. _build_cmdtuple(real_f, cmdtuples)
  146. else:
  147. cmdtuples.append((os.remove, real_f))
  148. cmdtuples.append((os.rmdir, path))
  149. def remove_tree(directory, verbose=1, dry_run=0):
  150. """Recursively remove an entire directory tree.
  151. Any errors are ignored (apart from being reported to stdout if 'verbose'
  152. is true).
  153. """
  154. global _path_created
  155. if verbose >= 1:
  156. log.info("removing '%s' (and everything under it)", directory)
  157. if dry_run:
  158. return
  159. cmdtuples = []
  160. _build_cmdtuple(directory, cmdtuples)
  161. for cmd in cmdtuples:
  162. try:
  163. cmd[0](cmd[1])
  164. # remove dir from cache if it's already there
  165. abspath = os.path.abspath(cmd[1])
  166. if abspath in _path_created:
  167. del _path_created[abspath]
  168. except (IOError, OSError), exc:
  169. log.warn("error removing %s: %s", directory, exc)
  170. def ensure_relative(path):
  171. """Take the full path 'path', and make it a relative path.
  172. This is useful to make 'path' the second argument to os.path.join().
  173. """
  174. drive, path = os.path.splitdrive(path)
  175. if path[0:1] == os.sep:
  176. path = drive + path[1:]
  177. return path