file.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 os
  22. import sys
  23. import warnings
  24. from typing import ClassVar, Set
  25. def ensure_dir_exists(dirname):
  26. """Ensure a directory exists, creating if necessary."""
  27. try:
  28. os.makedirs(dirname)
  29. except FileExistsError:
  30. pass
  31. def _fancy_rename(oldname, newname):
  32. """Rename file with temporary backup file to rollback if rename fails."""
  33. if not os.path.exists(newname):
  34. try:
  35. os.rename(oldname, newname)
  36. except OSError:
  37. raise
  38. return
  39. # Defer the tempfile import since it pulls in a lot of other things.
  40. import tempfile
  41. # destination file exists
  42. try:
  43. (fd, tmpfile) = tempfile.mkstemp(".tmp", prefix=oldname, dir=".")
  44. os.close(fd)
  45. os.remove(tmpfile)
  46. except OSError:
  47. # either file could not be created (e.g. permission problem)
  48. # or could not be deleted (e.g. rude virus scanner)
  49. raise
  50. try:
  51. os.rename(newname, tmpfile)
  52. except OSError:
  53. raise # no rename occurred
  54. try:
  55. os.rename(oldname, newname)
  56. except OSError:
  57. os.rename(tmpfile, newname)
  58. raise
  59. os.remove(tmpfile)
  60. def GitFile(filename, mode="rb", bufsize=-1, mask=0o644):
  61. """Create a file object that obeys the git file locking protocol.
  62. Returns: a builtin file object or a _GitFile object
  63. Note: See _GitFile for a description of the file locking protocol.
  64. Only read-only and write-only (binary) modes are supported; r+, w+, and a
  65. are not. To read and write from the same file, you can take advantage of
  66. the fact that opening a file for write does not actually open the file you
  67. request.
  68. The default file mask makes any created files user-writable and
  69. world-readable.
  70. """
  71. if "a" in mode:
  72. raise OSError("append mode not supported for Git files")
  73. if "+" in mode:
  74. raise OSError("read/write mode not supported for Git files")
  75. if "b" not in mode:
  76. raise OSError("text mode not supported for Git files")
  77. if "w" in mode:
  78. return _GitFile(filename, mode, bufsize, mask)
  79. else:
  80. return open(filename, mode, bufsize)
  81. class FileLocked(Exception):
  82. """File is already locked."""
  83. def __init__(self, filename, lockfilename) -> None:
  84. self.filename = filename
  85. self.lockfilename = lockfilename
  86. super().__init__(filename, lockfilename)
  87. class _GitFile:
  88. """File that follows the git locking protocol for writes.
  89. All writes to a file foo will be written into foo.lock in the same
  90. directory, and the lockfile will be renamed to overwrite the original file
  91. on close.
  92. Note: You *must* call close() or abort() on a _GitFile for the lock to be
  93. released. Typically this will happen in a finally block.
  94. """
  95. PROXY_PROPERTIES: ClassVar[Set[str]] = {
  96. "closed",
  97. "encoding",
  98. "errors",
  99. "mode",
  100. "name",
  101. "newlines",
  102. "softspace",
  103. }
  104. PROXY_METHODS: ClassVar[Set[str]] = {
  105. "__iter__",
  106. "flush",
  107. "fileno",
  108. "isatty",
  109. "read",
  110. "readline",
  111. "readlines",
  112. "seek",
  113. "tell",
  114. "truncate",
  115. "write",
  116. "writelines",
  117. }
  118. def __init__(self, filename, mode, bufsize, mask) -> None:
  119. self._filename = filename
  120. if isinstance(self._filename, bytes):
  121. self._lockfilename = self._filename + b".lock"
  122. else:
  123. self._lockfilename = self._filename + ".lock"
  124. try:
  125. fd = os.open(
  126. self._lockfilename,
  127. os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0),
  128. mask,
  129. )
  130. except FileExistsError as exc:
  131. raise FileLocked(filename, self._lockfilename) from exc
  132. self._file = os.fdopen(fd, mode, bufsize)
  133. self._closed = False
  134. for method in self.PROXY_METHODS:
  135. setattr(self, method, getattr(self._file, method))
  136. def abort(self):
  137. """Close and discard the lockfile without overwriting the target.
  138. If the file is already closed, this is a no-op.
  139. """
  140. if self._closed:
  141. return
  142. self._file.close()
  143. try:
  144. os.remove(self._lockfilename)
  145. self._closed = True
  146. except FileNotFoundError:
  147. # The file may have been removed already, which is ok.
  148. self._closed = True
  149. def close(self):
  150. """Close this file, saving the lockfile over the original.
  151. Note: If this method fails, it will attempt to delete the lockfile.
  152. However, it is not guaranteed to do so (e.g. if a filesystem
  153. becomes suddenly read-only), which will prevent future writes to
  154. this file until the lockfile is removed manually.
  155. Raises:
  156. OSError: if the original file could not be overwritten. The
  157. lock file is still closed, so further attempts to write to the same
  158. file object will raise ValueError.
  159. """
  160. if self._closed:
  161. return
  162. self._file.flush()
  163. os.fsync(self._file.fileno())
  164. self._file.close()
  165. try:
  166. if getattr(os, "replace", None) is not None:
  167. os.replace(self._lockfilename, self._filename)
  168. else:
  169. if sys.platform != "win32":
  170. os.rename(self._lockfilename, self._filename)
  171. else:
  172. # Windows versions prior to Vista don't support atomic
  173. # renames
  174. _fancy_rename(self._lockfilename, self._filename)
  175. finally:
  176. self.abort()
  177. def __del__(self) -> None:
  178. if not getattr(self, "_closed", True):
  179. warnings.warn(f"unclosed {self!r}", ResourceWarning, stacklevel=2)
  180. self.abort()
  181. def __enter__(self):
  182. return self
  183. def __exit__(self, exc_type, exc_val, exc_tb):
  184. if exc_type is not None:
  185. self.abort()
  186. else:
  187. self.close()
  188. def __getattr__(self, name):
  189. """Proxy property calls to the underlying file."""
  190. if name in self.PROXY_PROPERTIES:
  191. return getattr(self._file, name)
  192. raise AttributeError(name)