Skip to content
Myr

Refactored pager support to not rely on pydoc

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 c5d53f8 · Browse files · 5 files+92 added−16 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+92 added−16 removed

  • tests:+2 added−1 removed
  • other:+90 added−15 removed

5 files+92 added−16 removed

modified:click/_compat.py+17 added-6 removed
7 unmodified lines
89PY2 = sys.version_info[0] == 2101112_ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')131415def _make_text_stream(stream, encoding, errors):16 if encoding is None:17 encoding = get_best_encoding(stream)18 if errors is None:
410 unmodified lines
429 def __repr__(self):430 return repr(self._f)431432430_auto_wrap_for_ansi = lambda x: x433auto_wrap_for_ansi = None434435436try:437 import colorama
2 unmodified lines
440else:441 from weakref import WeakKeyDictionary442 _ansi_stream_wrappers = WeakKeyDictionary()443441 def _auto_wrap_for_ansi(stream):444 def auto_wrap_for_ansi(stream):445 cached = _ansi_stream_wrappers.get(stream)446 if cached is not None:447 return cached445 try:446 strip = not stream.isatty()447 except Exception:448 strip = True448 strip = not isatty(stream)449 rv = colorama.AnsiToWin32(stream, strip=strip).stream450 try:451 _ansi_stream_wrappers[stream] = rv452 except Exception:453 pass454 return rv455456457def strip_ansi(value):458 return _ansi_re.sub('', value)459460461def isatty(stream):462 try:463 return stream.isatty()464 except Exception:465 return False466467468binary_streams = {469 'stdin': get_binary_stdin,470 'stdout': get_binary_stdout,471 'stderr': get_binary_stderr,
7 unmodified lines
modified:click/_termui_impl.py+60 added-1 removed
8 unmodified lines
9 :copyright: (c) 2014 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12import os13import sys14import time15import math15from ._compat import get_text_stdout, range_type, PY216from ._compat import get_text_stdout, range_type, PY2, isatty, open_stream, \17 strip_ansi18from .utils import echo192021if os.name == 'nt':
203 unmodified lines
225226 if not PY2:227 __next__ = next228 del next229230231def pager(text):232 """Decide what method to use for paging through text."""233 stdout = get_text_stdout()234 if not isatty(sys.stdin) or not isatty(stdout):235 return _nullpager(stdout, text)236 if 'PAGER' in os.environ:237 if sys.platform == 'win32':238 return _tempfilepager(strip_ansi(text), os.environ['PAGER'])239 elif os.environ.get('TERM') in ('dumb', 'emacs'):240 return _pipepager(strip_ansi(text), os.environ['PAGER'])241 else:242 return _pipepager(text, os.environ['PAGER'])243 if os.environ.get('TERM') in ('dumb', 'emacs'):244 return _nullpager(stdout, text)245 if sys.platform == 'win32' or sys.platform.startswith('os2'):246 return _tempfilepager(strip_ansi(text), 'more <')247 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:248 return _pipepager(text, 'less')249250 import tempfile251 fd, filename = tempfile.mkstemp()252 os.close(fd)253 try:254 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:255 return _pipepager(text, 'more')256 return _nullpager(stdout, text)257 finally:258 os.unlink(filename)259260261def _pipepager(text, cmd):262 """Page through text by feeding it to another program."""263 pipe = os.popen(cmd, 'w')264 try:265 pipe.write(text)266 pipe.close()267 except IOError:268 pass269270271def _tempfilepager(text, cmd):272 """Page through text by invoking a program on a temporary file."""273 import tempfile274 filename = tempfile.mktemp()275 with open_stream(filename, 'w')[1] as f:276 f.write(text)277 try:278 os.system(cmd + ' "' + filename + '"')279 finally:280 os.unlink(filename)281282283def _nullpager(stream, text):284 """Simply print unformatted text. This is the ultimate fallback."""285 stream.write(strip_ansi(text))
modified:click/termui.py+2 added-6 removed
173 unmodified lines
174 if PY2 and isinstance(text, text_type):175 encoding = get_best_encoding(sys.stdout)176 text = text.encode(encoding, 'replace')177178 # Pydoc's pager is badly broken with LANG=C on Python 3 to the point179 # where it will corrupt the terminal. http://bugs.python.org/issue21398180 # I don't feel like reimplementing it given that it works on Python 2181 # and seems reasonably stable otherwise.182 import pydoc183 pydoc.pager(text)178 from ._termui_impl import pager179 return pager(text + '\n')180181182def progressbar(iterable=None, length=None, label=None, show_eta=True,183 show_percent=None, show_pos=None, fill_char='#',
64 unmodified lines
modified:click/utils.py+11 added-2 removed
2 unmodified lines
3from collections import deque45from ._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_ansi7 auto_wrap_for_ansi, strip_ansi, isatty89if not PY2:10 from ._compat import _find_binary_writer11
210 unmodified lines
222 :param nl: if set to `True` (the default) a newline is printed afterwards.223 """224 if file is None:225 file = sys.stdout226 file = _auto_wrap_for_ansi(file)226227 if message is not None and not isinstance(message, echo_native_types):228 message = text_type(message)229
10 unmodified lines
240 if nl:241 binary_file.write(b'\n')242 binary_file.flush()243 return244245 # If we have colorama support we wrap the stream to handle colors246 # for us. In case colorama is not supported and our output stream247 # is not a terminal, we strip the ansi codes ourselves.248 if auto_wrap_for_ansi is not None:249 file = auto_wrap_for_ansi(file)250 elif message and not isatty(file):251 message = strip_ansi(message)252253 if message:254 file.write(message)255 if nl:256 file.write('\n')257 file.flush()
101 unmodified lines
modified:tests/test_utils.py+2 added-1 removed
5 unmodified lines
6 click.echo(u'\N{SNOWMAN}')7 click.echo(b'\x44\x44')8 click.echo(42, nl=False)9 click.echo(b'a', nl=False)10 click.echo('\x1b[31mx\x1b[39m', nl=False)11 bytes = out.getvalue()11 assert bytes == b'\xe2\x98\x83\nDD\n42a'12 assert bytes == b'\xe2\x98\x83\nDD\n42ax'131415def test_filename_formatting():16 assert click.format_filename(b'foo.txt') == 'foo.txt'
5 unmodified lines