file_util.py 7.9 KB

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