file_util.py 8.0 KB

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