__init__.py 6.6 KB

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