file.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # file.py -- Safe access to git files
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Safe access to git files."""
  21. import io
  22. import os
  23. import sys
  24. def ensure_dir_exists(dirname):
  25. """Ensure a directory exists, creating if necessary."""
  26. try:
  27. os.makedirs(dirname)
  28. except FileExistsError:
  29. pass
  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. # Defer the tempfile import since it pulls in a lot of other things.
  39. import tempfile
  40. # destination file exists
  41. try:
  42. (fd, tmpfile) = tempfile.mkstemp(".tmp", prefix=oldname, dir=".")
  43. os.close(fd)
  44. os.remove(tmpfile)
  45. except OSError:
  46. # either file could not be created (e.g. permission problem)
  47. # or could not be deleted (e.g. rude virus scanner)
  48. raise
  49. try:
  50. os.rename(newname, tmpfile)
  51. except OSError:
  52. raise # no rename occurred
  53. try:
  54. os.rename(oldname, newname)
  55. except OSError:
  56. os.rename(tmpfile, newname)
  57. raise
  58. os.remove(tmpfile)
  59. def GitFile(filename, mode='rb', bufsize=-1):
  60. """Create a file object that obeys the git file locking protocol.
  61. Returns: a builtin file object or a _GitFile object
  62. Note: See _GitFile for a description of the file locking protocol.
  63. Only read-only and write-only (binary) modes are supported; r+, w+, and a
  64. are not. To read and write from the same file, you can take advantage of
  65. the fact that opening a file for write does not actually open the file you
  66. request.
  67. """
  68. if 'a' in mode:
  69. raise IOError('append mode not supported for Git files')
  70. if '+' in mode:
  71. raise IOError('read/write mode not supported for Git files')
  72. if 'b' not in mode:
  73. raise IOError('text mode not supported for Git files')
  74. if 'w' in mode:
  75. return _GitFile(filename, mode, bufsize)
  76. else:
  77. return io.open(filename, mode, bufsize)
  78. class FileLocked(Exception):
  79. """File is already locked."""
  80. def __init__(self, filename, lockfilename):
  81. self.filename = filename
  82. self.lockfilename = lockfilename
  83. super(FileLocked, self).__init__(filename, lockfilename)
  84. class _GitFile(object):
  85. """File that follows the git locking protocol for writes.
  86. All writes to a file foo will be written into foo.lock in the same
  87. directory, and the lockfile will be renamed to overwrite the original file
  88. on close.
  89. Note: You *must* call close() or abort() on a _GitFile for the lock to be
  90. released. Typically this will happen in a finally block.
  91. """
  92. PROXY_PROPERTIES = set(['closed', 'encoding', 'errors', 'mode', 'name',
  93. 'newlines', 'softspace'])
  94. PROXY_METHODS = ('__iter__', 'flush', 'fileno', 'isatty', 'read',
  95. 'readline', 'readlines', 'seek', 'tell',
  96. 'truncate', 'write', 'writelines')
  97. def __init__(self, filename, mode, bufsize):
  98. self._filename = filename
  99. if isinstance(self._filename, bytes):
  100. self._lockfilename = self._filename + b'.lock'
  101. else:
  102. self._lockfilename = self._filename + '.lock'
  103. try:
  104. fd = os.open(
  105. self._lockfilename,
  106. os.O_RDWR | os.O_CREAT | os.O_EXCL |
  107. getattr(os, "O_BINARY", 0))
  108. except FileExistsError:
  109. raise FileLocked(filename, self._lockfilename)
  110. self._file = os.fdopen(fd, mode, bufsize)
  111. self._closed = False
  112. for method in self.PROXY_METHODS:
  113. setattr(self, method, getattr(self._file, method))
  114. def abort(self):
  115. """Close and discard the lockfile without overwriting the target.
  116. If the file is already closed, this is a no-op.
  117. """
  118. if self._closed:
  119. return
  120. self._file.close()
  121. try:
  122. os.remove(self._lockfilename)
  123. self._closed = True
  124. except FileNotFoundError:
  125. # The file may have been removed already, which is ok.
  126. self._closed = True
  127. def close(self):
  128. """Close this file, saving the lockfile over the original.
  129. Note: If this method fails, it will attempt to delete the lockfile.
  130. However, it is not guaranteed to do so (e.g. if a filesystem
  131. becomes suddenly read-only), which will prevent future writes to
  132. this file until the lockfile is removed manually.
  133. Raises:
  134. OSError: if the original file could not be overwritten. The
  135. lock file is still closed, so further attempts to write to the same
  136. file object will raise ValueError.
  137. """
  138. if self._closed:
  139. return
  140. os.fsync(self._file.fileno())
  141. self._file.close()
  142. try:
  143. if getattr(os, 'replace', None) is not None:
  144. os.replace(self._lockfilename, self._filename)
  145. else:
  146. if sys.platform != 'win32':
  147. os.rename(self._lockfilename, self._filename)
  148. else:
  149. # Windows versions prior to Vista don't support atomic
  150. # renames
  151. _fancy_rename(self._lockfilename, self._filename)
  152. finally:
  153. self.abort()
  154. def __enter__(self):
  155. return self
  156. def __exit__(self, exc_type, exc_val, exc_tb):
  157. self.close()
  158. def __getattr__(self, name):
  159. """Proxy property calls to the underlying file."""
  160. if name in self.PROXY_PROPERTIES:
  161. return getattr(self._file, name)
  162. raise AttributeError(name)