file_util.py 7.96 KB
Newer Older
1 2
"""distutils.file_util

Greg Ward's avatar
Greg Ward committed
3 4
Utility functions for operating on single files.
"""
5 6 7

import os
from distutils.errors import DistutilsFileError
8
from distutils import log
9 10

# for generating verbose output in 'copy_file()'
11 12 13
_copy_action = { None:   'copying',
                 'hard': 'hard linking',
                 'sym':  'symbolically linking' }
14 15


16
def _copy_file_contents(src, dst, buffer_size=16*1024):
17 18 19 20 21
    """Copy the file 'src' to 'dst'; both must be filenames.  Any error
    opening either file, reading from 'src', or writing to 'dst', raises
    DistutilsFileError.  Data is read/written in chunks of 'buffer_size'
    bytes (default 16k).  No attempt is made to handle anything apart from
    regular files.
Greg Ward's avatar
Greg Ward committed
22
    """
23 24 25 26 27 28 29
    # Stolen from shutil module in the standard library, but with
    # custom error-handling added.
    fsrc = None
    fdst = None
    try:
        try:
            fsrc = open(src, 'rb')
30
        except OSError as e:
31
            raise DistutilsFileError("could not open '%s': %s" % (src, e.strerror))
Fred Drake's avatar
Fred Drake committed
32

33 34 35
        if os.path.exists(dst):
            try:
                os.unlink(dst)
36
            except OSError as e:
37
                raise DistutilsFileError(
38
                      "could not delete '%s': %s" % (dst, e.strerror))
39

40 41
        try:
            fdst = open(dst, 'wb')
42
        except OSError as e:
43
            raise DistutilsFileError(
44
                  "could not create '%s': %s" % (dst, e.strerror))
Fred Drake's avatar
Fred Drake committed
45

46
        while True:
47
            try:
Greg Ward's avatar
Greg Ward committed
48
                buf = fsrc.read(buffer_size)
49
            except OSError as e:
50
                raise DistutilsFileError(
51
                      "could not read from '%s': %s" % (src, e.strerror))
Fred Drake's avatar
Fred Drake committed
52

53 54 55 56 57
            if not buf:
                break

            try:
                fdst.write(buf)
58
            except OSError as e:
59
                raise DistutilsFileError(
60
                      "could not write to '%s': %s" % (dst, e.strerror))
61 62 63 64 65 66
    finally:
        if fdst:
            fdst.close()
        if fsrc:
            fsrc.close()

67
def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
68
              link=None, verbose=1, dry_run=0):
69 70 71 72 73 74 75 76 77
    """Copy a file 'src' to 'dst'.  If 'dst' is a directory, then 'src' is
    copied there with the same name; otherwise, it must be a filename.  (If
    the file exists, it will be ruthlessly clobbered.)  If 'preserve_mode'
    is true (the default), the file's mode (type and permission bits, or
    whatever is analogous on the current platform) is copied.  If
    'preserve_times' is true (the default), the last-modified and
    last-access times are copied as well.  If 'update' is true, 'src' will
    only be copied if 'dst' does not exist, or if 'dst' does exist but is
    older than 'src'.
Greg Ward's avatar
Greg Ward committed
78 79 80 81 82

    'link' allows you to make hard links (os.link) or symbolic links
    (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
    None (the default), files are copied.  Don't set 'link' on systems that
    don't support it: 'copy_file()' doesn't check if hard or symbolic
83 84
    linking is available. If hardlink fails, falls back to
    _copy_file_contents().
Greg Ward's avatar
Greg Ward committed
85 86 87 88

    Under Mac OS, uses the native file copy function in macostools; on
    other systems, uses '_copy_file_contents()' to copy file contents.

89 90 91
    Return a tuple (dest_name, copied): 'dest_name' is the actual name of
    the output file, and 'copied' is true if the file was copied (or would
    have been copied, if 'dry_run' true).
Greg Ward's avatar
Greg Ward committed
92
    """
93 94 95 96 97 98 99 100
    # XXX if the destination file already exists, we clobber it if
    # copying, but blow up if linking.  Hmmm.  And I don't know what
    # macostools.copyfile() does.  Should definitely be consistent, and
    # should probably blow up if destination exists and we would be
    # changing it (ie. it's not already a hard/soft link to src OR
    # (not update) and (src newer than dst).

    from distutils.dep_util import newer
101
    from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE
102

Greg Ward's avatar
Greg Ward committed
103
    if not os.path.isfile(src):
104 105
        raise DistutilsFileError(
              "can't copy '%s': doesn't exist or not a regular file" % src)
106

Greg Ward's avatar
Greg Ward committed
107
    if os.path.isdir(dst):
108
        dir = dst
Greg Ward's avatar
Greg Ward committed
109
        dst = os.path.join(dst, os.path.basename(src))
110
    else:
Greg Ward's avatar
Greg Ward committed
111
        dir = os.path.dirname(dst)
112

Greg Ward's avatar
Greg Ward committed
113
    if update and not newer(src, dst):
114
        if verbose >= 1:
115
            log.debug("not copying %s (output up-to-date)", src)
116
        return (dst, 0)
117 118 119 120

    try:
        action = _copy_action[link]
    except KeyError:
121
        raise ValueError("invalid value '%s' for 'link' argument" % link)
122

123
    if verbose >= 1:
124 125 126 127
        if os.path.basename(dst) == os.path.basename(src):
            log.info("%s %s -> %s", action, src, dir)
        else:
            log.info("%s %s -> %s", action, src, dst)
Fred Drake's avatar
Fred Drake committed
128

129
    if dry_run:
130
        return (dst, 1)
131 132 133 134

    # If linking (hard or symbolic), use the appropriate system call
    # (Unix only, of course, but that's the caller's responsibility)
    elif link == 'hard':
Greg Ward's avatar
Greg Ward committed
135
        if not (os.path.exists(dst) and os.path.samefile(src, dst)):
136 137 138 139 140 141 142 143
            try:
                os.link(src, dst)
                return (dst, 1)
            except OSError:
                # If hard linking fails, fall back on copying file
                # (some special filesystems don't support hard linking
                #  even under Unix, see issue #8876).
                pass
144
    elif link == 'sym':
Greg Ward's avatar
Greg Ward committed
145 146
        if not (os.path.exists(dst) and os.path.samefile(src, dst)):
            os.symlink(src, dst)
147
            return (dst, 1)
148 149 150

    # Otherwise (non-Mac, not linking), copy the file contents and
    # (optionally) copy the times and mode.
151 152 153 154 155 156 157 158 159 160
    _copy_file_contents(src, dst)
    if preserve_mode or preserve_times:
        st = os.stat(src)

        # According to David Ascher <da@ski.org>, utime() should be done
        # before chmod() (at least under NT).
        if preserve_times:
            os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
        if preserve_mode:
            os.chmod(dst, S_IMODE(st[ST_MODE]))
161

162
    return (dst, 1)
163 164 165


# XXX I suspect this is Unix-specific -- need porting help!
166 167 168
def move_file (src, dst,
               verbose=1,
               dry_run=0):
169

170 171 172
    """Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
    be moved into it with the same name; otherwise, 'src' is just renamed
    to 'dst'.  Return the new full name of the file.
173

Greg Ward's avatar
Greg Ward committed
174 175 176
    Handles cross-device moves on Unix using 'copy_file()'.  What about
    other systems???
    """
177
    from os.path import exists, isfile, isdir, basename, dirname
178
    import errno
Fred Drake's avatar
Fred Drake committed
179

180
    if verbose >= 1:
181
        log.info("moving %s -> %s", src, dst)
182 183 184 185

    if dry_run:
        return dst

Greg Ward's avatar
Greg Ward committed
186
    if not isfile(src):
187
        raise DistutilsFileError("can't move '%s': not a regular file" % src)
188

Greg Ward's avatar
Greg Ward committed
189 190 191
    if isdir(dst):
        dst = os.path.join(dst, basename(src))
    elif exists(dst):
192 193 194
        raise DistutilsFileError(
              "can't move '%s': destination '%s' already exists" %
              (src, dst))
195

Greg Ward's avatar
Greg Ward committed
196
    if not isdir(dirname(dst)):
197 198 199
        raise DistutilsFileError(
              "can't move '%s': destination '%s' not a valid path" %
              (src, dst))
200

201
    copy_it = False
202
    try:
Greg Ward's avatar
Greg Ward committed
203
        os.rename(src, dst)
204
    except OSError as e:
205
        (num, msg) = e.args
206
        if num == errno.EXDEV:
207
            copy_it = True
208
        else:
209 210
            raise DistutilsFileError(
                  "couldn't move '%s' to '%s': %s" % (src, dst, msg))
211 212

    if copy_it:
213
        copy_file(src, dst, verbose=verbose)
214
        try:
Greg Ward's avatar
Greg Ward committed
215
            os.unlink(src)
216
        except OSError as e:
217
            (num, msg) = e.args
218
            try:
Greg Ward's avatar
Greg Ward committed
219
                os.unlink(dst)
220
            except OSError:
221
                pass
222 223 224 225
            raise DistutilsFileError(
                  "couldn't move '%s' to '%s' by copy/delete: "
                  "delete '%s' failed: %s"
                  % (src, dst, src, msg))
226 227 228
    return dst


229
def write_file (filename, contents):
230
    """Create a file with the specified name and write 'contents' (a
Greg Ward's avatar
Greg Ward committed
231 232 233
    sequence of strings without line terminators) to it.
    """
    f = open(filename, "w")
234 235 236 237 238
    try:
        for line in contents:
            f.write(line + "\n")
    finally:
        f.close()