file.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # file.py -- Safe access to git files
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License or (at your option) a later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Safe access to git files."""
  19. import errno
  20. import os
  21. import tempfile
  22. import io
  23. def ensure_dir_exists(dirname):
  24. """Ensure a directory exists, creating if necessary."""
  25. try:
  26. os.makedirs(dirname)
  27. except OSError as e:
  28. if e.errno != errno.EEXIST:
  29. raise
  30. def fancy_rename(oldname, newname):
  31. """Rename file with temporary backup file to rollback if rename fails"""
  32. if not os.path.exists(newname):
  33. try:
  34. os.rename(oldname, newname)
  35. except OSError:
  36. raise
  37. return
  38. # destination file exists
  39. try:
  40. (fd, tmpfile) = tempfile.mkstemp(".tmp", prefix=oldname+".", dir=".")
  41. os.close(fd)
  42. os.remove(tmpfile)
  43. except OSError:
  44. # either file could not be created (e.g. permission problem)
  45. # or could not be deleted (e.g. rude virus scanner)
  46. raise
  47. try:
  48. os.rename(newname, tmpfile)
  49. except OSError:
  50. raise # no rename occurred
  51. try:
  52. os.rename(oldname, newname)
  53. except OSError:
  54. os.rename(tmpfile, newname)
  55. raise
  56. os.remove(tmpfile)
  57. def GitFile(filename, mode='rb', bufsize=-1):
  58. """Create a file object that obeys the git file locking protocol.
  59. :return: a builtin file object or a _GitFile object
  60. :note: See _GitFile for a description of the file locking protocol.
  61. Only read-only and write-only (binary) modes are supported; r+, w+, and a
  62. are not. To read and write from the same file, you can take advantage of
  63. the fact that opening a file for write does not actually open the file you
  64. request.
  65. """
  66. if 'a' in mode:
  67. raise IOError('append mode not supported for Git files')
  68. if '+' in mode:
  69. raise IOError('read/write mode not supported for Git files')
  70. if 'b' not in mode:
  71. raise IOError('text mode not supported for Git files')
  72. if 'w' in mode:
  73. return _GitFile(filename, mode, bufsize)
  74. else:
  75. return io.open(filename, mode, bufsize)
  76. class _GitFile(object):
  77. """File that follows the git locking protocol for writes.
  78. All writes to a file foo will be written into foo.lock in the same
  79. directory, and the lockfile will be renamed to overwrite the original file
  80. on close.
  81. :note: You *must* call close() or abort() on a _GitFile for the lock to be
  82. released. Typically this will happen in a finally block.
  83. """
  84. PROXY_PROPERTIES = set(['closed', 'encoding', 'errors', 'mode', 'name',
  85. 'newlines', 'softspace'])
  86. PROXY_METHODS = ('__iter__', 'flush', 'fileno', 'isatty', 'read',
  87. 'readline', 'readlines', 'seek', 'tell',
  88. 'truncate', 'write', 'writelines')
  89. def __init__(self, filename, mode, bufsize):
  90. self._filename = filename
  91. self._lockfilename = '%s.lock' % self._filename
  92. fd = os.open(self._lockfilename,
  93. os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0))
  94. self._file = os.fdopen(fd, mode, bufsize)
  95. self._closed = False
  96. for method in self.PROXY_METHODS:
  97. setattr(self, method, getattr(self._file, method))
  98. def abort(self):
  99. """Close and discard the lockfile without overwriting the target.
  100. If the file is already closed, this is a no-op.
  101. """
  102. if self._closed:
  103. return
  104. self._file.close()
  105. try:
  106. os.remove(self._lockfilename)
  107. self._closed = True
  108. except OSError as e:
  109. # The file may have been removed already, which is ok.
  110. if e.errno != errno.ENOENT:
  111. raise
  112. self._closed = True
  113. def close(self):
  114. """Close this file, saving the lockfile over the original.
  115. :note: If this method fails, it will attempt to delete the lockfile.
  116. However, it is not guaranteed to do so (e.g. if a filesystem becomes
  117. suddenly read-only), which will prevent future writes to this file
  118. until the lockfile is removed manually.
  119. :raises OSError: if the original file could not be overwritten. The lock
  120. file is still closed, so further attempts to write to the same file
  121. object will raise ValueError.
  122. """
  123. if self._closed:
  124. return
  125. self._file.close()
  126. try:
  127. try:
  128. os.rename(self._lockfilename, self._filename)
  129. except OSError as e:
  130. # Windows versions prior to Vista don't support atomic renames
  131. if e.errno != errno.EEXIST:
  132. raise
  133. fancy_rename(self._lockfilename, self._filename)
  134. finally:
  135. self.abort()
  136. def __enter__(self):
  137. return self
  138. def __exit__(self, exc_type, exc_val, exc_tb):
  139. self.close()
  140. def __getattr__(self, name):
  141. """Proxy property calls to the underlying file."""
  142. if name in self.PROXY_PROPERTIES:
  143. return getattr(self._file, name)
  144. raise AttributeError(name)