__init__.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import contextlib
  2. import io
  3. import os
  4. import sys
  5. import tempfile
  6. try:
  7. import fcntl
  8. except ImportError:
  9. fcntl = None
  10. __version__ = '1.3.0'
  11. PY2 = sys.version_info[0] == 2
  12. text_type = unicode if PY2 else str # noqa
  13. def _path_to_unicode(x):
  14. if not isinstance(x, text_type):
  15. return x.decode(sys.getfilesystemencoding())
  16. return x
  17. DEFAULT_MODE = "wb" if PY2 else "w"
  18. _proper_fsync = os.fsync
  19. if sys.platform != 'win32':
  20. if hasattr(fcntl, 'F_FULLFSYNC'):
  21. def _proper_fsync(fd):
  22. # https://lists.apple.com/archives/darwin-dev/2005/Feb/msg00072.html
  23. # https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/fsync.2.html
  24. # https://github.com/untitaker/python-atomicwrites/issues/6
  25. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  26. def _sync_directory(directory):
  27. # Ensure that filenames are written to disk
  28. fd = os.open(directory, 0)
  29. try:
  30. _proper_fsync(fd)
  31. finally:
  32. os.close(fd)
  33. def _replace_atomic(src, dst):
  34. os.rename(src, dst)
  35. _sync_directory(os.path.normpath(os.path.dirname(dst)))
  36. def _move_atomic(src, dst):
  37. os.link(src, dst)
  38. os.unlink(src)
  39. src_dir = os.path.normpath(os.path.dirname(src))
  40. dst_dir = os.path.normpath(os.path.dirname(dst))
  41. _sync_directory(dst_dir)
  42. if src_dir != dst_dir:
  43. _sync_directory(src_dir)
  44. else:
  45. from ctypes import windll, WinError
  46. _MOVEFILE_REPLACE_EXISTING = 0x1
  47. _MOVEFILE_WRITE_THROUGH = 0x8
  48. _windows_default_flags = _MOVEFILE_WRITE_THROUGH
  49. def _handle_errors(rv):
  50. if not rv:
  51. raise WinError()
  52. def _replace_atomic(src, dst):
  53. _handle_errors(windll.kernel32.MoveFileExW(
  54. _path_to_unicode(src), _path_to_unicode(dst),
  55. _windows_default_flags | _MOVEFILE_REPLACE_EXISTING
  56. ))
  57. def _move_atomic(src, dst):
  58. _handle_errors(windll.kernel32.MoveFileExW(
  59. _path_to_unicode(src), _path_to_unicode(dst),
  60. _windows_default_flags
  61. ))
  62. def replace_atomic(src, dst):
  63. '''
  64. Move ``src`` to ``dst``. If ``dst`` exists, it will be silently
  65. overwritten.
  66. Both paths must reside on the same filesystem for the operation to be
  67. atomic.
  68. '''
  69. return _replace_atomic(src, dst)
  70. def move_atomic(src, dst):
  71. '''
  72. Move ``src`` to ``dst``. There might a timewindow where both filesystem
  73. entries exist. If ``dst`` already exists, :py:exc:`FileExistsError` will be
  74. raised.
  75. Both paths must reside on the same filesystem for the operation to be
  76. atomic.
  77. '''
  78. return _move_atomic(src, dst)
  79. class AtomicWriter(object):
  80. '''
  81. A helper class for performing atomic writes. Usage::
  82. with AtomicWriter(path).open() as f:
  83. f.write(...)
  84. :param path: The destination filepath. May or may not exist.
  85. :param mode: The filemode for the temporary file. This defaults to `wb` in
  86. Python 2 and `w` in Python 3.
  87. :param overwrite: If set to false, an error is raised if ``path`` exists.
  88. Errors are only raised after the file has been written to. Either way,
  89. the operation is atomic.
  90. If you need further control over the exact behavior, you are encouraged to
  91. subclass.
  92. '''
  93. def __init__(self, path, mode=DEFAULT_MODE, overwrite=False,
  94. **open_kwargs):
  95. if 'a' in mode:
  96. raise ValueError(
  97. 'Appending to an existing file is not supported, because that '
  98. 'would involve an expensive `copy`-operation to a temporary '
  99. 'file. Open the file in normal `w`-mode and copy explicitly '
  100. 'if that\'s what you\'re after.'
  101. )
  102. if 'x' in mode:
  103. raise ValueError('Use the `overwrite`-parameter instead.')
  104. if 'w' not in mode:
  105. raise ValueError('AtomicWriters can only be written to.')
  106. self._path = path
  107. self._mode = mode
  108. self._overwrite = overwrite
  109. self._open_kwargs = open_kwargs
  110. def open(self):
  111. '''
  112. Open the temporary file.
  113. '''
  114. return self._open(self.get_fileobject)
  115. @contextlib.contextmanager
  116. def _open(self, get_fileobject):
  117. f = None # make sure f exists even if get_fileobject() fails
  118. try:
  119. success = False
  120. with get_fileobject(**self._open_kwargs) as f:
  121. yield f
  122. self.sync(f)
  123. self.commit(f)
  124. success = True
  125. finally:
  126. if not success:
  127. try:
  128. self.rollback(f)
  129. except Exception:
  130. pass
  131. def get_fileobject(self, suffix="", prefix=tempfile.template, dir=None,
  132. **kwargs):
  133. '''Return the temporary file to use.'''
  134. if dir is None:
  135. dir = os.path.normpath(os.path.dirname(self._path))
  136. descriptor, name = tempfile.mkstemp(suffix=suffix, prefix=prefix,
  137. dir=dir)
  138. # io.open() will take either the descriptor or the name, but we need
  139. # the name later for commit()/replace_atomic() and couldn't find a way
  140. # to get the filename from the descriptor.
  141. os.close(descriptor)
  142. kwargs['mode'] = self._mode
  143. kwargs['file'] = name
  144. return io.open(**kwargs)
  145. def sync(self, f):
  146. '''responsible for clearing as many file caches as possible before
  147. commit'''
  148. f.flush()
  149. _proper_fsync(f.fileno())
  150. def commit(self, f):
  151. '''Move the temporary file to the target location.'''
  152. if self._overwrite:
  153. replace_atomic(f.name, self._path)
  154. else:
  155. move_atomic(f.name, self._path)
  156. def rollback(self, f):
  157. '''Clean up all temporary resources.'''
  158. os.unlink(f.name)
  159. def atomic_write(path, writer_cls=AtomicWriter, **cls_kwargs):
  160. '''
  161. Simple atomic writes. This wraps :py:class:`AtomicWriter`::
  162. with atomic_write(path) as f:
  163. f.write(...)
  164. :param path: The target path to write to.
  165. :param writer_cls: The writer class to use. This parameter is useful if you
  166. subclassed :py:class:`AtomicWriter` to change some behavior and want to
  167. use that new subclass.
  168. Additional keyword arguments are passed to the writer class. See
  169. :py:class:`AtomicWriter`.
  170. '''
  171. return writer_cls(path, **cls_kwargs).open()