Skip to content
Myr

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

5 files+329 added−72 removed

modified:click/__init__.py+2 added-2 removed
26 unmodified lines
27from .types import ParamType, File, Path, Choice, IntRange, STRING, INT, \28 FLOAT, BOOL, UUID2930# Utilities31from .utils import echo31from .utils import echo, get_binary_stream, get_text_stream3233# Terminal functions34from .termui import prompt, confirm, get_terminal_size, echo_via_pager35
21 unmodified lines
57 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'STRING', 'INT',58 'FLOAT', 'BOOL', 'UUID',5960 # Utilities61 'echo',61 'echo', 'get_binary_stream', 'get_text_stream',6263 # Terminal functions64 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',65
9 unmodified lines
modified:click/_compat.py+285 added-50 removed
1import sys1import re2import io3import sys4import codecs566def _wrap_stream_for_codec(f, encoding=None, errors='strict'):7def _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)131415def 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 False212223def 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 rv293031class _NonClosingTextIOWrapper(io.TextIOWrapper):3233 def __init__(self, stream, encoding, errors):34 io.TextIOWrapper.__init__(self, _FixupStream(stream),35 encoding, errors)3637 def __del__(self):38 self.buffer._prevent_close = True394041class _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 """4647 def __init__(self, stream):48 self._stream = stream49 self._prevent_close = False5051 def __getattr__(self, name):52 return getattr(self._stream, name)5354 def close(self):55 if not self._prevent_close:56 self._stream.close()5758 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)6364 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 True7374 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 True8687 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 True969798PY2 = sys.version_info[0] == 299if PY2:100 text_type = unicode101 bytes = str
5 unmodified lines
107108 def isidentifier(x):109 return _identifier_re.search(x) is not None11030 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.stdin113114 def get_binary_stdout():115 return sys.stdout116117 def get_binary_stderr():118 return sys.stderr119120 def get_text_stdin(encoding=None, errors=None):121 return _make_text_stream(sys.stdin, encoding, errors)122123 def get_text_stdout(encoding=None, errors=None):124 return _make_text_stream(sys.stdout, encoding, errors)125126 def get_text_stderr(encoding=None, errors=None):127 return _make_text_stream(sys.stderr, encoding, errors)128129 def filename_to_ui(value):130 if isinstance(value, bytes):131 value = value.decode(sys.getfilesystemencoding(), 'replace')132 return value
4 unmodified lines
137 string_types = (str,)138 isidentifier = lambda x: x.isidentifier()139 iteritems = lambda x: iter(x.items())14059 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.148149 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 True160161 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)167168 if is_binary:169 return stream170171 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)17668 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 stream18475 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)186187 # 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 buf191192 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))195196 def _is_compatible_text_stream(stream, encoding, errors):197 stream_encoding = getattr(stream, 'encoding', None)198 stream_errors = getattr(stream, 'errors', None)199200 # Perfect match.201 if stream_encoding == encoding and stream_errors == errors:202 return True203204 # 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 None208209 return False210211 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_reader21988 return f, False220 if _is_compatible_text_stream(text_reader, encoding, errors):221 return text_reader222223 # 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_reader231232 # 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)238239 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_writer247248 if _is_compatible_text_stream(text_writer, encoding, errors):249 return text_writer250251 # 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_writer259260 # 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)266267 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 reader273274 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 writer280281 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 writer287288 def get_text_stdin(encoding=None, errors=None):289 return _force_correct_text_reader(sys.stdin, encoding, errors)290291 def get_text_stdout(encoding=None, errors=None):292 return _force_correct_text_writer(sys.stdout, encoding, errors)293294 def get_text_stderr(encoding=None, errors=None):295 return _force_correct_text_writer(sys.stderr, encoding, errors)296297 def filename_to_ui(value):298 if isinstance(value, bytes):299 value = value.decode(sys.getfilesystemencoding(), 'replace')300 else:
12 unmodified lines
313 msg = str(e)314 if isinstance(msg, bytes):315 msg = msg.decode('utf-8', 'replace')316 return msg317318319def 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), False332333334binary_streams = {335 'stdin': get_binary_stdin,336 'stdout': get_binary_stdout,337 'stderr': get_binary_stderr,338}339340text_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
1import os2import sys3import struct45from ._compat import raw_input, PY2, text_type, string_types6from .utils import get_best_encoding, echo5from ._compat import raw_input, PY2, text_type, string_types, \6 get_best_encoding7from .utils import echo8from .exceptions import Abort, UsageError9from .types import convert_type1011
172 unmodified lines
modified:click/utils.py+35 added-18 removed
1import sys2import codecs2from collections import deque35from ._compat import text_type, open_stream, get_streerror, string_types, PY24from ._compat import text_type, open_stream, get_streerror, string_types, \5 PY2, get_best_encoding, binary_streams, text_streams678def unpack_args(args, nargs_spec):9 """Given an iterable of arguments and an iterable of nargs specifications
62 unmodified lines
72 pass73 return wrapper747576def 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 False828384def 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 enc909176def make_str(value):77 """Converts a value into a valid string."""78 if isinstance(value, bytes):79 try:
117 unmodified lines
197 message = message.encode(encoding, 'replace')198 file.write(message)199 file.write('\n')200 file.flush()201202203def 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.209210 :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()217218219def 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.224225 :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 lines
43.. autofunction:: confirm4445.. autofunction:: get_terminal_size4647.. autofunction:: get_binary_stream4849.. autofunction:: get_text_stream5051Commands52--------5354.. autoclass:: Command
85 unmodified lines