blob: d5cd8e3e24f46a8d4610717d76fb3ef9ad80b643 [file] [log] [blame]
Greg Wardaebf7062000-04-04 02:05:59 +00001"""distutils.dir_util
2
3Utility functions for manipulating directories and directory trees."""
4
Éric Araujofc773a22014-03-12 03:34:02 -04005import os
Éric Araujoff1144e2010-11-20 19:35:27 +00006import errno
Greg Ward2d238c52000-05-27 01:35:27 +00007from distutils.errors import DistutilsFileError, DistutilsInternalError
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +00008from distutils import log
Greg Wardaebf7062000-04-04 02:05:59 +00009
10# cache for by mkpath() -- in addition to cheapening redundant calls,
11# eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
Greg Wardb248b7f2000-06-17 02:19:30 +000012_path_created = {}
Greg Wardaebf7062000-04-04 02:05:59 +000013
14# I don't use os.makedirs because a) it's new to Python 1.5.2, and
15# b) it blows up if the directory already exists (I want to silently
16# succeed in that case).
Tarek Ziadéfe66fc12009-05-17 11:25:57 +000017def mkpath(name, mode=0o777, verbose=1, dry_run=0):
18 """Create a directory and any missing ancestor directories.
19
20 If the directory already exists (or if 'name' is the empty string, which
21 means the current directory, which of course exists), then do nothing.
22 Raise DistutilsFileError if unable to create some directory along the way
23 (eg. some sub-path exists, but is a file rather than a directory).
24 If 'verbose' is true, print a one-line summary of each mkdir to stdout.
25 Return the list of directories actually created.
26 """
Greg Wardaebf7062000-04-04 02:05:59 +000027
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 Ward071ed762000-09-26 02:12:31 +000051 (head, tail) = os.path.split(head)
Greg Ward071ed762000-09-26 02:12:31 +000052 tails.insert(0, tail) # push next higher dir onto stack
Greg Wardaebf7062000-04-04 02:05:59 +000053
Greg Wardaebf7062000-04-04 02:05:59 +000054 # now 'head' contains the deepest directory that already exists
55 # (that is, the child of 'head' in 'name' is the highest directory
56 # that does *not* exist)
57 for d in tails:
58 #print "head = %s, d = %s: " % (head, d),
Greg Ward071ed762000-09-26 02:12:31 +000059 head = os.path.join(head, d)
Greg Ward963cd2d2000-09-30 17:47:17 +000060 abs_head = os.path.abspath(head)
61
62 if _path_created.get(abs_head):
Greg Wardaebf7062000-04-04 02:05:59 +000063 continue
64
Tarek Ziadé35e6fd52009-02-06 00:53:43 +000065 if verbose >= 1:
Tarek Ziadé70a74eb2009-02-06 00:38:35 +000066 log.info("creating %s", head)
Greg Wardaebf7062000-04-04 02:05:59 +000067
68 if not dry_run:
69 try:
Senthil Kumaran9b86a692010-09-17 16:35:37 +000070 os.mkdir(head, mode)
Guido van Rossumb940e112007-01-10 16:19:56 +000071 except OSError as exc:
Éric Araujoba7209f2010-11-06 04:48:05 +000072 if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
73 raise DistutilsFileError(
74 "could not create '%s': %s" % (head, exc.args[-1]))
75 created_dirs.append(head)
Greg Wardaebf7062000-04-04 02:05:59 +000076
Greg Ward963cd2d2000-09-30 17:47:17 +000077 _path_created[abs_head] = 1
Greg Wardaebf7062000-04-04 02:05:59 +000078 return created_dirs
79
Tarek Ziadéfe66fc12009-05-17 11:25:57 +000080def create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):
81 """Create all the empty directories under 'base_dir' needed to put 'files'
82 there.
Greg Wardaebf7062000-04-04 02:05:59 +000083
Benjamin Peterson82f34ad2015-01-13 09:17:24 -050084 'base_dir' is just the name of a directory which doesn't necessarily
Tarek Ziadéfe66fc12009-05-17 11:25:57 +000085 exist yet; 'files' is a list of filenames to be interpreted relative to
86 'base_dir'. 'base_dir' + the directory portion of every file in 'files'
87 will be created if it doesn't already exist. 'mode', 'verbose' and
88 'dry_run' flags are as for 'mkpath()'.
89 """
Greg Wardaebf7062000-04-04 02:05:59 +000090 # First get the list of directories to create
Guido van Rossum486364b2007-06-30 05:01:58 +000091 need_dir = set()
Greg Wardaebf7062000-04-04 02:05:59 +000092 for file in files:
Guido van Rossum486364b2007-06-30 05:01:58 +000093 need_dir.add(os.path.join(base_dir, os.path.dirname(file)))
Greg Wardaebf7062000-04-04 02:05:59 +000094
95 # Now create them
Guido van Rossum486364b2007-06-30 05:01:58 +000096 for dir in sorted(need_dir):
Tarek Ziadé70a74eb2009-02-06 00:38:35 +000097 mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
Greg Wardaebf7062000-04-04 02:05:59 +000098
Tarek Ziadéfe66fc12009-05-17 11:25:57 +000099def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
100 preserve_symlinks=0, update=0, verbose=1, dry_run=0):
101 """Copy an entire directory tree 'src' to a new location 'dst'.
Greg Wardaebf7062000-04-04 02:05:59 +0000102
Tarek Ziadéfe66fc12009-05-17 11:25:57 +0000103 Both 'src' and 'dst' must be directory names. If 'src' is not a
104 directory, raise DistutilsFileError. If 'dst' does not exist, it is
105 created with 'mkpath()'. The end result of the copy is that every
106 file in 'src' is copied to 'dst', and directories under 'src' are
107 recursively copied to 'dst'. Return the list of files that were
108 copied or might have been copied, using their output name. The
109 return value is unaffected by 'update' or 'dry_run': it is simply
110 the list of all files under 'src', with the names changed to be
111 under 'dst'.
Greg Wardaebf7062000-04-04 02:05:59 +0000112
Tarek Ziadéfe66fc12009-05-17 11:25:57 +0000113 'preserve_mode' and 'preserve_times' are the same as for
114 'copy_file'; note that they only apply to regular files, not to
115 directories. If 'preserve_symlinks' is true, symlinks will be
116 copied as symlinks (on platforms that support them!); otherwise
117 (the default), the destination of the symlink will be copied.
118 'update' and 'verbose' are the same as for 'copy_file'.
119 """
Greg Wardaebf7062000-04-04 02:05:59 +0000120 from distutils.file_util import copy_file
121
Greg Ward071ed762000-09-26 02:12:31 +0000122 if not dry_run and not os.path.isdir(src):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000123 raise DistutilsFileError(
124 "cannot copy tree '%s': not a directory" % src)
Greg Wardaebf7062000-04-04 02:05:59 +0000125 try:
Greg Ward071ed762000-09-26 02:12:31 +0000126 names = os.listdir(src)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200127 except OSError as e:
Greg Wardaebf7062000-04-04 02:05:59 +0000128 if dry_run:
129 names = []
130 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000131 raise DistutilsFileError(
Jason R. Coombs311321e2014-08-31 17:42:20 -0400132 "error listing files in '%s': %s" % (src, e.strerror))
Greg Wardaebf7062000-04-04 02:05:59 +0000133
134 if not dry_run:
Tarek Ziadé70a74eb2009-02-06 00:38:35 +0000135 mkpath(dst, verbose=verbose)
Greg Wardaebf7062000-04-04 02:05:59 +0000136
137 outputs = []
138
139 for n in names:
Greg Ward071ed762000-09-26 02:12:31 +0000140 src_name = os.path.join(src, n)
141 dst_name = os.path.join(dst, n)
Greg Wardaebf7062000-04-04 02:05:59 +0000142
Éric Araujo3e4a3dc2012-12-08 14:21:51 -0500143 if n.startswith('.nfs'):
144 # skip NFS rename files
145 continue
146
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é35e6fd52009-02-06 00:53:43 +0000149 if verbose >= 1:
Tarek Ziadé70a74eb2009-02-06 00:38:35 +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é70a74eb2009-02-06 00:38:35 +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é70a74eb2009-02-06 00:38:35 +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éfe66fc12009-05-17 11:25:57 +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éfe66fc12009-05-17 11:25:57 +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éfe66fc12009-05-17 11:25:57 +0000181 Any errors are ignored (apart from being reported to stdout if 'verbose'
182 is true).
Greg Wardfcd4f872000-06-17 02:18:19 +0000183 """
Greg Wardb248b7f2000-06-17 02:19:30 +0000184 global _path_created
Greg Wardfcd4f872000-06-17 02:18:19 +0000185
Tarek Ziadé35e6fd52009-02-06 00:53:43 +0000186 if verbose >= 1:
Tarek Ziadé70a74eb2009-02-06 00:38:35 +0000187 log.info("removing '%s' (and everything under it)", directory)
Greg Wardaebf7062000-04-04 02:05:59 +0000188 if dry_run:
189 return
Greg Ward039accf2000-06-17 01:58:14 +0000190 cmdtuples = []
191 _build_cmdtuple(directory, cmdtuples)
192 for cmd in cmdtuples:
193 try:
Neal Norwitzd9108552006-03-17 08:00:19 +0000194 cmd[0](cmd[1])
Greg Ward039accf2000-06-17 01:58:14 +0000195 # remove dir from cache if it's already there
Greg Ward963cd2d2000-09-30 17:47:17 +0000196 abspath = os.path.abspath(cmd[1])
Neal Norwitzf1a69c12006-08-20 16:25:10 +0000197 if abspath in _path_created:
Greg Ward963cd2d2000-09-30 17:47:17 +0000198 del _path_created[abspath]
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200199 except OSError as exc:
Éric Araujofc773a22014-03-12 03:34:02 -0400200 log.warn("error removing %s: %s", directory, exc)
Andrew M. Kuchling40f23e02002-11-26 17:42:48 +0000201
Tarek Ziadéc81d84b2009-05-17 11:14:15 +0000202def ensure_relative(path):
Tarek Ziadéfe66fc12009-05-17 11:25:57 +0000203 """Take the full path 'path', and make it a relative path.
204
205 This is useful to make 'path' the second argument to os.path.join().
Andrew M. Kuchling40f23e02002-11-26 17:42:48 +0000206 """
207 drive, path = os.path.splitdrive(path)
Tarek Ziadéc81d84b2009-05-17 11:14:15 +0000208 if path[0:1] == os.sep:
209 path = drive + path[1:]
210 return path