Merge pull request #1298 from joewledger/fix_958
Before adoption: this commit came in with the history the project adopted, so no landing records it.
click.open_file respects "errors" parameter.
authored by David Lord · committed by GitHub · parents 0f12615, 4e85c77 · Browse files · 2 files·+152 added−89 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+152 added−89 removed
- tests:+48 added−11 removed
- other:+104 added−78 removed
Provenance
- Commit
9ea9666- Tree
8f1cc7b- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
0f12615- Parent 2
4e85c77
2 files changed+152 added−89 removed
modified:click/_compat.py+104 added-78 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- if encoding is None:487- return open(filename, mode), True488- return io.open(filename, mode, encoding=encoding, errors=errors), True517+ return _wrap_io_open(filename, mode, encoding, errors), True518 519 # Some usability stuff for atomic writes520 if 'a' in mode:521 raise ValueError(19 unmodified lines541 except OSError:542 perm = None543 544 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL516- 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.EACCES531- and os.path.isdir(dir)532- 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 540- if encoding is not None:541- f = io.open(fd, mode, encoding=encoding, errors=errors)542- else:543- f = os.fdopen(fd, mode)544-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+48 added-11 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-294 result = runner.invoke(cli, ['hello.txt'])295 assert result.exception is None296 assert result.output == 'Cool stuff\nmeep\n'297 1 unmodified line299 assert result.exception is None300 assert result.output == 'foobar\nmeep\n'301 302 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+313+314+def test_open_file_respects_ignore(runner):315+ with runner.isolated_filesystem():316+ with open("test.txt", "w") as f:317+ f.write("Hello world!")318+319+ with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:320+ assert f.errors == "ignore"321+322+323+def test_open_file_ignore_invalid_utf8(runner):324+ with runner.isolated_filesystem():325+ with open("test.txt", "wb") as f:326+ f.write(b"\xe2\x28\xa1")327+328+ with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:329+ f.read()330+331+332+def test_open_file_ignore_no_encoding(runner):333+ with runner.isolated_filesystem():334+ with open("test.bin", "wb") as f:335+ f.write(os.urandom(16))336+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', [343 0o400,344 0o444,34 unmodified lines379 assert result.exception is None380 assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions381 382 344-@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')348- 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 354-@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')358- 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()