file_util.py 8.0 KB

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