Skip to content
Myr

Implemented atomic file opening support.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 3df2c33 · Browse files · 5 files+114 added−18 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+114 added−18 removed

  • tests:+20 added−0 removed
  • other:+94 added−18 removed

5 files+114 added−18 removed

modified:click/_compat.py+70 added-12 removed
1 unmodified line
2import io3import os4import sys5import codecs6import tempfile789def _make_text_stream(stream, encoding, errors):10 if encoding is None:
328 unmodified lines
339 msg = msg.decode('utf-8', 'replace')340 return msg341342342def open_stream(filename, mode='r', encoding=None, errors='strict'):343 if filename != '-':344 if encoding is not None:345 return io.open(filename, mode, encoding=encoding,346 errors=errors), True347 return open(filename, mode), True348 if 'w' in mode:343def open_stream(filename, mode='r', encoding=None, errors='strict',344 atomic=False):345 # standard streams first. These are simple because they don't need346 # special handling for the atomic flag. It's entirely ignored.347 if filename == '-':348 if 'w' in mode:349 if 'b' in mode:350 return get_binary_stdout(), False351 return get_text_stdout(encoding=encoding, errors=errors), False352 if 'b' in mode:350 return get_binary_stdout(), False351 return get_text_stdout(encoding=encoding, errors=errors), False352 if 'b' in mode:353 return get_binary_stdin(), False354 return get_text_stdin(encoding=encoding, errors=errors), False353 return get_binary_stdin(), False354 return get_text_stdin(encoding=encoding, errors=errors), False355356 # Non-atomic writes directly go out through the regular open357 # functions.358 if not atomic:359 if encoding is None:360 return open(filename, mode), True361 return io.open(filename, mode, encoding=encoding, errors=errors), True362363 # Atomic writes are more complicated. They work by opening a file364 # as a proxy in the same folder and then using the fdopen365 # functionality to wrap it in a python file. Then we wrap it in an366 # atomic file that moves the file over on close.367 fd, tmp_filename = tempfile.mkstemp(dir=os.path.dirname(filename),368 prefix='.__atomic-write')369370 if encoding is not None:371 f = io.open(fd, mode, encoding=encoding, errors=errors)372 else:373 f = os.fdopen(fd, mode)374375 return _AtomicFile(f, tmp_filename, filename), True376377378# Used in a destructor call, needs extra protection from interpreter379# cleanup.380_rename = os.rename381382383class _AtomicFile(object):384385 def __init__(self, f, tmp_filename, real_filename):386 self._f = f387 self._tmp_filename = tmp_filename388 self._real_filename = real_filename389 self.closed = False390391 @property392 def name(self):393 return self._real_filename394395 def close(self, delete=False):396 if self.closed:397 return398 self._f.close()399 _rename(self._tmp_filename, self._real_filename)400 self.closed = True401402 def __getattr__(self, name):403 return getattr(self._f, name)404405 def __enter__(self):406 return self407408 def __exit__(self, exc_type, exc_value, tb):409 self.close(delete=exc_type is not None)410411 def __repr__(self):412 return repr(self._f)413414415binary_streams = {416 'stdin': get_binary_stdin,417 'stdout': get_binary_stdout,418 'stderr': get_binary_stderr,
7 unmodified lines
modified:click/types.py+12 added-3 removed
238 unmodified lines
239 The `lazy` flag controls if the file should be opened immediately or240 upon first IO. The default is to be non lazy for standard input and241 output streams as well as files opened for reading, lazy otherwise.242243 Starting with Click 2.0 files can also be opened atomically in which244 case all writes go into a separate file in the same folder and upon245 completion the file will be moved over to the original location. This246 is useful if a file is modified that is regularly read by other users.247248 See :ref:`file-args` for more information.249 """250 name = 'filename'251 envvar_list_splitter = os.path.pathsep252248 def __init__(self, mode='r', encoding=None, errors='strict', lazy=None):253 def __init__(self, mode='r', encoding=None, errors='strict', lazy=None,254 atomic=False):255 self.mode = mode256 self.encoding = encoding257 self.errors = errors258 self.lazy = lazy259 self.atomic = atomic260261 def resolve_lazy_flag(self, value):262 if self.lazy is not None:263 return self.lazy
10 unmodified lines
274275 lazy = self.resolve_lazy_flag(value)276277 if lazy:271 f = LazyFile(value, self.mode, self.encoding, self.errors)278 f = LazyFile(value, self.mode, self.encoding, self.errors,279 atomic=self.atomic)280 if ctx is not None:281 ctx.call_on_close(f.close_intelligently)282 return f283284 f, should_close = open_stream(value, self.mode,277 self.encoding, self.errors)285 self.encoding, self.errors,286 atomic=self.atomic)287 # If a context is provided we automatically close the file288 # at the end of the context execution (or flush out). If a289 # context does not exist it's the caller's responsibility to290 # properly close the file. This for instance happens when the
137 unmodified lines
modified:click/utils.py+6 added-3 removed
120 unmodified lines
121 filename parameter does make sense. This is useful for safely opening122 files for writing.123 """124125 def __init__(self, filename, mode='r', encoding=None, errors='strict'):125 def __init__(self, filename, mode='r', encoding=None, errors='strict',126 atomic=False):127 self.name = filename128 self.mode = mode129 self.encoding = encoding130 self.errors = errors131 self.atomic = atomic132133 if filename == '-':134 self._f, self.should_close = open_stream(filename, mode,135 encoding, errors)
1 unmodified line
137 if 'r' in mode:138 # Open and close the file in case we're opening it for139 # reading so that we can catch at least some errors in140 # some cases early.139 open(filename, mode, encoding, errors).close()141 open(filename, mode).close()142 self._f = None143 self.should_close = True144145 def __getattr__(self, name):
13 unmodified lines
159 return self._f160 try:161 rv, self.should_close = open_stream(self.name, self.mode,162 self.encoding,161 self.errors)163 self.errors,164 atomic=self.atomic)165 except (IOError, OSError) as e:166 from .exceptions import FileError167 raise FileError(self.name, hint=get_streerror(e))168 self._f = rv
110 unmodified lines
modified:docs/arguments.rst+6 added
131 unmodified lines
132necessary for manually prompting with the :func:`prompt` function as you133do not know if a stream like stdout was openend (which was already open134before) or a real file that needs closing.135136Starting with Click 2.0 it's also possible to open files in atomic mode by137passing ``atomic=True``. In atomic mode all writes go into a separate138file in the same folder and upon completion the file will be moved over to139the original location. This is useful if a file is modified that is140regularly read by other users.141142Environment Variables143---------------------144145Like options, arguments can also get values from an environment variable.
26 unmodified lines
modified:tests/test_arguments.py+20 added
70 unmodified lines
71 assert result.output == 'Hey!'72 assert result.exit_code == 0737475def test_file_atomics(runner):76 @click.command()77 @click.argument('output', type=click.File('wb', atomic=True))78 def inout(output):79 output.write(b'Foo bar baz\n')80 output.flush()81 with open(output.name, 'rb') as f:82 old_content = f.read()83 assert old_content == b'OLD\n'8485 with runner.isolated_filesystem():86 with open('foo.txt', 'wb') as f:87 f.write(b'OLD\n')88 result = runner.invoke(inout, ['foo.txt'], input='Hey!')89 assert result.output == ''90 assert result.exit_code == 091 with open('foo.txt', 'rb') as f:92 assert f.read() == b'Foo bar baz\n'939495def test_nargs_envvar(runner):96 @click.command()97 @click.option('--arg', nargs=-1)98 def cmd(arg):
39 unmodified lines