blob: 9c5cf337c6c9ab87fa693e3d754b584573424a8d [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
Tarek Ziadé2b66da72009-12-21 01:22:46 +00007import os
Éric Araujo4fadd532010-11-20 20:02:41 +00008import errno
Greg Ward2d238c52000-05-27 01:35:27 +00009from distutils.errors import DistutilsFileError, DistutilsInternalError
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000010from distutils import log
Greg Wardaebf7062000-04-04 02:05:59 +000011
12# cache for by mkpath() -- in addition to cheapening redundant calls,
13# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
Greg Wardb248b7f2000-06-17 02:19:30 +000014_path_created = {}
Greg Wardaebf7062000-04-04 02:05:59 +000015
16# I don't use os.makedirs because a) it's new to Python 1.5.2, and
17# b) it blows up if the directory already exists (I want to silently
18# succeed in that case).
Tarek Ziadé513a8b72009-05-17 11:22:36 +000019def mkpath(name, mode=0777, verbose=1, dry_run=0):
20 """Create a directory and any missing ancestor directories.
21
22 If the directory already exists (or if 'name' is the empty string, which
23 means the current directory, which of course exists), then do nothing.
24 Raise DistutilsFileError if unable to create some directory along the way
25 (eg. some sub-path exists, but is a file rather than a directory).
26 If 'verbose' is true, print a one-line summary of each mkdir to stdout.
27 Return the list of directories actually created.
28 """
Greg Wardaebf7062000-04-04 02:05:59 +000029
Greg Wardb248b7f2000-06-17 02:19:30 +000030 global _path_created
Greg Wardaebf7062000-04-04 02:05:59 +000031
Greg Ward2d238c52000-05-27 01:35:27 +000032 # Detect a common bug -- name is None
Tarek Ziadé513a8b72009-05-17 11:22:36 +000033 if not isinstance(name, basestring):
Greg Ward2d238c52000-05-27 01:35:27 +000034 raise DistutilsInternalError, \
Walter Dörwald70a6b492004-02-12 17:35:32 +000035 "mkpath: 'name' must be a string (got %r)" % (name,)
Greg Ward2d238c52000-05-27 01:35:27 +000036
Greg Wardaebf7062000-04-04 02:05:59 +000037 # XXX what's the better way to handle verbosity? print as we create
38 # each directory in the path (the current behaviour), or only announce
39 # the creation of the whole path? (quite easy to do the latter since
40 # we're not using a recursive algorithm)
41
Greg Ward071ed762000-09-26 02:12:31 +000042 name = os.path.normpath(name)
Greg Wardaebf7062000-04-04 02:05:59 +000043 created_dirs = []
Greg Ward071ed762000-09-26 02:12:31 +000044 if os.path.isdir(name) or name == '':
Greg Wardaebf7062000-04-04 02:05:59 +000045 return created_dirs
Greg Ward963cd2d2000-09-30 17:47:17 +000046 if _path_created.get(os.path.abspath(name)):
Greg Wardaebf7062000-04-04 02:05:59 +000047 return created_dirs
48
Greg Ward071ed762000-09-26 02:12:31 +000049 (head, tail) = os.path.split(name)
Greg Wardaebf7062000-04-04 02:05:59 +000050 tails = [tail] # stack of lone dirs to create
Fred Drakeb94b8492001-12-06 20:51:35 +000051
Greg Ward071ed762000-09-26 02:12:31 +000052 while head and tail and not os.path.isdir(head):
Greg Ward071ed762000-09-26 02:12:31 +000053 (head, tail) = os.path.split(head)
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
Greg Wardaebf7062000-04-04 02:05:59 +000056 # now 'head' contains the deepest directory that already exists
57 # (that is, the child of 'head' in 'name' is the highest directory
58 # that does *not* exist)
59 for d in tails:
60 #print "head = %s, d = %s: " % (head, d),
Greg Ward071ed762000-09-26 02:12:31 +000061 head = os.path.join(head, d)
Greg Ward963cd2d2000-09-30 17:47:17 +000062 abs_head = os.path.abspath(head)
63
64 if _path_created.get(abs_head):
Greg Wardaebf7062000-04-04 02:05:59 +000065 continue
66
Tarek Ziadéaaf2e182009-02-06 00:49:45 +000067 if verbose >= 1:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +000068 log.info("creating %s", head)
Greg Wardaebf7062000-04-04 02:05:59 +000069
70 if not dry_run:
71 try:
Senthil Kumaran9c379bb2010-09-17 16:40:01 +000072 os.mkdir(head, mode)
Greg Wardaebf7062000-04-04 02:05:59 +000073 except OSError, exc:
Éric Araujoe9954b52010-11-06 04:53:42 +000074 if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
75 raise DistutilsFileError(
76 "could not create '%s': %s" % (head, exc.args[-1]))
77 created_dirs.append(head)
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
Tarek Ziadé513a8b72009-05-17 11:22:36 +000082def create_tree(base_dir, files, mode=0777, verbose=1, dry_run=0):
83 """Create all the empty directories under 'base_dir' needed to put 'files'
84 there.
Greg Wardaebf7062000-04-04 02:05:59 +000085
Tarek Ziadé513a8b72009-05-17 11:22:36 +000086 'base_dir' is just the a name of a directory which doesn't necessarily
87 exist yet; 'files' is a list of filenames to be interpreted relative to
88 'base_dir'. 'base_dir' + the directory portion of every file in 'files'
89 will be created if it doesn't already exist. 'mode', 'verbose' and
90 'dry_run' flags are as for 'mkpath()'.
91 """
Greg Wardaebf7062000-04-04 02:05:59 +000092 # First get the list of directories to create
93 need_dir = {}
94 for file in files:
Greg Ward071ed762000-09-26 02:12:31 +000095 need_dir[os.path.join(base_dir, os.path.dirname(file))] = 1
Greg Wardaebf7062000-04-04 02:05:59 +000096 need_dirs = need_dir.keys()
97 need_dirs.sort()
98
99 # Now create them
100 for dir in need_dirs:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000101 mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
Greg Wardaebf7062000-04-04 02:05:59 +0000102
Tarek Ziadé513a8b72009-05-17 11:22:36 +0000103def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
104 preserve_symlinks=0, update=0, verbose=1, dry_run=0):
105 """Copy an entire directory tree 'src' to a new location 'dst'.
Greg Wardaebf7062000-04-04 02:05:59 +0000106
Tarek Ziadé513a8b72009-05-17 11:22:36 +0000107 Both 'src' and 'dst' must be directory names. If 'src' is not a
108 directory, raise DistutilsFileError. If 'dst' does not exist, it is
109 created with 'mkpath()'. The end result of the copy is that every
110 file in 'src' is copied to 'dst', and directories under 'src' are
111 recursively copied to 'dst'. Return the list of files that were
112 copied or might have been copied, using their output name. The
113 return value is unaffected by 'update' or 'dry_run': it is simply
114 the list of all files under 'src', with the names changed to be
115 under 'dst'.
Greg Wardaebf7062000-04-04 02:05:59 +0000116
Tarek Ziadé513a8b72009-05-17 11:22:36 +0000117 'preserve_mode' and 'preserve_times' are the same as for
118 'copy_file'; note that they only apply to regular files, not to
119 directories. If 'preserve_symlinks' is true, symlinks will be
120 copied as symlinks (on platforms that support them!); otherwise
121 (the default), the destination of the symlink will be copied.
122 'update' and 'verbose' are the same as for 'copy_file'.
123 """
Greg Wardaebf7062000-04-04 02:05:59 +0000124 from distutils.file_util import copy_file
125
Greg Ward071ed762000-09-26 02:12:31 +0000126 if not dry_run and not os.path.isdir(src):
Greg Wardaebf7062000-04-04 02:05:59 +0000127 raise DistutilsFileError, \
Fred Drakeb94b8492001-12-06 20:51:35 +0000128 "cannot copy tree '%s': not a directory" % src
Greg Wardaebf7062000-04-04 02:05:59 +0000129 try:
Greg Ward071ed762000-09-26 02:12:31 +0000130 names = os.listdir(src)
Greg Wardaebf7062000-04-04 02:05:59 +0000131 except os.error, (errno, errstr):
132 if dry_run:
133 names = []
134 else:
135 raise DistutilsFileError, \
136 "error listing files in '%s': %s" % (src, errstr)
137
138 if not dry_run:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000139 mkpath(dst, verbose=verbose)
Greg Wardaebf7062000-04-04 02:05:59 +0000140
141 outputs = []
142
143 for n in names:
Greg Ward071ed762000-09-26 02:12:31 +0000144 src_name = os.path.join(src, n)
145 dst_name = os.path.join(dst, n)
Greg Wardaebf7062000-04-04 02:05:59 +0000146
Greg Ward071ed762000-09-26 02:12:31 +0000147 if preserve_symlinks and os.path.islink(src_name):
148 link_dest = os.readlink(src_name)
Tarek Ziadéaaf2e182009-02-06 00:49:45 +0000149 if verbose >= 1:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000150 log.info("linking %s -> %s", dst_name, link_dest)
Greg Wardaebf7062000-04-04 02:05:59 +0000151 if not dry_run:
Greg Ward071ed762000-09-26 02:12:31 +0000152 os.symlink(link_dest, dst_name)
153 outputs.append(dst_name)
Fred Drakeb94b8492001-12-06 20:51:35 +0000154
Greg Ward071ed762000-09-26 02:12:31 +0000155 elif os.path.isdir(src_name):
156 outputs.extend(
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000157 copy_tree(src_name, dst_name, preserve_mode,
158 preserve_times, preserve_symlinks, update,
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000159 verbose=verbose, dry_run=dry_run))
Greg Wardaebf7062000-04-04 02:05:59 +0000160 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000161 copy_file(src_name, dst_name, preserve_mode,
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000162 preserve_times, update, verbose=verbose,
163 dry_run=dry_run)
Greg Ward071ed762000-09-26 02:12:31 +0000164 outputs.append(dst_name)
Greg Wardaebf7062000-04-04 02:05:59 +0000165
166 return outputs
167
Greg Ward039accf2000-06-17 01:58:14 +0000168def _build_cmdtuple(path, cmdtuples):
Tarek Ziadé513a8b72009-05-17 11:22:36 +0000169 """Helper for remove_tree()."""
Greg Ward039accf2000-06-17 01:58:14 +0000170 for f in os.listdir(path):
171 real_f = os.path.join(path,f)
172 if os.path.isdir(real_f) and not os.path.islink(real_f):
173 _build_cmdtuple(real_f, cmdtuples)
174 else:
175 cmdtuples.append((os.remove, real_f))
176 cmdtuples.append((os.rmdir, path))
177
Tarek Ziadé513a8b72009-05-17 11:22:36 +0000178def remove_tree(directory, verbose=1, dry_run=0):
179 """Recursively remove an entire directory tree.
Greg Wardaebf7062000-04-04 02:05:59 +0000180
Tarek Ziadé513a8b72009-05-17 11:22:36 +0000181 Any errors are ignored (apart from being reported to stdout if 'verbose'
182 is true).
Greg Wardfcd4f872000-06-17 02:18:19 +0000183 """
184 from distutils.util import grok_environment_error
Greg Wardb248b7f2000-06-17 02:19:30 +0000185 global _path_created
Greg Wardfcd4f872000-06-17 02:18:19 +0000186
Tarek Ziadéaaf2e182009-02-06 00:49:45 +0000187 if verbose >= 1:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000188 log.info("removing '%s' (and everything under it)", directory)
Greg Wardaebf7062000-04-04 02:05:59 +0000189 if dry_run:
190 return
Greg Ward039accf2000-06-17 01:58:14 +0000191 cmdtuples = []
192 _build_cmdtuple(directory, cmdtuples)
193 for cmd in cmdtuples:
194 try:
Tarek Ziadéf6384862009-10-03 00:07:35 +0000195 cmd[0](cmd[1])
Greg Ward039accf2000-06-17 01:58:14 +0000196 # remove dir from cache if it's already there
Greg Ward963cd2d2000-09-30 17:47:17 +0000197 abspath = os.path.abspath(cmd[1])
Guido van Rossum8bc09652008-02-21 18:18:37 +0000198 if abspath in _path_created:
Greg Ward963cd2d2000-09-30 17:47:17 +0000199 del _path_created[abspath]
Greg Ward039accf2000-06-17 01:58:14 +0000200 except (IOError, OSError), exc:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000201 log.warn(grok_environment_error(
202 exc, "error removing %s: " % directory))
Andrew M. Kuchling40f23e02002-11-26 17:42:48 +0000203
Tarek Ziadé294c9d92009-05-17 11:11:57 +0000204def ensure_relative(path):
Tarek Ziadé513a8b72009-05-17 11:22:36 +0000205 """Take the full path 'path', and make it a relative path.
206
207 This is useful to make 'path' the second argument to os.path.join().
Andrew M. Kuchling40f23e02002-11-26 17:42:48 +0000208 """
209 drive, path = os.path.splitdrive(path)
Tarek Ziadé294c9d92009-05-17 11:11:57 +0000210 if path[0:1] == os.sep:
211 path = drive + path[1:]
212 return path