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
Provenance
- Commit
aef1650- Tree
84bbb9d- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
c5d53f8
5 files changed+92 added−16 removed
modified:click/_compat.py+17 added-6 removed
7 unmodified lines8 9 PY2 = sys.version_info[0] == 210 11 12+_ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')13+14+15 def _make_text_stream(stream, encoding, errors):16 if encoding is None:17 encoding = get_best_encoding(stream)18 if errors is None:410 unmodified lines429 def __repr__(self):430 return repr(self._f)431 432 430-_auto_wrap_for_ansi = lambda x: x433+auto_wrap_for_ansi = None434 435 436 try:437 import colorama2 unmodified lines440 else:441 from weakref import WeakKeyDictionary442 _ansi_stream_wrappers = WeakKeyDictionary()443 441- 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 rv455 456 457+def strip_ansi(value):458+ return _ansi_re.sub('', value)459+460+461+def isatty(stream):462+ try:463+ return stream.isatty()464+ except Exception:465+ return False466+467+468 binary_streams = {469 'stdin': get_binary_stdin,470 'stdout': get_binary_stdout,471 'stderr': get_binary_stderr,7 unmodified linesmodified:click/_termui_impl.py+60 added-1 removed
8 unmodified lines9 :copyright: (c) 2014 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 import os13+import sys14 import time15 import math15-from ._compat import get_text_stdout, range_type, PY216+from ._compat import get_text_stdout, range_type, PY2, isatty, open_stream, \17+ strip_ansi18 from .utils import echo19 20 21 if os.name == 'nt':203 unmodified lines225 226 if not PY2:227 __next__ = next228 del next229+230+231+def 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')249+250+ 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)259+260+261+def _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+ pass269+270+271+def _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)281+282+283+def _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 lines174 if PY2 and isinstance(text, text_type):175 encoding = get_best_encoding(sys.stdout)176 text = text.encode(encoding, 'replace')177 178- # 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')180 181 182 def progressbar(iterable=None, length=None, label=None, show_eta=True,183 show_percent=None, show_pos=None, fill_char='#',64 unmodified linesmodified:click/utils.py+11 added-2 removed
2 unmodified lines3 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_ansi7+ auto_wrap_for_ansi, strip_ansi, isatty8 9 if not PY2:10 from ._compat import _find_binary_writer11 210 unmodified lines222 :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)226 227 if message is not None and not isinstance(message, echo_native_types):228 message = text_type(message)229 10 unmodified lines240 if nl:241 binary_file.write(b'\n')242 binary_file.flush()243 return244+245+ # 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)252+253+ if message:254 file.write(message)255 if nl:256 file.write('\n')257 file.flush()101 unmodified linesmodified:tests/test_utils.py+2 added-1 removed
5 unmodified lines6 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'13 14 15 def test_filename_formatting():16 assert click.format_filename(b'foo.txt') == 'foo.txt'5 unmodified lines