You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

232 lines
7.6 KiB

26 years ago
  1. """distutils.file_util
  2. Utility functions for operating on single files.
  3. """
  4. __revision__ = "$Id$"
  5. import os
  6. from distutils.errors import DistutilsFileError
  7. from distutils import log
  8. # for generating verbose output in 'copy_file()'
  9. _copy_action = { None: 'copying',
  10. 'hard': 'hard linking',
  11. 'sym': 'symbolically linking' }
  12. def _copy_file_contents(src, dst, buffer_size=16*1024):
  13. """Copy the file 'src' to 'dst'; both must be filenames. Any error
  14. opening either file, reading from 'src', or writing to 'dst', raises
  15. DistutilsFileError. Data is read/written in chunks of 'buffer_size'
  16. bytes (default 16k). No attempt is made to handle anything apart from
  17. regular files.
  18. """
  19. # Stolen from shutil module in the standard library, but with
  20. # custom error-handling added.
  21. fsrc = None
  22. fdst = None
  23. try:
  24. try:
  25. fsrc = open(src, 'rb')
  26. except os.error as e:
  27. raise DistutilsFileError("could not open '%s': %s" % (src, e.strerror))
  28. if os.path.exists(dst):
  29. try:
  30. os.unlink(dst)
  31. except os.error as e:
  32. raise DistutilsFileError(
  33. "could not delete '%s': %s" % (dst, e.strerror))
  34. try:
  35. fdst = open(dst, 'wb')
  36. except os.error as e:
  37. raise DistutilsFileError(
  38. "could not create '%s': %s" % (dst, e.strerror))
  39. while True:
  40. try:
  41. buf = fsrc.read(buffer_size)
  42. except os.error as e:
  43. raise DistutilsFileError(
  44. "could not read from '%s': %s" % (src, e.strerror))
  45. if not buf:
  46. break
  47. try:
  48. fdst.write(buf)
  49. except os.error as e:
  50. raise DistutilsFileError(
  51. "could not write to '%s': %s" % (dst, e.strerror))
  52. finally:
  53. if fdst:
  54. fdst.close()
  55. if fsrc:
  56. fsrc.close()
  57. def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
  58. link=None, verbose=1, dry_run=0):
  59. """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is
  60. copied there with the same name; otherwise, it must be a filename. (If
  61. the file exists, it will be ruthlessly clobbered.) If 'preserve_mode'
  62. is true (the default), the file's mode (type and permission bits, or
  63. whatever is analogous on the current platform) is copied. If
  64. 'preserve_times' is true (the default), the last-modified and
  65. last-access times are copied as well. If 'update' is true, 'src' will
  66. only be copied if 'dst' does not exist, or if 'dst' does exist but is
  67. older than 'src'.
  68. 'link' allows you to make hard links (os.link) or symbolic links
  69. (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
  70. None (the default), files are copied. Don't set 'link' on systems that
  71. don't support it: 'copy_file()' doesn't check if hard or symbolic
  72. linking is available.
  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. os.link(src, dst)
  115. elif link == 'sym':
  116. if not (os.path.exists(dst) and os.path.samefile(src, dst)):
  117. os.symlink(src, dst)
  118. # Otherwise (non-Mac, not linking), copy the file contents and
  119. # (optionally) copy the times and mode.
  120. else:
  121. _copy_file_contents(src, dst)
  122. if preserve_mode or preserve_times:
  123. st = os.stat(src)
  124. # According to David Ascher <da@ski.org>, utime() should be done
  125. # before chmod() (at least under NT).
  126. if preserve_times:
  127. os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
  128. if preserve_mode:
  129. os.chmod(dst, S_IMODE(st[ST_MODE]))
  130. return (dst, 1)
  131. # XXX I suspect this is Unix-specific -- need porting help!
  132. def move_file (src, dst,
  133. verbose=1,
  134. dry_run=0):
  135. """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
  136. be moved into it with the same name; otherwise, 'src' is just renamed
  137. to 'dst'. Return the new full name of the file.
  138. Handles cross-device moves on Unix using 'copy_file()'. What about
  139. other systems???
  140. """
  141. from os.path import exists, isfile, isdir, basename, dirname
  142. import errno
  143. if verbose >= 1:
  144. log.info("moving %s -> %s", src, dst)
  145. if dry_run:
  146. return dst
  147. if not isfile(src):
  148. raise DistutilsFileError("can't move '%s': not a regular file" % src)
  149. if isdir(dst):
  150. dst = os.path.join(dst, basename(src))
  151. elif exists(dst):
  152. raise DistutilsFileError(
  153. "can't move '%s': destination '%s' already exists" %
  154. (src, dst))
  155. if not isdir(dirname(dst)):
  156. raise DistutilsFileError(
  157. "can't move '%s': destination '%s' not a valid path" %
  158. (src, dst))
  159. copy_it = False
  160. try:
  161. os.rename(src, dst)
  162. except os.error as e:
  163. (num, msg) = e
  164. if num == errno.EXDEV:
  165. copy_it = True
  166. else:
  167. raise DistutilsFileError(
  168. "couldn't move '%s' to '%s': %s" % (src, dst, msg))
  169. if copy_it:
  170. copy_file(src, dst, verbose=verbose)
  171. try:
  172. os.unlink(src)
  173. except os.error as e:
  174. (num, msg) = e
  175. try:
  176. os.unlink(dst)
  177. except os.error:
  178. pass
  179. raise DistutilsFileError(
  180. "couldn't move '%s' to '%s' by copy/delete: "
  181. "delete '%s' failed: %s"
  182. % (src, dst, src, msg))
  183. return dst
  184. def write_file (filename, contents):
  185. """Create a file with the specified name and write 'contents' (a
  186. sequence of strings without line terminators) to it.
  187. """
  188. f = open(filename, "w")
  189. try:
  190. for line in contents:
  191. f.write(line + "\n")
  192. finally:
  193. f.close()