Unbroke colorama integrated echo for unicode.
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 aef1650 · Browse files · 4 files·+64 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+64 added−20 removed
- tests:+19 added−0 removed
- other:+45 added−20 removed
Provenance
- Commit
537d6d5- Tree
2270ef8- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
aef1650
4 files changed+64 added−20 removed
modified:click/_compat.py+33 added-5 removed
2 unmodified lines3 import os4 import sys5 import codecs6 import tempfile7+from weakref import WeakKeyDictionary8 9 10 PY2 = sys.version_info[0] == 211 36 unmodified lines48 # python 3 text behavior forced on, so we need to unbreak49 # it to look like python 2 stuff.50 if PY2:51 def write(self, x):52+ if isinstance(x, str):53+ self.flush()54+ return self.buffer.write(x)51- return io.TextIOWrapper.write(self, unicode(x))55+ return io.TextIOWrapper.write(self, x)56 57 def writelines(self, lines):54- lines = map(unicode, lines)55- return io.TextIOWrapper.writelines(self, lines)58+ for line in lines:59+ self.write(line)60 61 def __del__(self):62 try:63 self.detach()377 unmodified lines441 import colorama442 except ImportError:443 colorama = None444 else:441- from weakref import WeakKeyDictionary445 _ansi_stream_wrappers = WeakKeyDictionary()446 447 def auto_wrap_for_ansi(stream):448+ try:445- cached = _ansi_stream_wrappers.get(stream)449+ cached = _ansi_stream_wrappers.get(stream)450+ except Exception:451+ cached = None452 if cached is not None:453 return cached454 strip = not isatty(stream)455 rv = colorama.AnsiToWin32(stream, strip=strip).stream14 unmodified lines470 except Exception:471 return False472 473 474+_default_text_cache = WeakKeyDictionary()475+476+477+def _default_text_stdout():478+ """Like :func:`get_text_stdout` but uses a cache if available to speed479+ it up. This will not create streams over and over again.480+ """481+ stream = sys.stdout482+ try:483+ rv = _default_text_cache.get(stream)484+ except Exception:485+ rv = None486+ if rv is not None:487+ return rv488+ rv = get_text_stdout()489+ try:490+ _default_text_cache[stream] = rv491+ except Exception:492+ pass493+ return rv494+495+496 binary_streams = {497 'stdin': get_binary_stdin,498 'stdout': get_binary_stdout,499 'stderr': get_binary_stderr,7 unmodified linesmodified:click/_termui_impl.py+8 added-7 removed
11 unmodified lines12 import os13 import sys14 import time15 import math16-from ._compat import get_text_stdout, range_type, PY2, isatty, open_stream, \17- strip_ansi16+from ._compat import _default_text_stdout, range_type, PY2, isatty, \17+ open_stream, strip_ansi18 from .utils import echo19 20 21 if os.name == 'nt':38 unmodified lines60 self.show_percent = show_percent61 self.show_pos = show_pos62 self.label = label or ''63 if file is None:64- file = get_text_stdout()64+ file = _default_text_stdout()65 self.file = file66 self.width = width67 68 if length is None:74 unmodified lines143 show_pos = self.show_pos144 145 info_bits = []146 if self.length_known:147- bar = self.fill_char * int(self.pct * self.width)148- bar += self.empty_char * (self.width - len(bar))147+ bar_length = int(self.pct * self.width)148+ bar = self.fill_char * bar_length149+ bar += self.empty_char * (self.width - bar_length)150 if show_percent is None:151 show_percent = not show_pos152 else:153 if self.finished:1 unmodified line155 else:156 bar = list(self.empty_char * self.width)157 if self.time_per_iteration != 0:158 bar[int((math.cos(self.pos * self.time_per_iteration)158- / 2.0 + 0.5) * len(bar))] = self.fill_char159+ / 2.0 + 0.5) * self.width)] = self.fill_char160 bar = ''.join(bar)161 if show_pos is None:162 show_pos = True163 66 unmodified lines230 231 232 def pager(text):233 """Decide what method to use for paging through text."""233- stdout = get_text_stdout()234+ stdout = _default_text_stdout()235 if not isatty(sys.stdin) or not isatty(stdout):236 return _nullpager(stdout, text)237 if 'PAGER' in os.environ:238 if sys.platform == 'win32':48 unmodified linesmodified:click/utils.py+4 added-8 removed
1 unmodified line2 import sys3 from collections import deque4 5 from ._compat import text_type, open_stream, get_streerror, string_types, \6- PY2, get_best_encoding, binary_streams, text_streams, filename_to_ui, \7- auto_wrap_for_ansi, strip_ansi, isatty6+ PY2, binary_streams, text_streams, filename_to_ui, \7+ auto_wrap_for_ansi, strip_ansi, isatty, _default_text_stdout8 9 if not PY2:10 from ._compat import _find_binary_writer11 209 unmodified lines221 :param file: the file to write to (defaults to ``stdout``)222 :param nl: if set to `True` (the default) a newline is printed afterwards.223 """224 if file is None:225- file = sys.stdout225+ file = _default_text_stdout()226 227 if message is not None and not isinstance(message, echo_native_types):228 message = text_type(message)229 230 if message:231- if PY2:232- if isinstance(message, text_type):233- encoding = get_best_encoding(file)234- message = message.encode(encoding, 'replace')235- elif isinstance(message, (bytes, bytearray)):231+ if not PY2 and isinstance(message, (bytes, bytearray)):232 binary_file = _find_binary_writer(file)233 if binary_file is not None:234 file.flush()235 binary_file.write(message)119 unmodified linesmodified:tests/test_utils.py+19 added
1+import sys2 import click3 4 5 def test_echo(runner):5 unmodified lines11 click.echo('\x1b[31mx\x1b[39m', nl=False)12 bytes = out.getvalue()13 assert bytes == b'\xe2\x98\x83\nDD\n42ax'14 15+ # If we are on python 2 we expect that writing bytes into a string io16+ # does not do anything crazy. On Python 317+ if sys.version_info[0] == 2:18+ import StringIO19+ sys.stdout = x = StringIO.StringIO()20+ try:21+ click.echo('\xf6')22+ finally:23+ sys.stdout = sys.__stdout__24+ assert x.getvalue() == '\xf6\n'25 26+ # And in any case, if wrapped, we expect bytes to survive.27+ @click.command()28+ def cli():29+ click.echo(b'\xf6')30+ result = runner.invoke(cli, [])31+ assert result.output_bytes == b'\xf6\n'32+33+34 def test_filename_formatting():35 assert click.format_filename(b'foo.txt') == 'foo.txt'36 assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt'37 assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt'3 unmodified lines