refactor open_stream and text stream utilities
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent fb880d7 · Browse files · 2 files·+136 added−139 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+136 added−139 removed
- tests:+32 added−55 removed
- other:+104 added−84 removed
Provenance
- Commit
4e85c77- Tree
2d0d739- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
fb880d7
2 files changed+136 added−139 removed
modified:click/_compat.py+104 added-84 removed
327 unmodified lines328 # environments. It's not quite clear what the correct behavior is329 # but this at least will force Click to recover somehow.330 return is_ascii_encoding(getattr(stream, 'encoding', None) or 'ascii')331 332+ def _is_compat_stream_attr(stream, attr, value):333+ """A stream attribute is compatible if it is equal to the334+ desired value or the desired value is unset and the attribute335+ has a value.336+ """337+ stream_value = getattr(stream, attr, None)338+ return stream_value == value or (value is None and stream_value is not None)339+340 def _is_compatible_text_stream(stream, encoding, errors):333- stream_encoding = getattr(stream, 'encoding', None)334- stream_errors = getattr(stream, 'errors', None)341+ """Check if a stream's encoding and errors attributes are342+ compatible with the desired values.343+ """344+ return (345+ _is_compat_stream_attr(stream, "encoding", encoding)346+ and _is_compat_stream_attr(stream, "errors", errors)347+ )348 336- # Perfect match.337- if stream_encoding == encoding and stream_errors == errors:338- return True339-340- # Otherwise, it's only a compatible stream if we did not ask for341- # an encoding.342- if encoding is None:343- return stream_encoding is not None344-345- return False346-347- def _force_correct_text_reader(text_reader, encoding, errors,348- force_readable=False):349- if _is_binary_reader(text_reader, False):350- binary_reader = text_reader349+ def _force_correct_text_stream(350+ text_stream,351+ encoding,352+ errors,353+ is_binary,354+ find_binary,355+ force_readable=False,356+ force_writable=False,357+ ):358+ if is_binary(text_stream, False):359+ binary_reader = text_stream360 else:352- # If there is no target encoding set, we need to verify that the353- # reader is not actually misconfigured.354- if encoding is None and not _stream_is_misconfigured(text_reader):355- return text_reader361+ # If the stream looks compatible, and won't default to a362+ # misconfigured ascii encoding, return it as-is.363+ if (364+ _is_compatible_text_stream(text_stream, encoding, errors)365+ and not (366+ encoding is None367+ and _stream_is_misconfigured(text_stream)368+ )369+ ):370+ return text_stream371 357- if _is_compatible_text_stream(text_reader, encoding, errors):358- return text_reader372+ # Otherwise, get the underlying binary reader.373+ binary_reader = find_binary(text_stream)374 360- # If the reader has no encoding, we try to find the underlying361- # binary reader for it. If that fails because the environment is362- # misconfigured, we silently go with the same reader because this363- # is too common to happen. In that case, mojibake is better than364- # exceptions.365- binary_reader = _find_binary_reader(text_reader)375+ # If that's not possible, silently use the original reader376+ # and get mojibake instead of exceptions.377 if binary_reader is None:367- return text_reader378+ return text_stream379 369- # At this point, we default the errors to replace instead of strict370- # because nobody handles those errors anyways and at this point371- # we're so fundamentally fucked that nothing can repair it.380+ # Default errors to replace instead of strict in order to get381+ # something that works.382 if errors is None:373- errors = 'replace'374- return _make_text_stream(binary_reader, encoding, errors,375- force_readable=force_readable)383+ errors = "replace"384 377- def _force_correct_text_writer(text_writer, encoding, errors,378- force_writable=False):379- if _is_binary_writer(text_writer, False):380- binary_writer = text_writer381- else:382- # If there is no target encoding set, we need to verify that the383- # writer is not actually misconfigured.384- if encoding is None and not _stream_is_misconfigured(text_writer):385- return text_writer385+ # Wrap the binary stream in a text stream with the correct386+ # encoding parameters.387+ return _make_text_stream(388+ binary_reader,389+ encoding,390+ errors,391+ force_readable=force_readable,392+ force_writable=force_writable,393+ )394 387- if _is_compatible_text_stream(text_writer, encoding, errors):388- return text_writer395+ def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):396+ return _force_correct_text_stream(397+ text_reader,398+ encoding,399+ errors,400+ _is_binary_reader,401+ _find_binary_reader,402+ force_readable=force_readable,403+ )404 390- # If the writer has no encoding, we try to find the underlying391- # binary writer for it. If that fails because the environment is392- # misconfigured, we silently go with the same writer because this393- # is too common to happen. In that case, mojibake is better than394- # exceptions.395- binary_writer = _find_binary_writer(text_writer)396- if binary_writer is None:397- return text_writer405+ def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):406+ return _force_correct_text_stream(407+ text_writer,408+ encoding,409+ errors,410+ _is_binary_writer,411+ _find_binary_writer,412+ force_writable=force_writable,413+ )414 399- # At this point, we default the errors to replace instead of strict400- # because nobody handles those errors anyways and at this point401- # we're so fundamentally fucked that nothing can repair it.402- if errors is None:403- errors = 'replace'404- return _make_text_stream(binary_writer, encoding, errors,405- force_writable=force_writable)406-415 def get_binary_stdin():416 reader = _find_binary_reader(sys.stdin)417 if reader is None:418 raise RuntimeError('Was not able to determine binary '56 unmodified lines475 msg = msg.decode('utf-8', 'replace')476 return msg477 478 471-def open_stream(filename, mode='r', encoding=None, errors='strict',472- atomic=False):479+def _wrap_io_open(file, mode, encoding, errors):480+ """On Python 2, :func:`io.open` returns a text file wrapper that481+ requires passing ``unicode`` to ``write``. Need to open the file in482+ binary mode then wrap it in a subclass that can write ``str`` and483+ ``unicode``.484+485+ Also handles not passing ``encoding`` and ``errors`` in binary mode.486+ """487+ binary = "b" in mode488+489+ if binary:490+ kwargs = {}491+ else:492+ kwargs = {"encoding": encoding, "errors": errors}493+494+ if not PY2 or binary:495+ return io.open(file, mode, **kwargs)496+497+ f = io.open(file, "b" + mode.replace("t", ""))498+ return _make_text_stream(f, **kwargs)499+500+501+def open_stream(filename, mode='r', encoding=None, errors='strict', atomic=False):502+ binary = "b" in mode503+504 # Standard streams first. These are simple because they don't need505 # special handling for the atomic flag. It's entirely ignored.506 if filename == '-':507 if any(m in mode for m in ['w', 'a', 'x']):477- if 'b' in mode:508+ if binary:509 return get_binary_stdout(), False510 return get_text_stdout(encoding=encoding, errors=errors), False480- if 'b' in mode:511+ if binary:512 return get_binary_stdin(), False513 return get_text_stdin(encoding=encoding, errors=errors), False514 515 # Non-atomic writes directly go out through the regular open functions.516 if not atomic:486- open_kwargs = {}517+ return _wrap_io_open(filename, mode, encoding, errors), True518 488- if encoding is not None:489- open_kwargs['encoding'] = encoding490-491- if errors is not None:492- open_kwargs['errors'] = errors493-494- return codecs.open(filename, mode, **open_kwargs), True495-519 # Some usability stuff for atomic writes520 if 'a' in mode:521 raise ValueError(522 'Appending to an existing file is not supported, because that '18 unmodified lines541 except OSError:542 perm = None543 544 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL522- if 'b' in mode:545+546+ if binary:547 flags |= getattr(os, 'O_BINARY', 0)548 549 while True:550 tmp_filename = os.path.join(6 unmodified lines557 except OSError as e:558 if e.errno == errno.EEXIST or (559 os.name == "nt"560 and e.errno == errno.EACCES537- and os.path.isdir(dir)538- and os.access(dir, os.W_OK)561+ and os.path.isdir(e.filename)562+ and os.access(e.filename, os.W_OK)563 ):564 continue565 raise566 567 if perm is not None:568 os.chmod(tmp_filename, perm) # in case perm includes bits in umask569 546- if encoding is not None:547- f = io.open(fd, mode, encoding=encoding, errors=errors)548- else:549- f = os.fdopen(fd, mode)550-570+ f = _wrap_io_open(fd, mode, encoding, errors)571 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True572 573 574 # Used in a destructor call, needs extra protection from interpreter cleanup.196 unmodified linesmodified:tests/test_utils.py+32 added-55 removed
277 unmodified lines278 assert err == 'Pause to stderr\n'279 280 281 def test_open_file(runner):282+ @click.command()283+ @click.argument('filename')284+ def cli(filename):285+ with click.open_file(filename) as f:286+ click.echo(f.read())287+288+ click.echo('meep')289+290 with runner.isolated_filesystem():291 with open('hello.txt', 'w') as f:292 f.write('Cool stuff')293 286- @click.command()287- @click.argument('filename')288- def cli(filename):289- with click.open_file(filename) as f:290- click.echo(f.read())291- click.echo('meep')292-293- @click.command()294- @click.argument('filename')295- def cli_ignore_errors(filename):296- with click.open_file(filename, errors="ignore") as f:297- click.echo(f.read())298- click.echo('meep')299-294 result = runner.invoke(cli, ['hello.txt'])295 assert result.exception is None296 assert result.output == 'Cool stuff\nmeep\n'297 298 result = runner.invoke(cli, ['-'], input='foobar')299 assert result.exception is None300 assert result.output == 'foobar\nmeep\n'301 308- # Test that invalid unicode does not throw an exception when we ignore errors,309- # but does throw an exception when we don't310- random_input = os.urandom(64)311- result = runner.invoke(cli_ignore_errors, ['-'], input=random_input)312- assert result.exception is None302 314- result = runner.invoke(cli, ['-'], input=random_input)315- assert isinstance(result.exception, UnicodeDecodeError)303+def test_open_file_ignore_errors_stdin(runner):304+ @click.command()305+ @click.argument("filename")306+ def cli(filename):307+ with click.open_file(filename, errors="ignore") as f:308+ click.echo(f.read())309 310+ result = runner.invoke(cli, ["-"], input=os.urandom(16))311+ assert result.exception is None312 318-def test_click_open_file_respects_ignore(runner):319- file_name = "hello_world.txt"313 314+def test_open_file_respects_ignore(runner):315 with runner.isolated_filesystem():322- with open(file_name, "w") as f:316+ with open("test.txt", "w") as f:317 f.write("Hello world!")318 325- click_wrapper = click.utils.open_file(file_name, encoding="UTF-8", errors="ignore")326- assert click_wrapper.errors == "ignore"319+ with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:320+ assert f.errors == "ignore"321 322 329-@pytest.mark.parametrize("ignore", [330- True,331- False332-])333-def test_click_open_file_ignore_invalid_utf8(ignore, runner):334- file_name = "invalid_utf8.txt"335-323+def test_open_file_ignore_invalid_utf8(runner):324 with runner.isolated_filesystem():337- with open(file_name, "wb") as f:338- f.write(b'\xe2\x28\xa1')325+ with open("test.txt", "wb") as f:326+ f.write(b"\xe2\x28\xa1")327 340- open_kwargs = {"encoding": "UTF-8"}328+ with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:329+ f.read()330 342- if ignore:343- # Here we ignore invalid UTF-8, so we should not throw an exception344- open_kwargs["errors"] = "ignore"345- click.utils.open_file(file_name, **open_kwargs).read()346- else:347- # Here we are not ignoring invalid UTF-8, so we expect a UnicodeDecodeError348- with pytest.raises(UnicodeDecodeError):349- click.utils.open_file(file_name, **open_kwargs).read()331 351-352-def test_click_open_file_ignore_no_encoding_provided(runner):353- file_name = "random_input.bin"354-332+def test_open_file_ignore_no_encoding(runner):333 with runner.isolated_filesystem():356- with open(file_name, "wb") as f:357- f.write(os.urandom(64))334+ with open("test.bin", "wb") as f:335+ f.write(os.urandom(16))336 359- click.utils.open_file(file_name, errors="ignore").read()337+ with click.open_file("test.bin", errors="ignore") as f:338+ f.read()339 340 341 @pytest.mark.skipif(WIN, reason='os.chmod() is not fully supported on Windows.')342 @pytest.mark.parametrize('permissions', [36 unmodified lines379 assert result.exception is None380 assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions381 382 404-@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')383 def test_iter_keepopenfile(tmpdir):384 expected = list(map(str, range(10)))385 p = tmpdir.mkdir('testdir').join('testfile')408- p.write(os.linesep.join(expected))386+ p.write("\n".join(expected))387 with p.open() as f:388 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):389 assert e_line == a_line.strip()390 391 414-@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')392 def test_iter_lazyfile(tmpdir):393 expected = list(map(str, range(10)))394 p = tmpdir.mkdir('testdir').join('testfile')418- p.write(os.linesep.join(expected))395+ p.write("\n".join(expected))396 with p.open() as f:397 with click.utils.LazyFile(f.name) as lf:398 for e_line, a_line in zip(expected, lf):399 assert e_line == a_line.strip()