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
Provenance
- Commit
469ba25- Tree
b24cdaf- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
3df2c33
5 files changed+114 added−18 removed
modified:click/_compat.py+70 added-12 removed
1 unmodified line2 import io3 import os4 import sys5 import codecs6+import tempfile7 8 9 def _make_text_stream(stream, encoding, errors):10 if encoding is None:328 unmodified lines339 msg = msg.decode('utf-8', 'replace')340 return msg341 342 342-def 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:343+def 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), False355 356+ # 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), True362 363+ # 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')369+370+ if encoding is not None:371+ f = io.open(fd, mode, encoding=encoding, errors=errors)372+ else:373+ f = os.fdopen(fd, mode)374+375+ return _AtomicFile(f, tmp_filename, filename), True376+377+378+# Used in a destructor call, needs extra protection from interpreter379+# cleanup.380+_rename = os.rename381+382+383+class _AtomicFile(object):384+385+ def __init__(self, f, tmp_filename, real_filename):386+ self._f = f387+ self._tmp_filename = tmp_filename388+ self._real_filename = real_filename389+ self.closed = False390+391+ @property392+ def name(self):393+ return self._real_filename394+395+ 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 = True401+402+ def __getattr__(self, name):403+ return getattr(self._f, name)404+405+ def __enter__(self):406+ return self407+408+ def __exit__(self, exc_type, exc_value, tb):409+ self.close(delete=exc_type is not None)410+411+ def __repr__(self):412+ return repr(self._f)413+414+415 binary_streams = {416 'stdin': get_binary_stdin,417 'stdout': get_binary_stdout,418 'stderr': get_binary_stderr,7 unmodified linesmodified:click/types.py+12 added-3 removed
238 unmodified lines239 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.242 243+ 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.247+248 See :ref:`file-args` for more information.249 """250 name = 'filename'251 envvar_list_splitter = os.path.pathsep252 248- 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 = atomic260 261 def resolve_lazy_flag(self, value):262 if self.lazy is not None:263 return self.lazy10 unmodified lines274 275 lazy = self.resolve_lazy_flag(value)276 277 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 f283 284 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 the137 unmodified linesmodified:click/utils.py+6 added-3 removed
120 unmodified lines121 filename parameter does make sense. This is useful for safely opening122 files for writing.123 """124 125- 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 = atomic132 133 if filename == '-':134 self._f, self.should_close = open_stream(filename, mode,135 encoding, errors)1 unmodified line137 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 = True144 145 def __getattr__(self, name):13 unmodified lines159 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 = rv110 unmodified linesmodified:docs/arguments.rst+6 added
131 unmodified lines132 necessary for manually prompting with the :func:`prompt` function as you133 do not know if a stream like stdout was openend (which was already open134 before) or a real file that needs closing.135 136+Starting with Click 2.0 it's also possible to open files in atomic mode by137+passing ``atomic=True``. In atomic mode all writes go into a separate138+file in the same folder and upon completion the file will be moved over to139+the original location. This is useful if a file is modified that is140+regularly read by other users.141+142 Environment Variables143 ---------------------144 145 Like options, arguments can also get values from an environment variable.26 unmodified linesmodified:tests/test_arguments.py+20 added
70 unmodified lines71 assert result.output == 'Hey!'72 assert result.exit_code == 073 74 75+def 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'84+85+ 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'93+94+95 def test_nargs_envvar(runner):96 @click.command()97 @click.option('--arg', nargs=-1)98 def cmd(arg):39 unmodified lines