Improved stream support and added it to public API.
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 48f3e91 · Browse files · 5 files·+329 added−72 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+329 added−72 removed
- other:+329 added−72 removed
Provenance
- Commit
002c38d- Tree
607b245- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
48f3e91
5 files changed+329 added−72 removed
modified:click/__init__.py+2 added-2 removed
26 unmodified lines27 from .types import ParamType, File, Path, Choice, IntRange, STRING, INT, \28 FLOAT, BOOL, UUID29 30 # Utilities31-from .utils import echo31+from .utils import echo, get_binary_stream, get_text_stream32 33 # Terminal functions34 from .termui import prompt, confirm, get_terminal_size, echo_via_pager35 21 unmodified lines57 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'STRING', 'INT',58 'FLOAT', 'BOOL', 'UUID',59 60 # Utilities61- 'echo',61+ 'echo', 'get_binary_stream', 'get_text_stream',62 63 # Terminal functions64 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',65 9 unmodified linesmodified:click/_compat.py+285 added-50 removed
1-import sys1 import re2+import io3+import sys4 import codecs5 6 6-def _wrap_stream_for_codec(f, encoding=None, errors='strict'):7+def _make_text_stream(stream, encoding, errors):8 if encoding is None:8- encoding = 'utf-8'9- info = codecs.lookup(encoding)10- f = codecs.StreamReaderWriter(f, info.streamreader,11- info.streamwriter,12- errors)13- f.encoding = encoding14- return f9+ encoding = get_best_encoding(stream)10+ if errors is None:11+ errors = 'replace'12+ return _NonClosingTextIOWrapper(stream, encoding, errors)13 14 15+def is_ascii_encoding(encoding):16+ """Checks if a given encoding is ascii."""17+ try:18+ return codecs.lookup(encoding).name == 'ascii'19+ except LookupError:20+ return False21+22+23+def get_best_encoding(stream):24+ """Returns the default stream encoding if not found."""25+ rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()26+ if is_ascii_encoding(rv):27+ return 'utf-8'28+ return rv29+30+31+class _NonClosingTextIOWrapper(io.TextIOWrapper):32+33+ def __init__(self, stream, encoding, errors):34+ io.TextIOWrapper.__init__(self, _FixupStream(stream),35+ encoding, errors)36+37+ def __del__(self):38+ self.buffer._prevent_close = True39+40+41+class _FixupStream(object):42+ """The new io interface needs more from streams than streams43+ traditionally implement. As such this fixup stuff is necessary in44+ some circumstances.45+ """46+47+ def __init__(self, stream):48+ self._stream = stream49+ self._prevent_close = False50+51+ def __getattr__(self, name):52+ return getattr(self._stream, name)53+54+ def close(self):55+ if not self._prevent_close:56+ self._stream.close()57+58+ def read1(self, size):59+ f = getattr(self._stream, 'read1', None)60+ if f is not None:61+ return f(size)62+ return self._stream.readline(size)63+64+ def readable(self):65+ x = getattr(self._stream, 'readable', None)66+ if x is not None:67+ return x68+ try:69+ self._stream.read(0)70+ except Exception:71+ return False72+ return True73+74+ def writable(self):75+ x = getattr(self._stream, 'writable', None)76+ if x is not None:77+ return x78+ try:79+ self._stream.write('')80+ except Exception:81+ try:82+ self._stream.write(b'')83+ except Exception:84+ return False85+ return True86+87+ def seekable(self):88+ x = getattr(self._stream, 'seekable', None)89+ if x is not None:90+ return x91+ try:92+ self._stream.seek(self._stream.tell())93+ except Exception:94+ return False95+ return True96+97+98 PY2 = sys.version_info[0] == 299 if PY2:100 text_type = unicode101 bytes = str5 unmodified lines107 108 def isidentifier(x):109 return _identifier_re.search(x) is not None110 30- def open_stream(filename, mode='r', encoding=None, errors='strict'):31- if filename != '-':32- if encoding is not None:33- return codecs.open(filename, mode, encoding, errors), True34- return open(filename, mode), True35- if 'w' in mode:36- f = sys.stdout37- if encoding is not None:38- f = _wrap_stream_for_codec(f, encoding, errors)39- else:40- f = sys.stdin41- if 'b' not in mode:42- if encoding is None:43- encoding = sys.stdin.encoding44- f = _wrap_stream_for_codec(f, encoding, errors)45- return f, False111+ def get_binary_stdin():112+ return sys.stdin113 114+ def get_binary_stdout():115+ return sys.stdout116+117+ def get_binary_stderr():118+ return sys.stderr119+120+ def get_text_stdin(encoding=None, errors=None):121+ return _make_text_stream(sys.stdin, encoding, errors)122+123+ def get_text_stdout(encoding=None, errors=None):124+ return _make_text_stream(sys.stdout, encoding, errors)125+126+ def get_text_stderr(encoding=None, errors=None):127+ return _make_text_stream(sys.stderr, encoding, errors)128+129 def filename_to_ui(value):130 if isinstance(value, bytes):131 value = value.decode(sys.getfilesystemencoding(), 'replace')132 return value4 unmodified lines137 string_types = (str,)138 isidentifier = lambda x: x.isidentifier()139 iteritems = lambda x: iter(x.items())140 59- def _make_binary_stream(f, stream_name):60- buf = getattr(f, 'buffer', None)61- if buf is not None and isinstance(buf, io.BufferedReader):141+ def _is_binary_reader(stream, default=False):142+ try:143+ return isinstance(stream.read(0), bytes)144+ except Exception:145+ return default146+ # This happens in some cases where the stream was already147+ # closed. In this case we assume the defalt.148+149+ def _is_binary_writer(stream, default=False):150+ try:151+ stream.write(b'')152+ except Exception:153+ try:154+ stream.write('')155+ return False156+ except Exception:157+ pass158+ return default159+ return True160+161+ def _find_binary_reader(stream):162+ # We need to figure out if the given stream is already binary.163+ # This can happen because the official docs recommend detatching164+ # the streams to get binary streams. Some code might do this, so165+ # we need to deal with this case explicitly.166+ is_binary = _is_binary_reader(stream, False)167+168+ if is_binary:169+ return stream170+171+ buf = getattr(stream, 'buffer', None)172+ # Same situation here, this time we assume that the buffer is173+ # actually binary in case it's closed.174+ if buf is not None and _is_binary_reader(buf, True):175 return buf63- raise TypeError('%s is a stream that does not give access to its '64- 'underlying binary stream. Please do not set '65- 'sys.stdout directly to a StringIO object or '66- 'something similar.' % stream_name)176 68- def open_stream(filename, mode='r', encoding=None, errors='strict'):69- if filename != '-':70- if encoding is not None:71- return open(filename, mode, encoding=encoding,72- errors=errors), True73- return open(filename, mode), True177+ def _find_binary_writer(stream):178+ # We need to figure out if the given stream is already binary.179+ # This can happen because the official docs recommend detatching180+ # the streams to get binary streams. Some code might do this, so181+ # we need to deal with this case explicitly.182+ if _is_binary_writer(stream, False):183+ return stream184 75- if 'w' in mode:76- f = sys.stdout77- if encoding is not None or 'b' in mode:78- f = _make_binary_stream(f, 'stdout')79- if encoding is not None:80- f = _wrap_stream_for_codec(f, encoding, errors)185+ buf = getattr(stream, 'buffer', None)186+187+ # Same situation here, this time we assume that the buffer is188+ # actually binary in case it's closed.189+ if buf is not None and _is_binary_writer(buf, True):190+ return buf191+192+ def _stream_is_misconfigured(stream):193+ """A stream is misconfigured if it's encoding is ASCII."""194+ return is_ascii_encoding(getattr(stream, 'encoding', None))195+196+ def _is_compatible_text_stream(stream, encoding, errors):197+ stream_encoding = getattr(stream, 'encoding', None)198+ stream_errors = getattr(stream, 'errors', None)199+200+ # Perfect match.201+ if stream_encoding == encoding and stream_errors == errors:202+ return True203+204+ # Otherwise it's only a compatible stream if we did not ask for205+ # an encoding.206+ if encoding is None:207+ return stream_encoding is not None208+209+ return False210+211+ def _force_correct_text_reader(text_reader, encoding, errors):212+ if _is_binary_reader(text_reader, False):213+ binary_reader = text_reader214 else:82- f = sys.stdin83- if 'b' in mode:84- f = _make_binary_stream(f, 'stdin')85- if encoding is not None:86- f = _wrap_stream_for_codec(f, encoding, errors)215+ # If there is no target encoding set we need to verify that the216+ # reader is actually not misconfigured.217+ if encoding is None and not _stream_is_misconfigured(text_reader):218+ return text_reader219 88- return f, False220+ if _is_compatible_text_stream(text_reader, encoding, errors):221+ return text_reader222 223+ # If the reader has no encoding we try to find the underlying224+ # binary reader for it. If that fails because the environment is225+ # misconfigured, we silently go with the same reader because this226+ # is too common to happen. In that case mojibake is better than227+ # exceptions.228+ binary_reader = _find_binary_reader(text_reader)229+ if binary_reader is None:230+ return text_reader231+232+ # At this point we default the errors to replace instead of strict233+ # because nobody handles those errors anyways and at this point234+ # we're so fundamentally fucked that nothing can repair it.235+ if errors is None:236+ errors = 'replace'237+ return _make_text_stream(binary_reader, encoding, errors)238+239+ def _force_correct_text_writer(text_writer, encoding, errors):240+ if _is_binary_writer(text_writer, False):241+ binary_writer = text_writer242+ else:243+ # If there is no target encoding set we need to verify that the244+ # writer is actually not misconfigured.245+ if encoding is None and not _stream_is_misconfigured(text_writer):246+ return text_writer247+248+ if _is_compatible_text_stream(text_writer, encoding, errors):249+ return text_writer250+251+ # If the writer has no encoding we try to find the underlying252+ # binary writer for it. If that fails because the environment is253+ # misconfigured, we silently go with the same writer because this254+ # is too common to happen. In that case mojibake is better than255+ # exceptions.256+ binary_writer = _find_binary_writer(text_writer)257+ if binary_writer is None:258+ return text_writer259+260+ # At this point we default the errors to replace instead of strict261+ # because nobody handles those errors anyways and at this point262+ # we're so fundamentally fucked that nothing can repair it.263+ if errors is None:264+ errors = 'replace'265+ return _make_text_stream(binary_writer, encoding, errors)266+267+ def get_binary_stdin():268+ reader = _find_binary_reader(sys.stdin)269+ if reader is None:270+ raise RuntimeError('Was not able to determine binary '271+ 'stream for sys.stdin.')272+ return reader273+274+ def get_binary_stdout():275+ writer = _find_binary_writer(sys.stdout)276+ if writer is None:277+ raise RuntimeError('Was not able to determine binary '278+ 'stream for sys.stdout.')279+ return writer280+281+ def get_binary_stderr():282+ writer = _find_binary_writer(sys.stderr)283+ if writer is None:284+ raise RuntimeError('Was not able to determine binary '285+ 'stream for sys.stderr.')286+ return writer287+288+ def get_text_stdin(encoding=None, errors=None):289+ return _force_correct_text_reader(sys.stdin, encoding, errors)290+291+ def get_text_stdout(encoding=None, errors=None):292+ return _force_correct_text_writer(sys.stdout, encoding, errors)293+294+ def get_text_stderr(encoding=None, errors=None):295+ return _force_correct_text_writer(sys.stderr, encoding, errors)296+297 def filename_to_ui(value):298 if isinstance(value, bytes):299 value = value.decode(sys.getfilesystemencoding(), 'replace')300 else:12 unmodified lines313 msg = str(e)314 if isinstance(msg, bytes):315 msg = msg.decode('utf-8', 'replace')316 return msg317+318+319+def open_stream(filename, mode='r', encoding=None, errors='strict'):320+ if filename != '-':321+ if encoding is not None:322+ return io.open(filename, mode, encoding=encoding,323+ errors=errors), True324+ return open(filename, mode), True325+ if 'w' in mode:326+ if 'b' in mode:327+ return get_binary_stdout(), False328+ return get_text_stdout(encoding=encoding, errors=errors), False329+ if 'b' in mode:330+ return get_binary_stdin(), False331+ return get_text_stdin(encoding=encoding, errors=errors), False332+333+334+binary_streams = {335+ 'stdin': get_binary_stdin,336+ 'stdout': get_binary_stdout,337+ 'stderr': get_binary_stderr,338+}339+340+text_streams = {341+ 'stdin': get_text_stdin,342+ 'stdout': get_text_stdout,343+ 'stderr': get_text_stderr,344+}modified:click/termui.py+3 added-2 removed
1 import os2 import sys3 import struct4 5-from ._compat import raw_input, PY2, text_type, string_types6-from .utils import get_best_encoding, echo5+from ._compat import raw_input, PY2, text_type, string_types, \6+ get_best_encoding7+from .utils import echo8 from .exceptions import Abort, UsageError9 from .types import convert_type10 11 172 unmodified linesmodified:click/utils.py+35 added-18 removed
1 import sys2-import codecs2 from collections import deque3 5-from ._compat import text_type, open_stream, get_streerror, string_types, PY24+from ._compat import text_type, open_stream, get_streerror, string_types, \5+ PY2, get_best_encoding, binary_streams, text_streams6 7 8 def unpack_args(args, nargs_spec):9 """Given an iterable of arguments and an iterable of nargs specifications62 unmodified lines72 pass73 return wrapper74 75 76-def is_ascii_encoding(encoding):77- """Checks if a given encoding is ascii."""78- try:79- return codecs.lookup(encoding).name == 'ascii'80- except LookupError:81- return False82-83-84-def get_best_encoding(stream):85- """Returns the best encoding that should be used for a stream."""86- enc = getattr(stream, 'encoding', None)87- if enc is None or is_ascii_encoding(enc):88- return 'utf-8'89- return enc90-91-76 def make_str(value):77 """Converts a value into a valid string."""78 if isinstance(value, bytes):79 try:117 unmodified lines197 message = message.encode(encoding, 'replace')198 file.write(message)199 file.write('\n')200 file.flush()201+202+203+def get_binary_stream(name):204+ """Returns a system stream for byte processing. This essentially205+ returns the stream from the sys module with the given name but it206+ solves some compatibility issues between different Python versions.207+ Primarily this function is necessary for getting binary streams on208+ Python 3.209+210+ :param name: the name of the stream to open. Valid names are ``'stdin'``,211+ ``'stdout'`` and ``'stderr'``212+ """213+ opener = binary_streams.get(name)214+ if opener is None:215+ raise TypeError('Unknown standard stream %r' % name)216+ return opener()217+218+219+def get_text_stream(name, encoding=None, errors='strict'):220+ """Returns a system stream for text processing. This usually returns221+ a wrapped stream around a binary stream returned from222+ :func:`get_binary_stream` but it also can take shortcuts on Python 3223+ for already correctly configured streams.224+225+ :param name: the name of the stream to open. Valid names are ``'stdin'``,226+ ``'stdout'`` and ``'stderr'``227+ :param encoding: overrides the detected default encoding.228+ :param errors: overrides the default error mode.229+ """230+ opener = text_streams.get(name)231+ if opener is None:232+ raise TypeError('Unknown standard stream %r' % name)233+ return opener(encoding, errors)modified:docs/api.rst+4 added
42 unmodified lines43 .. autofunction:: confirm44 45 .. autofunction:: get_terminal_size46 47+.. autofunction:: get_binary_stream48+49+.. autofunction:: get_text_stream50+51 Commands52 --------53 54 .. autoclass:: Command85 unmodified lines