blob: 0c890559eee834245062bc5f923651bc86919f98 [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
Greg Wardaebf7062000-04-04 02:05:59 +00006__revision__ = "$Id$"
7
8import os
9from distutils.errors import DistutilsFileError
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000010from distutils import log
Greg Wardaebf7062000-04-04 02:05:59 +000011
12# for generating verbose output in 'copy_file()'
13_copy_action = { None: 'copying',
14 'hard': 'hard linking',
15 'sym': 'symbolically linking' }
16
17
18def _copy_file_contents (src, dst, buffer_size=16*1024):
19 """Copy the file 'src' to 'dst'; both must be filenames. Any error
Greg Ward9e3dc4e2000-09-23 00:59:34 +000020 opening either file, reading from 'src', or writing to 'dst', raises
21 DistutilsFileError. Data is read/written in chunks of 'buffer_size'
22 bytes (default 16k). No attempt is made to handle anything apart from
23 regular files.
24 """
Greg Wardaebf7062000-04-04 02:05:59 +000025 # Stolen from shutil module in the standard library, but with
26 # custom error-handling added.
27
28 fsrc = None
29 fdst = None
30 try:
31 try:
32 fsrc = open(src, 'rb')
33 except os.error, (errno, errstr):
34 raise DistutilsFileError, \
35 "could not open '%s': %s" % (src, errstr)
Fred Drakeb94b8492001-12-06 20:51:35 +000036
Andrew M. Kuchling3b388ec2002-02-01 18:29:34 +000037 if os.path.exists(dst):
38 try:
39 os.unlink(dst)
40 except os.error, (errno, errstr):
41 raise DistutilsFileError, \
42 "could not delete '%s': %s" % (dst, errstr)
Tim Peters182b5ac2004-07-18 06:16:08 +000043
Greg Wardaebf7062000-04-04 02:05:59 +000044 try:
45 fdst = open(dst, 'wb')
46 except os.error, (errno, errstr):
47 raise DistutilsFileError, \
48 "could not create '%s': %s" % (dst, errstr)
Fred Drakeb94b8492001-12-06 20:51:35 +000049
Greg Wardaebf7062000-04-04 02:05:59 +000050 while 1:
51 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +000052 buf = fsrc.read(buffer_size)
Greg Wardaebf7062000-04-04 02:05:59 +000053 except os.error, (errno, errstr):
54 raise DistutilsFileError, \
55 "could not read from '%s': %s" % (src, errstr)
Fred Drakeb94b8492001-12-06 20:51:35 +000056
Greg Wardaebf7062000-04-04 02:05:59 +000057 if not buf:
58 break
59
60 try:
61 fdst.write(buf)
62 except os.error, (errno, errstr):
63 raise DistutilsFileError, \
64 "could not write to '%s': %s" % (dst, errstr)
Fred Drakeb94b8492001-12-06 20:51:35 +000065
Greg Wardaebf7062000-04-04 02:05:59 +000066 finally:
67 if fdst:
68 fdst.close()
69 if fsrc:
70 fsrc.close()
71
72# _copy_file_contents()
73
Greg Wardaebf7062000-04-04 02:05:59 +000074def copy_file (src, dst,
75 preserve_mode=1,
76 preserve_times=1,
77 update=0,
78 link=None,
Tarek Ziadéd5eb9852009-02-06 00:31:59 +000079 verbose=1,
Greg Wardaebf7062000-04-04 02:05:59 +000080 dry_run=0):
81
Greg Ward9e3dc4e2000-09-23 00:59:34 +000082 """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is
83 copied there with the same name; otherwise, it must be a filename. (If
84 the file exists, it will be ruthlessly clobbered.) If 'preserve_mode'
85 is true (the default), the file's mode (type and permission bits, or
86 whatever is analogous on the current platform) is copied. If
87 'preserve_times' is true (the default), the last-modified and
88 last-access times are copied as well. If 'update' is true, 'src' will
89 only be copied if 'dst' does not exist, or if 'dst' does exist but is
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000090 older than 'src'.
Greg Wardaebf7062000-04-04 02:05:59 +000091
Greg Ward9e3dc4e2000-09-23 00:59:34 +000092 'link' allows you to make hard links (os.link) or symbolic links
93 (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
94 None (the default), files are copied. Don't set 'link' on systems that
95 don't support it: 'copy_file()' doesn't check if hard or symbolic
96 linking is available.
Greg Wardaebf7062000-04-04 02:05:59 +000097
Greg Ward9e3dc4e2000-09-23 00:59:34 +000098 Under Mac OS, uses the native file copy function in macostools; on
99 other systems, uses '_copy_file_contents()' to copy file contents.
Greg Wardaebf7062000-04-04 02:05:59 +0000100
Greg Ward0d4a8532000-09-30 17:29:35 +0000101 Return a tuple (dest_name, copied): 'dest_name' is the actual name of
102 the output file, and 'copied' is true if the file was copied (or would
103 have been copied, if 'dry_run' true).
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000104 """
Greg Wardaebf7062000-04-04 02:05:59 +0000105 # XXX if the destination file already exists, we clobber it if
106 # copying, but blow up if linking. Hmmm. And I don't know what
107 # macostools.copyfile() does. Should definitely be consistent, and
108 # should probably blow up if destination exists and we would be
109 # changing it (ie. it's not already a hard/soft link to src OR
110 # (not update) and (src newer than dst).
111
Greg Wardaebf7062000-04-04 02:05:59 +0000112 from distutils.dep_util import newer
Greg Warde628a2f2001-07-25 19:48:03 +0000113 from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE
Greg Wardaebf7062000-04-04 02:05:59 +0000114
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000115 if not os.path.isfile(src):
Greg Wardaebf7062000-04-04 02:05:59 +0000116 raise DistutilsFileError, \
117 "can't copy '%s': doesn't exist or not a regular file" % src
118
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000119 if os.path.isdir(dst):
Greg Wardaebf7062000-04-04 02:05:59 +0000120 dir = dst
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000121 dst = os.path.join(dst, os.path.basename(src))
Greg Wardaebf7062000-04-04 02:05:59 +0000122 else:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000123 dir = os.path.dirname(dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000124
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000125 if update and not newer(src, dst):
Tarek Ziadéaaf2e182009-02-06 00:49:45 +0000126 if verbose >= 1:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000127 log.debug("not copying %s (output up-to-date)", src)
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000128 return dst, 0
Greg Wardaebf7062000-04-04 02:05:59 +0000129
130 try:
131 action = _copy_action[link]
132 except KeyError:
133 raise ValueError, \
134 "invalid value '%s' for 'link' argument" % link
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000135
Tarek Ziadéaaf2e182009-02-06 00:49:45 +0000136 if verbose >= 1:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000137 if os.path.basename(dst) == os.path.basename(src):
138 log.info("%s %s -> %s", action, src, dir)
139 else:
140 log.info("%s %s -> %s", action, src, dst)
Fred Drakeb94b8492001-12-06 20:51:35 +0000141
Greg Wardaebf7062000-04-04 02:05:59 +0000142 if dry_run:
Greg Ward0d4a8532000-09-30 17:29:35 +0000143 return (dst, 1)
Greg Wardaebf7062000-04-04 02:05:59 +0000144
Greg Ward0d4a8532000-09-30 17:29:35 +0000145 # On Mac OS, use the native file copy routine
Greg Wardaebf7062000-04-04 02:05:59 +0000146 if os.name == 'mac':
147 import macostools
148 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000149 macostools.copy(src, dst, 0, preserve_times)
Greg Ward3af07e92000-04-22 15:17:14 +0000150 except os.error, exc:
Greg Wardaebf7062000-04-04 02:05:59 +0000151 raise DistutilsFileError, \
152 "could not copy '%s' to '%s': %s" % (src, dst, exc[-1])
Fred Drakeb94b8492001-12-06 20:51:35 +0000153
Greg Wardaebf7062000-04-04 02:05:59 +0000154 # If linking (hard or symbolic), use the appropriate system call
155 # (Unix only, of course, but that's the caller's responsibility)
156 elif link == 'hard':
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000157 if not (os.path.exists(dst) and os.path.samefile(src, dst)):
158 os.link(src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000159 elif link == 'sym':
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000160 if not (os.path.exists(dst) and os.path.samefile(src, dst)):
161 os.symlink(src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000162
163 # Otherwise (non-Mac, not linking), copy the file contents and
164 # (optionally) copy the times and mode.
165 else:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000166 _copy_file_contents(src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000167 if preserve_mode or preserve_times:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000168 st = os.stat(src)
Greg Wardaebf7062000-04-04 02:05:59 +0000169
170 # According to David Ascher <da@ski.org>, utime() should be done
171 # before chmod() (at least under NT).
172 if preserve_times:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000173 os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
Greg Wardaebf7062000-04-04 02:05:59 +0000174 if preserve_mode:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000175 os.chmod(dst, S_IMODE(st[ST_MODE]))
Greg Wardaebf7062000-04-04 02:05:59 +0000176
Greg Ward0d4a8532000-09-30 17:29:35 +0000177 return (dst, 1)
Greg Wardaebf7062000-04-04 02:05:59 +0000178
179# copy_file ()
180
181
182# XXX I suspect this is Unix-specific -- need porting help!
183def move_file (src, dst,
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000184 verbose=1,
Greg Wardaebf7062000-04-04 02:05:59 +0000185 dry_run=0):
186
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000187 """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
188 be moved into it with the same name; otherwise, 'src' is just renamed
189 to 'dst'. Return the new full name of the file.
Greg Wardaebf7062000-04-04 02:05:59 +0000190
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000191 Handles cross-device moves on Unix using 'copy_file()'. What about
192 other systems???
193 """
Greg Wardaebf7062000-04-04 02:05:59 +0000194 from os.path import exists, isfile, isdir, basename, dirname
Andrew M. Kuchling106ffdb2001-08-09 20:59:53 +0000195 import errno
Fred Drakeb94b8492001-12-06 20:51:35 +0000196
Tarek Ziadéaaf2e182009-02-06 00:49:45 +0000197 if verbose >= 1:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000198 log.info("moving %s -> %s", src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000199
200 if dry_run:
201 return dst
202
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000203 if not isfile(src):
Greg Wardaebf7062000-04-04 02:05:59 +0000204 raise DistutilsFileError, \
205 "can't move '%s': not a regular file" % src
206
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000207 if isdir(dst):
208 dst = os.path.join(dst, basename(src))
209 elif exists(dst):
Greg Wardaebf7062000-04-04 02:05:59 +0000210 raise DistutilsFileError, \
211 "can't move '%s': destination '%s' already exists" % \
212 (src, dst)
213
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000214 if not isdir(dirname(dst)):
Greg Wardaebf7062000-04-04 02:05:59 +0000215 raise DistutilsFileError, \
216 "can't move '%s': destination '%s' not a valid path" % \
217 (src, dst)
218
219 copy_it = 0
220 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000221 os.rename(src, dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000222 except os.error, (num, msg):
223 if num == errno.EXDEV:
224 copy_it = 1
225 else:
226 raise DistutilsFileError, \
227 "couldn't move '%s' to '%s': %s" % (src, dst, msg)
228
229 if copy_it:
Tarek Ziadéd5eb9852009-02-06 00:31:59 +0000230 copy_file(src, dst, verbose=verbose)
Greg Wardaebf7062000-04-04 02:05:59 +0000231 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000232 os.unlink(src)
Greg Wardaebf7062000-04-04 02:05:59 +0000233 except os.error, (num, msg):
234 try:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000235 os.unlink(dst)
Greg Wardaebf7062000-04-04 02:05:59 +0000236 except os.error:
237 pass
238 raise DistutilsFileError, \
Fred Drakeb94b8492001-12-06 20:51:35 +0000239 ("couldn't move '%s' to '%s' by copy/delete: " +
Greg Wardaebf7062000-04-04 02:05:59 +0000240 "delete '%s' failed: %s") % \
241 (src, dst, src, msg)
242
243 return dst
244
245# move_file ()
246
247
248def write_file (filename, contents):
249 """Create a file with the specified name and write 'contents' (a
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000250 sequence of strings without line terminators) to it.
251 """
252 f = open(filename, "w")
Greg Wardaebf7062000-04-04 02:05:59 +0000253 for line in contents:
Greg Ward9e3dc4e2000-09-23 00:59:34 +0000254 f.write(line + "\n")
255 f.close()