blob: 1f0d49c25f5d00d360f335d4769aaf4051ab4c8b [file] [log] [blame]
Greg Wardaebf7062000-04-04 02:05:59 +00001"""distutils.dir_util
2
3Utility functions for manipulating directories and directory trees."""
4
Greg Wardaebf7062000-04-04 02:05:59 +00005__revision__ = "$Id$"
6
Andrew M. Kuchling40f23e02002-11-26 17:42:48 +00007import os, sys
Greg Ward2d238c52000-05-27 01:35:27 +00008from distutils.errors import DistutilsFileError, DistutilsInternalError
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +00009from distutils import log
Greg Wardaebf7062000-04-04 02:05:59 +000010
11# cache for by mkpath() -- in addition to cheapening redundant calls,
12# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
Greg Wardb248b7f2000-06-17 02:19:30 +000013_path_created = {}
Greg Wardaebf7062000-04-04 02:05:59 +000014
15# I don't use os.makedirs because a) it's new to Python 1.5.2, and
16# b) it blows up if the directory already exists (I want to silently
17# succeed in that case).
Guido van Rossumcd16bf62007-06-13 18:07:49 +000018def mkpath (name, mode=0o777, verbose=0, dry_run=0):
Greg Wardaebf7062000-04-04 02:05:59 +000019 """Create a directory and any missing ancestor directories. If the
20 directory already exists (or if 'name' is the empty string, which
21 means the current directory, which of course exists), then do
22 nothing. Raise DistutilsFileError if unable to create some
23 directory along the way (eg. some sub-path exists, but is a file
24 rather than a directory). If 'verbose' is true, print a one-line
25 summary of each mkdir to stdout. Return the list of directories
26 actually created."""
27
Greg Wardb248b7f2000-06-17 02:19:30 +000028 global _path_created
Greg Wardaebf7062000-04-04 02:05:59 +000029
Greg Ward2d238c52000-05-27 01:35:27 +000030 # Detect a common bug -- name is None
Guido van Rossum3172c5d2007-10-16 18:12:55 +000031 if not isinstance(name, str):
Collin Winter5b7e9d72007-08-30 03:52:21 +000032 raise DistutilsInternalError(
33 "mkpath: 'name' must be a string (got %r)" % (name,))
Greg Ward2d238c52000-05-27 01:35:27 +000034
Greg Wardaebf7062000-04-04 02:05:59 +000035 # XXX what's the better way to handle verbosity? print as we create
36 # each directory in the path (the current behaviour), or only announce
37 # the creation of the whole path? (quite easy to do the latter since
38 # we're not using a recursive algorithm)
39
Greg Ward071ed762000-09-26 02:12:31 +000040 name = os.path.normpath(name)
Greg Wardaebf7062000-04-04 02:05:59 +000041 created_dirs = []
Greg Ward071ed762000-09-26 02:12:31 +000042 if os.path.isdir(name) or name == '':
Greg Wardaebf7062000-04-04 02:05:59 +000043 return created_dirs
Greg Ward963cd2d2000-09-30 17:47:17 +000044 if _path_created.get(os.path.abspath(name)):
Greg Wardaebf7062000-04-04 02:05:59 +000045 return created_dirs
46
Greg Ward071ed762000-09-26 02:12:31 +000047 (head, tail) = os.path.split(name)
Greg Wardaebf7062000-04-04 02:05:59 +000048 tails = [tail] # stack of lone dirs to create
Fred Drakeb94b8492001-12-06 20:51:35 +000049
Greg Ward071ed762000-09-26 02:12:31 +000050 while head and tail and not os.path.isdir(head):
Greg Wardaebf7062000-04-04 02:05:59 +000051 #print "splitting '%s': " % head,
Greg Ward071ed762000-09-26 02:12:31 +000052 (head, tail) = os.path.split(head)
Greg Wardaebf7062000-04-04 02:05:59 +000053 #print "to ('%s','%s')" % (head, tail)
Greg Ward071ed762000-09-26 02:12:31 +000054 tails.insert(0, tail) # push next higher dir onto stack
Greg Wardaebf7062000-04-04 02:05:59 +000055
56 #print "stack of tails:", tails
57
58 # now 'head' contains the deepest directory that already exists
59 # (that is, the child of 'head' in 'name' is the highest directory
60 # that does *not* exist)
61 for d in tails:
62 #print "head = %s, d = %s: " % (head, d),
Greg Ward071ed762000-09-26 02:12:31 +000063 head = os.path.join(head, d)
Greg Ward963cd2d2000-09-30 17:47:17 +000064 abs_head = os.path.abspath(head)
65
66 if _path_created.get(abs_head):
Greg Wardaebf7062000-04-04 02:05:59 +000067 continue
68
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000069 log.info("creating %s", head)
Greg Wardaebf7062000-04-04 02:05:59 +000070
71 if not dry_run:
72 try:
Greg Ward071ed762000-09-26 02:12:31 +000073 os.mkdir(head)
Greg Wardaebf7062000-04-04 02:05:59 +000074 created_dirs.append(head)
Guido van Rossumb940e112007-01-10 16:19:56 +000075 except OSError as exc:
Guido van Rossum8c746142007-08-29 13:18:47 +000076 raise DistutilsFileError(
77 "could not create '%s': %s" % (head, exc.args[-1]))
Greg Wardaebf7062000-04-04 02:05:59 +000078
Greg Ward963cd2d2000-09-30 17:47:17 +000079 _path_created[abs_head] = 1
Greg Wardaebf7062000-04-04 02:05:59 +000080 return created_dirs
81
82# mkpath ()
83
84
Guido van Rossumcd16bf62007-06-13 18:07:49 +000085def create_tree (base_dir, files, mode=0o777, verbose=0, dry_run=0):
Greg Wardaebf7062000-04-04 02:05:59 +000086
87 """Create all the empty directories under 'base_dir' needed to
88 put 'files' there. 'base_dir' is just the a name of a directory
89 which doesn't necessarily exist yet; 'files' is a list of filenames
90 to be interpreted relative to 'base_dir'. 'base_dir' + the
91 directory portion of every file in 'files' will be created if it
92 doesn't already exist. 'mode', 'verbose' and 'dry_run' flags are as
93 for 'mkpath()'."""
94
95 # First get the list of directories to create
Guido van Rossum486364b2007-06-30 05:01:58 +000096 need_dir = set()
Greg Wardaebf7062000-04-04 02:05:59 +000097 for file in files:
Guido van Rossum486364b2007-06-30 05:01:58 +000098 need_dir.add(os.path.join(base_dir, os.path.dirname(file)))
Greg Wardaebf7062000-04-04 02:05:59 +000099
100 # Now create them
Guido van Rossum486364b2007-06-30 05:01:58 +0000101 for dir in sorted(need_dir):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000102 mkpath(dir, mode, dry_run=dry_run)
Greg Wardaebf7062000-04-04 02:05:59 +0000103
104# create_tree ()
105
106
107def copy_tree (src, dst,
108 preserve_mode=1,
109 preserve_times=1,
110 preserve_symlinks=0,
111 update=0,
112 verbose=0,
113 dry_run=0):
114
115 """Copy an entire directory tree 'src' to a new location 'dst'. Both
116 'src' and 'dst' must be directory names. If 'src' is not a
117 directory, raise DistutilsFileError. If 'dst' does not exist, it is
118 created with 'mkpath()'. The end result of the copy is that every
119 file in 'src' is copied to 'dst', and directories under 'src' are
120 recursively copied to 'dst'. Return the list of files that were
121 copied or might have been copied, using their output name. The
122 return value is unaffected by 'update' or 'dry_run': it is simply
123 the list of all files under 'src', with the names changed to be
124 under 'dst'.
125
126 'preserve_mode' and 'preserve_times' are the same as for
127 'copy_file'; note that they only apply to regular files, not to
128 directories. If 'preserve_symlinks' is true, symlinks will be
129 copied as symlinks (on platforms that support them!); otherwise
130 (the default), the destination of the symlink will be copied.
131 'update' and 'verbose' are the same as for 'copy_file'."""
132
133 from distutils.file_util import copy_file
134
Greg Ward071ed762000-09-26 02:12:31 +0000135 if not dry_run and not os.path.isdir(src):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000136 raise DistutilsFileError(
137 "cannot copy tree '%s': not a directory" % src)
Greg Wardaebf7062000-04-04 02:05:59 +0000138 try:
Greg Ward071ed762000-09-26 02:12:31 +0000139 names = os.listdir(src)
Guido van Rossumb940e112007-01-10 16:19:56 +0000140 except os.error as e:
141 (errno, errstr) = e
Greg Wardaebf7062000-04-04 02:05:59 +0000142 if dry_run:
143 names = []
144 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000145 raise DistutilsFileError(
146 "error listing files in '%s': %s" % (src, errstr))
Greg Wardaebf7062000-04-04 02:05:59 +0000147
148 if not dry_run:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000149 mkpath(dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000150
151 outputs = []
152
153 for n in names:
Greg Ward071ed762000-09-26 02:12:31 +0000154 src_name = os.path.join(src, n)
155 dst_name = os.path.join(dst, n)
Greg Wardaebf7062000-04-04 02:05:59 +0000156
Greg Ward071ed762000-09-26 02:12:31 +0000157 if preserve_symlinks and os.path.islink(src_name):
158 link_dest = os.readlink(src_name)
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000159 log.info("linking %s -> %s", dst_name, link_dest)
Greg Wardaebf7062000-04-04 02:05:59 +0000160 if not dry_run:
Greg Ward071ed762000-09-26 02:12:31 +0000161 os.symlink(link_dest, dst_name)
162 outputs.append(dst_name)
Fred Drakeb94b8492001-12-06 20:51:35 +0000163
Greg Ward071ed762000-09-26 02:12:31 +0000164 elif os.path.isdir(src_name):
165 outputs.extend(
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000166 copy_tree(src_name, dst_name, preserve_mode,
167 preserve_times, preserve_symlinks, update,
168 dry_run=dry_run))
Greg Wardaebf7062000-04-04 02:05:59 +0000169 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000170 copy_file(src_name, dst_name, preserve_mode,
171 preserve_times, update, dry_run=dry_run)
Greg Ward071ed762000-09-26 02:12:31 +0000172 outputs.append(dst_name)
Greg Wardaebf7062000-04-04 02:05:59 +0000173
174 return outputs
175
Greg Ward039accf2000-06-17 01:58:14 +0000176# Helper for remove_tree()
177def _build_cmdtuple(path, cmdtuples):
178 for f in os.listdir(path):
179 real_f = os.path.join(path,f)
180 if os.path.isdir(real_f) and not os.path.islink(real_f):
181 _build_cmdtuple(real_f, cmdtuples)
182 else:
183 cmdtuples.append((os.remove, real_f))
184 cmdtuples.append((os.rmdir, path))
185
Greg Wardaebf7062000-04-04 02:05:59 +0000186
187def remove_tree (directory, verbose=0, dry_run=0):
188 """Recursively remove an entire directory tree. Any errors are ignored
Greg Wardfcd4f872000-06-17 02:18:19 +0000189 (apart from being reported to stdout if 'verbose' is true).
190 """
191 from distutils.util import grok_environment_error
Greg Wardb248b7f2000-06-17 02:19:30 +0000192 global _path_created
Greg Wardfcd4f872000-06-17 02:18:19 +0000193
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000194 log.info("removing '%s' (and everything under it)", directory)
Greg Wardaebf7062000-04-04 02:05:59 +0000195 if dry_run:
196 return
Greg Ward039accf2000-06-17 01:58:14 +0000197 cmdtuples = []
198 _build_cmdtuple(directory, cmdtuples)
199 for cmd in cmdtuples:
200 try:
Neal Norwitzd9108552006-03-17 08:00:19 +0000201 cmd[0](cmd[1])
Greg Ward039accf2000-06-17 01:58:14 +0000202 # remove dir from cache if it's already there
Greg Ward963cd2d2000-09-30 17:47:17 +0000203 abspath = os.path.abspath(cmd[1])
Neal Norwitzf1a69c12006-08-20 16:25:10 +0000204 if abspath in _path_created:
Greg Ward963cd2d2000-09-30 17:47:17 +0000205 del _path_created[abspath]
Guido van Rossumb940e112007-01-10 16:19:56 +0000206 except (IOError, OSError) as exc:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000207 log.warn(grok_environment_error(
208 exc, "error removing %s: " % directory))
Andrew M. Kuchling40f23e02002-11-26 17:42:48 +0000209
210
211def ensure_relative (path):
212 """Take the full path 'path', and make it a relative path so
213 it can be the second argument to os.path.join().
214 """
215 drive, path = os.path.splitdrive(path)
216 if sys.platform == 'mac':
217 return os.sep + path
218 else:
219 if path[0:1] == os.sep:
220 path = drive + path[1:]
221 return path