file.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. def ensure_dir_exists(dirname):
  22. """Ensure a directory exists, creating if necessary."""
  23. try:
  24. os.makedirs(dirname)
  25. except OSError, e:
  26. if e.errno != errno.EEXIST:
  27. raise
  28. def GitFile(filename, mode='r', bufsize=-1):
  29. """Create a file object that obeys the git file locking protocol.
  30. See _GitFile for a description of the file locking protocol.
  31. Only read-only and write-only (binary) modes are supported; r+, w+, and a
  32. are not. To read and write from the same file, you can take advantage of
  33. the fact that opening a file for write does not actually open the file you
  34. request:
  35. >>> write_file = GitFile('filename', 'wb')
  36. >>> read_file = GitFile('filename', 'rb')
  37. >>> read_file.readlines()
  38. ['contents\n', 'of\n', 'the\n', 'file\n']
  39. >>> write_file.write('foo')
  40. >>> read_file.close()
  41. >>> write_file.close()
  42. >>> new_file = GitFile('filename', 'rb')
  43. 'foo'
  44. >>> new_file.close()
  45. >>> other_file = GitFile('filename', 'wb')
  46. Traceback (most recent call last):
  47. ...
  48. OSError: [Errno 17] File exists: 'filename.lock'
  49. :return: a builtin file object or a _GitFile object
  50. """
  51. if 'a' in mode:
  52. raise IOError('append mode not supported for Git files')
  53. if '+' in mode:
  54. raise IOError('read/write mode not supported for Git files')
  55. if 'b' not in mode:
  56. raise IOError('text mode not supported for Git files')
  57. if 'w' in mode:
  58. return _GitFile(filename, mode, bufsize)
  59. else:
  60. return file(filename, mode, bufsize)
  61. class _GitFile(object):
  62. """File that follows the git locking protocol for writes.
  63. All writes to a file foo will be written into foo.lock in the same
  64. directory, and the lockfile will be renamed to overwrite the original file
  65. on close.
  66. :note: You *must* call close() or abort() on a _GitFile for the lock to be
  67. released. Typically this will happen in a finally block.
  68. """
  69. PROXY_PROPERTIES = set(['closed', 'encoding', 'errors', 'mode', 'name',
  70. 'newlines', 'softspace'])
  71. PROXY_METHODS = ('__iter__', 'flush', 'fileno', 'isatty', 'next', 'read',
  72. 'readline', 'readlines', 'xreadlines', 'seek', 'tell',
  73. 'truncate', 'write', 'writelines')
  74. def __init__(self, filename, mode, bufsize):
  75. self._filename = filename
  76. self._lockfilename = '%s.lock' % self._filename
  77. fd = os.open(self._lockfilename,
  78. os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0))
  79. self._file = os.fdopen(fd, mode, bufsize)
  80. self._closed = False
  81. for method in self.PROXY_METHODS:
  82. setattr(self, method, getattr(self._file, method))
  83. def abort(self):
  84. """Close and discard the lockfile without overwriting the target.
  85. If the file is already closed, this is a no-op.
  86. """
  87. if self._closed:
  88. return
  89. self._file.close()
  90. try:
  91. os.remove(self._lockfilename)
  92. self._closed = True
  93. except OSError, e:
  94. # The file may have been removed already, which is ok.
  95. if e.errno != errno.ENOENT:
  96. raise
  97. def close(self):
  98. """Close this file, saving the lockfile over the original.
  99. :note: If this method fails, it will attempt to delete the lockfile.
  100. However, it is not guaranteed to do so (e.g. if a filesystem becomes
  101. suddenly read-only), which will prevent future writes to this file
  102. until the lockfile is removed manually.
  103. :raises OSError: if the original file could not be overwritten. The lock
  104. file is still closed, so further attempts to write to the same file
  105. object will raise ValueError.
  106. """
  107. if self._closed:
  108. return
  109. self._file.close()
  110. try:
  111. os.rename(self._lockfilename, self._filename)
  112. finally:
  113. self.abort()
  114. def __getattr__(self, name):
  115. """Proxy property calls to the underlying file."""
  116. if name in self.PROXY_PROPERTIES:
  117. return getattr(self._file, name)
  118. raise AttributeError(name)