PageRenderTime 45ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/modified-2.7/distutils/file_util.py

https://bitbucket.org/dac_io/pypy
Python | 231 lines | 197 code | 18 blank | 16 comment | 32 complexity | b6cc97716fed7208d5461c818cbbb4cc MD5 | raw file
  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'.
  14. Both must be filenames. Any error opening either file, reading from
  15. 'src', or writing to 'dst', raises DistutilsFileError. Data is
  16. read/written in chunks of 'buffer_size' bytes (default 16k). No attempt
  17. is made to handle anything apart from 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, (errno, errstr):
  27. raise DistutilsFileError("could not open '%s': %s" % (src, errstr))
  28. if os.path.exists(dst):
  29. try:
  30. os.unlink(dst)
  31. except os.error, (errno, errstr):
  32. raise DistutilsFileError(
  33. "could not delete '%s': %s" % (dst, errstr))
  34. try:
  35. fdst = open(dst, 'wb')
  36. except os.error, (errno, errstr):
  37. raise DistutilsFileError(
  38. "could not create '%s': %s" % (dst, errstr))
  39. while 1:
  40. try:
  41. buf = fsrc.read(buffer_size)
  42. except os.error, (errno, errstr):
  43. raise DistutilsFileError(
  44. "could not read from '%s': %s" % (src, errstr))
  45. if not buf:
  46. break
  47. try:
  48. fdst.write(buf)
  49. except os.error, (errno, errstr):
  50. raise DistutilsFileError(
  51. "could not write to '%s': %s" % (dst, errstr))
  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'.
  60. If 'dst' is a directory, then 'src' is copied there with the same name;
  61. otherwise, it must be a filename. (If the file exists, it will be
  62. ruthlessly clobbered.) If 'preserve_mode' is true (the default),
  63. the file's mode (type and permission bits, or whatever is analogous on
  64. the current platform) is copied. If 'preserve_times' is true (the
  65. default), the last-modified and last-access times are copied as well.
  66. If 'update' is true, 'src' will only be copied if 'dst' does not exist,
  67. or if 'dst' does exist but is 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. if 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, verbose=1, dry_run=0):
  133. """Move a file 'src' to 'dst'.
  134. If 'dst' is a directory, the file will be moved into it with the same
  135. name; otherwise, 'src' is just renamed to 'dst'. Return the new
  136. full name of the file.
  137. Handles cross-device moves on Unix using 'copy_file()'. What about
  138. other systems???
  139. """
  140. from os.path import exists, isfile, isdir, basename, dirname
  141. import errno
  142. if verbose >= 1:
  143. log.info("moving %s -> %s", src, dst)
  144. if dry_run:
  145. return dst
  146. if not isfile(src):
  147. raise DistutilsFileError("can't move '%s': not a regular file" % src)
  148. if isdir(dst):
  149. dst = os.path.join(dst, basename(src))
  150. elif exists(dst):
  151. raise DistutilsFileError(
  152. "can't move '%s': destination '%s' already exists" %
  153. (src, dst))
  154. if not isdir(dirname(dst)):
  155. raise DistutilsFileError(
  156. "can't move '%s': destination '%s' not a valid path" % \
  157. (src, dst))
  158. copy_it = 0
  159. try:
  160. os.rename(src, dst)
  161. except os.error, (num, msg):
  162. if num == errno.EXDEV:
  163. copy_it = 1
  164. else:
  165. raise DistutilsFileError(
  166. "couldn't move '%s' to '%s': %s" % (src, dst, msg))
  167. if copy_it:
  168. copy_file(src, dst, verbose=verbose)
  169. try:
  170. os.unlink(src)
  171. except os.error, (num, msg):
  172. try:
  173. os.unlink(dst)
  174. except os.error:
  175. pass
  176. raise DistutilsFileError(
  177. ("couldn't move '%s' to '%s' by copy/delete: " +
  178. "delete '%s' failed: %s") %
  179. (src, dst, src, msg))
  180. return dst
  181. def write_file (filename, contents):
  182. """Create a file with the specified name and write 'contents' (a
  183. sequence of strings without line terminators) to it.
  184. """
  185. f = open(filename, "w")
  186. try:
  187. for line in contents:
  188. f.write(line + "\n")
  189. finally:
  190. f.close()