blob: c225ad317293256e7f7c2865d62884da8d923ba5 [file] [log] [blame]
Greg Wardaebf7062000-04-04 02:05:59 +00001"""distutils.file_util
2
Greg Ward449f5562000-09-26 02:03:34 +00003Utility functions for operating on single files.
4"""
Greg Wardaebf7062000-04-04 02:05:59 +00005
Martin v. Löwis5a6601c2004-11-10 22:23:15 +00006# This module should be kept compatible with Python 2.1.
Andrew M. Kuchlingd448f662002-11-19 13:12:28 +00007
Greg Wardaebf7062000-04-04 02:05:59 +00008__revision__ = "$Id$"
9
10import os
11from distutils.errors import DistutilsFileError
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000012from distutils import log
Greg Wardaebf7062000-04-04 02:05:59 +000013
14# for generating verbose output in 'copy_file()'
15_copy_action = { None: 'copying',
16 'hard': 'hard linking',
17 'sym': 'symbolically linking' }
18
19
20def _copy_file_contents (src, dst, buffer_size=16*1024):
21 """Copy the file 'src' to 'dst'; both must be filenames. Any error
Greg Ward9e3dc4e2000-09-23 00:59:34 +000022 opening either file, reading from 'src', or writing to 'dst', raises
23 DistutilsFileError. Data is read/written in chunks of 'buffer_size'
24 bytes (default 16k). No attempt is made to handle anything apart from
25 regular files.
26 """
Greg Wardaebf7062000-04-04 02:05:59 +000027 # Stolen from shutil module in the standard library, but with
28 # custom error-handling added.
29
30 fsrc = None
31 fdst = None
32 try:
33 try:
34 fsrc = open(src, 'rb')
Guido van Rossumb940e112007-01-10 16:19:56 +000035 except os.error as e:
36 (errno, errstr) = e
Greg Wardaebf7062000-04-04 02:05:59 +000037 raise DistutilsFileError, \
38 "could not open '%s': %s" % (src, errstr)
Fred Drakeb94b8492001-12-06 20:51:35 +000039
Andrew M. Kuchling3b388ec2002-02-01 18:29:34 +000040 if os.path.exists(dst):
41 try:
42 os.unlink(dst)
Guido van Rossumb940e112007-01-10 16:19:56 +000043 except os.error as e:
44 (errno, errstr) = e
Andrew M. Kuchling3b388ec2002-02-01 18:29:34 +000045 raise DistutilsFileError, \
46 "could not delete '%s': %s" % (dst, errstr)
Tim Peters182b5ac2004-07-18 06:16:08 +000047
Greg Wardaebf7062000-04-04 02:05:59 +000048 try:
49 fdst = open(dst, 'wb')
Guido van Rossumb940e112007-01-10 16:19:56 +000050 except os.error as e:
51 (errno, errstr) = e
Greg Wardaebf7062000-04-04 02:05:59 +000052 raise DistutilsFileError, \
53 "could not create '%s': %s" % (dst, errstr)
Fred Drakeb94b8492001-12-06 20:51:35 +000054
Greg Wardaebf7062000-04-04 02:05:59 +000055 while 1:
56 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +000057 buf = fsrc.read(buffer_size)
Guido van Rossumb940e112007-01-10 16:19:56 +000058 except os.error as e:
59 (errno, errstr) = e
Greg Wardaebf7062000-04-04 02:05:59 +000060 raise DistutilsFileError, \
61 "could not read from '%s': %s" % (src, errstr)
Fred Drakeb94b8492001-12-06 20:51:35 +000062
Greg Wardaebf7062000-04-04 02:05:59 +000063 if not buf:
64 break
65
66 try:
67 fdst.write(buf)
Guido van Rossumb940e112007-01-10 16:19:56 +000068 except os.error as e:
69 (errno, errstr) = e
Greg Wardaebf7062000-04-04 02:05:59 +000070 raise DistutilsFileError, \
71 "could not write to '%s': %s" % (dst, errstr)
Fred Drakeb94b8492001-12-06 20:51:35 +000072
Greg Wardaebf7062000-04-04 02:05:59 +000073 finally:
74 if fdst:
75 fdst.close()
76 if fsrc:
77 fsrc.close()
78
79# _copy_file_contents()
80
Greg Wardaebf7062000-04-04 02:05:59 +000081def copy_file (src, dst,
82 preserve_mode=1,
83 preserve_times=1,
84 update=0,
85 link=None,
86 verbose=0,
87 dry_run=0):
88
Greg Ward9e3dc4e2000-09-23 00:59:34 +000089 """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is
90 copied there with the same name; otherwise, it must be a filename. (If
91 the file exists, it will be ruthlessly clobbered.) If 'preserve_mode'
92 is true (the default), the file's mode (type and permission bits, or
93 whatever is analogous on the current platform) is copied. If
94 'preserve_times' is true (the default), the last-modified and
95 last-access times are copied as well. If 'update' is true, 'src' will
96 only be copied if 'dst' does not exist, or if 'dst' does exist but is
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000097 older than 'src'.
Greg Wardaebf7062000-04-04 02:05:59 +000098
Greg Ward9e3dc4e2000-09-23 00:59:34 +000099 'link' allows you to make hard links (os.link) or symbolic links
100 (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
101 None (the default), files are copied. Don't set 'link' on systems that
102 don't support it: 'copy_file()' doesn't check if hard or symbolic
103 linking is available.
Greg Wardaebf7062000-04-04 02:05:59 +0000104
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000105 Under Mac OS, uses the native file copy function in macostools; on
106 other systems, uses '_copy_file_contents()' to copy file contents.
Greg Wardaebf7062000-04-04 02:05:59 +0000107
Greg Ward0d4a8532000-09-30 17:29:35 +0000108 Return a tuple (dest_name, copied): 'dest_name' is the actual name of
109 the output file, and 'copied' is true if the file was copied (or would
110 have been copied, if 'dry_run' true).
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000111 """
Greg Wardaebf7062000-04-04 02:05:59 +0000112 # XXX if the destination file already exists, we clobber it if
113 # copying, but blow up if linking. Hmmm. And I don't know what
114 # macostools.copyfile() does. Should definitely be consistent, and
115 # should probably blow up if destination exists and we would be
116 # changing it (ie. it's not already a hard/soft link to src OR
117 # (not update) and (src newer than dst).
118
Greg Wardaebf7062000-04-04 02:05:59 +0000119 from distutils.dep_util import newer
Greg Warde628a2f2001-07-25 19:48:03 +0000120 from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE
Greg Wardaebf7062000-04-04 02:05:59 +0000121
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000122 if not os.path.isfile(src):
Greg Wardaebf7062000-04-04 02:05:59 +0000123 raise DistutilsFileError, \
124 "can't copy '%s': doesn't exist or not a regular file" % src
125
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000126 if os.path.isdir(dst):
Greg Wardaebf7062000-04-04 02:05:59 +0000127 dir = dst
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000128 dst = os.path.join(dst, os.path.basename(src))
Greg Wardaebf7062000-04-04 02:05:59 +0000129 else:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000130 dir = os.path.dirname(dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000131
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000132 if update and not newer(src, dst):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000133 log.debug("not copying %s (output up-to-date)", src)
134 return dst, 0
Greg Wardaebf7062000-04-04 02:05:59 +0000135
136 try:
137 action = _copy_action[link]
138 except KeyError:
139 raise ValueError, \
140 "invalid value '%s' for 'link' argument" % link
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000141 if os.path.basename(dst) == os.path.basename(src):
142 log.info("%s %s -> %s", action, src, dir)
143 else:
144 log.info("%s %s -> %s", action, src, dst)
Fred Drakeb94b8492001-12-06 20:51:35 +0000145
Greg Wardaebf7062000-04-04 02:05:59 +0000146 if dry_run:
Greg Ward0d4a8532000-09-30 17:29:35 +0000147 return (dst, 1)
Greg Wardaebf7062000-04-04 02:05:59 +0000148
Greg Ward0d4a8532000-09-30 17:29:35 +0000149 # On Mac OS, use the native file copy routine
Greg Wardaebf7062000-04-04 02:05:59 +0000150 if os.name == 'mac':
151 import macostools
152 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000153 macostools.copy(src, dst, 0, preserve_times)
Guido van Rossumb940e112007-01-10 16:19:56 +0000154 except os.error as exc:
Greg Wardaebf7062000-04-04 02:05:59 +0000155 raise DistutilsFileError, \
156 "could not copy '%s' to '%s': %s" % (src, dst, exc[-1])
Fred Drakeb94b8492001-12-06 20:51:35 +0000157
Greg Wardaebf7062000-04-04 02:05:59 +0000158 # If linking (hard or symbolic), use the appropriate system call
159 # (Unix only, of course, but that's the caller's responsibility)
160 elif link == 'hard':
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000161 if not (os.path.exists(dst) and os.path.samefile(src, dst)):
162 os.link(src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000163 elif link == 'sym':
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000164 if not (os.path.exists(dst) and os.path.samefile(src, dst)):
165 os.symlink(src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000166
167 # Otherwise (non-Mac, not linking), copy the file contents and
168 # (optionally) copy the times and mode.
169 else:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000170 _copy_file_contents(src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000171 if preserve_mode or preserve_times:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000172 st = os.stat(src)
Greg Wardaebf7062000-04-04 02:05:59 +0000173
174 # According to David Ascher <da@ski.org>, utime() should be done
175 # before chmod() (at least under NT).
176 if preserve_times:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000177 os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
Greg Wardaebf7062000-04-04 02:05:59 +0000178 if preserve_mode:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000179 os.chmod(dst, S_IMODE(st[ST_MODE]))
Greg Wardaebf7062000-04-04 02:05:59 +0000180
Greg Ward0d4a8532000-09-30 17:29:35 +0000181 return (dst, 1)
Greg Wardaebf7062000-04-04 02:05:59 +0000182
183# copy_file ()
184
185
186# XXX I suspect this is Unix-specific -- need porting help!
187def move_file (src, dst,
188 verbose=0,
189 dry_run=0):
190
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000191 """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
192 be moved into it with the same name; otherwise, 'src' is just renamed
193 to 'dst'. Return the new full name of the file.
Greg Wardaebf7062000-04-04 02:05:59 +0000194
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000195 Handles cross-device moves on Unix using 'copy_file()'. What about
196 other systems???
197 """
Greg Wardaebf7062000-04-04 02:05:59 +0000198 from os.path import exists, isfile, isdir, basename, dirname
Andrew M. Kuchling106ffdb2001-08-09 20:59:53 +0000199 import errno
Fred Drakeb94b8492001-12-06 20:51:35 +0000200
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000201 log.info("moving %s -> %s", src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000202
203 if dry_run:
204 return dst
205
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000206 if not isfile(src):
Greg Wardaebf7062000-04-04 02:05:59 +0000207 raise DistutilsFileError, \
208 "can't move '%s': not a regular file" % src
209
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000210 if isdir(dst):
211 dst = os.path.join(dst, basename(src))
212 elif exists(dst):
Greg Wardaebf7062000-04-04 02:05:59 +0000213 raise DistutilsFileError, \
214 "can't move '%s': destination '%s' already exists" % \
215 (src, dst)
216
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000217 if not isdir(dirname(dst)):
Greg Wardaebf7062000-04-04 02:05:59 +0000218 raise DistutilsFileError, \
219 "can't move '%s': destination '%s' not a valid path" % \
220 (src, dst)
221
222 copy_it = 0
223 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000224 os.rename(src, dst)
Guido van Rossumb940e112007-01-10 16:19:56 +0000225 except os.error as e:
226 (num, msg) = e
Greg Wardaebf7062000-04-04 02:05:59 +0000227 if num == errno.EXDEV:
228 copy_it = 1
229 else:
230 raise DistutilsFileError, \
231 "couldn't move '%s' to '%s': %s" % (src, dst, msg)
232
233 if copy_it:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000234 copy_file(src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000235 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000236 os.unlink(src)
Guido van Rossumb940e112007-01-10 16:19:56 +0000237 except os.error as e:
238 (num, msg) = e
Greg Wardaebf7062000-04-04 02:05:59 +0000239 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000240 os.unlink(dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000241 except os.error:
242 pass
243 raise DistutilsFileError, \
Fred Drakeb94b8492001-12-06 20:51:35 +0000244 ("couldn't move '%s' to '%s' by copy/delete: " +
Greg Wardaebf7062000-04-04 02:05:59 +0000245 "delete '%s' failed: %s") % \
246 (src, dst, src, msg)
247
248 return dst
249
250# move_file ()
251
252
253def write_file (filename, contents):
254 """Create a file with the specified name and write 'contents' (a
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000255 sequence of strings without line terminators) to it.
256 """
257 f = open(filename, "w")
Greg Wardaebf7062000-04-04 02:05:59 +0000258 for line in contents:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000259 f.write(line + "\n")
260 f.close()