ยปCore Development>Code coverage>Lib/distutils/file_util.py

Python code coverage for Lib/distutils/file_util.py

#countcontent
1n/a"""distutils.file_util
2n/a
3n/aUtility functions for operating on single files.
4n/a"""
5n/a
6n/aimport os
7n/afrom distutils.errors import DistutilsFileError
8n/afrom distutils import log
9n/a
10n/a# for generating verbose output in 'copy_file()'
11n/a_copy_action = { None: 'copying',
12n/a 'hard': 'hard linking',
13n/a 'sym': 'symbolically linking' }
14n/a
15n/a
16n/adef _copy_file_contents(src, dst, buffer_size=16*1024):
17n/a """Copy the file 'src' to 'dst'; both must be filenames. Any error
18n/a opening either file, reading from 'src', or writing to 'dst', raises
19n/a DistutilsFileError. Data is read/written in chunks of 'buffer_size'
20n/a bytes (default 16k). No attempt is made to handle anything apart from
21n/a regular files.
22n/a """
23n/a # Stolen from shutil module in the standard library, but with
24n/a # custom error-handling added.
25n/a fsrc = None
26n/a fdst = None
27n/a try:
28n/a try:
29n/a fsrc = open(src, 'rb')
30n/a except OSError as e:
31n/a raise DistutilsFileError("could not open '%s': %s" % (src, e.strerror))
32n/a
33n/a if os.path.exists(dst):
34n/a try:
35n/a os.unlink(dst)
36n/a except OSError as e:
37n/a raise DistutilsFileError(
38n/a "could not delete '%s': %s" % (dst, e.strerror))
39n/a
40n/a try:
41n/a fdst = open(dst, 'wb')
42n/a except OSError as e:
43n/a raise DistutilsFileError(
44n/a "could not create '%s': %s" % (dst, e.strerror))
45n/a
46n/a while True:
47n/a try:
48n/a buf = fsrc.read(buffer_size)
49n/a except OSError as e:
50n/a raise DistutilsFileError(
51n/a "could not read from '%s': %s" % (src, e.strerror))
52n/a
53n/a if not buf:
54n/a break
55n/a
56n/a try:
57n/a fdst.write(buf)
58n/a except OSError as e:
59n/a raise DistutilsFileError(
60n/a "could not write to '%s': %s" % (dst, e.strerror))
61n/a finally:
62n/a if fdst:
63n/a fdst.close()
64n/a if fsrc:
65n/a fsrc.close()
66n/a
67n/adef copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
68n/a link=None, verbose=1, dry_run=0):
69n/a """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is
70n/a copied there with the same name; otherwise, it must be a filename. (If
71n/a the file exists, it will be ruthlessly clobbered.) If 'preserve_mode'
72n/a is true (the default), the file's mode (type and permission bits, or
73n/a whatever is analogous on the current platform) is copied. If
74n/a 'preserve_times' is true (the default), the last-modified and
75n/a last-access times are copied as well. If 'update' is true, 'src' will
76n/a only be copied if 'dst' does not exist, or if 'dst' does exist but is
77n/a older than 'src'.
78n/a
79n/a 'link' allows you to make hard links (os.link) or symbolic links
80n/a (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
81n/a None (the default), files are copied. Don't set 'link' on systems that
82n/a don't support it: 'copy_file()' doesn't check if hard or symbolic
83n/a linking is available. If hardlink fails, falls back to
84n/a _copy_file_contents().
85n/a
86n/a Under Mac OS, uses the native file copy function in macostools; on
87n/a other systems, uses '_copy_file_contents()' to copy file contents.
88n/a
89n/a Return a tuple (dest_name, copied): 'dest_name' is the actual name of
90n/a the output file, and 'copied' is true if the file was copied (or would
91n/a have been copied, if 'dry_run' true).
92n/a """
93n/a # XXX if the destination file already exists, we clobber it if
94n/a # copying, but blow up if linking. Hmmm. And I don't know what
95n/a # macostools.copyfile() does. Should definitely be consistent, and
96n/a # should probably blow up if destination exists and we would be
97n/a # changing it (ie. it's not already a hard/soft link to src OR
98n/a # (not update) and (src newer than dst).
99n/a
100n/a from distutils.dep_util import newer
101n/a from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE
102n/a
103n/a if not os.path.isfile(src):
104n/a raise DistutilsFileError(
105n/a "can't copy '%s': doesn't exist or not a regular file" % src)
106n/a
107n/a if os.path.isdir(dst):
108n/a dir = dst
109n/a dst = os.path.join(dst, os.path.basename(src))
110n/a else:
111n/a dir = os.path.dirname(dst)
112n/a
113n/a if update and not newer(src, dst):
114n/a if verbose >= 1:
115n/a log.debug("not copying %s (output up-to-date)", src)
116n/a return (dst, 0)
117n/a
118n/a try:
119n/a action = _copy_action[link]
120n/a except KeyError:
121n/a raise ValueError("invalid value '%s' for 'link' argument" % link)
122n/a
123n/a if verbose >= 1:
124n/a if os.path.basename(dst) == os.path.basename(src):
125n/a log.info("%s %s -> %s", action, src, dir)
126n/a else:
127n/a log.info("%s %s -> %s", action, src, dst)
128n/a
129n/a if dry_run:
130n/a return (dst, 1)
131n/a
132n/a # If linking (hard or symbolic), use the appropriate system call
133n/a # (Unix only, of course, but that's the caller's responsibility)
134n/a elif link == 'hard':
135n/a if not (os.path.exists(dst) and os.path.samefile(src, dst)):
136n/a try:
137n/a os.link(src, dst)
138n/a return (dst, 1)
139n/a except OSError:
140n/a # If hard linking fails, fall back on copying file
141n/a # (some special filesystems don't support hard linking
142n/a # even under Unix, see issue #8876).
143n/a pass
144n/a elif link == 'sym':
145n/a if not (os.path.exists(dst) and os.path.samefile(src, dst)):
146n/a os.symlink(src, dst)
147n/a return (dst, 1)
148n/a
149n/a # Otherwise (non-Mac, not linking), copy the file contents and
150n/a # (optionally) copy the times and mode.
151n/a _copy_file_contents(src, dst)
152n/a if preserve_mode or preserve_times:
153n/a st = os.stat(src)
154n/a
155n/a # According to David Ascher <da@ski.org>, utime() should be done
156n/a # before chmod() (at least under NT).
157n/a if preserve_times:
158n/a os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
159n/a if preserve_mode:
160n/a os.chmod(dst, S_IMODE(st[ST_MODE]))
161n/a
162n/a return (dst, 1)
163n/a
164n/a
165n/a# XXX I suspect this is Unix-specific -- need porting help!
166n/adef move_file (src, dst,
167n/a verbose=1,
168n/a dry_run=0):
169n/a
170n/a """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
171n/a be moved into it with the same name; otherwise, 'src' is just renamed
172n/a to 'dst'. Return the new full name of the file.
173n/a
174n/a Handles cross-device moves on Unix using 'copy_file()'. What about
175n/a other systems???
176n/a """
177n/a from os.path import exists, isfile, isdir, basename, dirname
178n/a import errno
179n/a
180n/a if verbose >= 1:
181n/a log.info("moving %s -> %s", src, dst)
182n/a
183n/a if dry_run:
184n/a return dst
185n/a
186n/a if not isfile(src):
187n/a raise DistutilsFileError("can't move '%s': not a regular file" % src)
188n/a
189n/a if isdir(dst):
190n/a dst = os.path.join(dst, basename(src))
191n/a elif exists(dst):
192n/a raise DistutilsFileError(
193n/a "can't move '%s': destination '%s' already exists" %
194n/a (src, dst))
195n/a
196n/a if not isdir(dirname(dst)):
197n/a raise DistutilsFileError(
198n/a "can't move '%s': destination '%s' not a valid path" %
199n/a (src, dst))
200n/a
201n/a copy_it = False
202n/a try:
203n/a os.rename(src, dst)
204n/a except OSError as e:
205n/a (num, msg) = e.args
206n/a if num == errno.EXDEV:
207n/a copy_it = True
208n/a else:
209n/a raise DistutilsFileError(
210n/a "couldn't move '%s' to '%s': %s" % (src, dst, msg))
211n/a
212n/a if copy_it:
213n/a copy_file(src, dst, verbose=verbose)
214n/a try:
215n/a os.unlink(src)
216n/a except OSError as e:
217n/a (num, msg) = e.args
218n/a try:
219n/a os.unlink(dst)
220n/a except OSError:
221n/a pass
222n/a raise DistutilsFileError(
223n/a "couldn't move '%s' to '%s' by copy/delete: "
224n/a "delete '%s' failed: %s"
225n/a % (src, dst, src, msg))
226n/a return dst
227n/a
228n/a
229n/adef write_file (filename, contents):
230n/a """Create a file with the specified name and write 'contents' (a
231n/a sequence of strings without line terminators) to it.
232n/a """
233n/a f = open(filename, "w")
234n/a try:
235n/a for line in contents:
236n/a f.write(line + "\n")
237n/a finally:
238n/a f.close()