Added style helpers and added deeper ansi color support. Colorama now optional.
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 d27f3a6 · Browse files · 12 files·+171 added−70 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+171 added−70 removed
- other:+171 added−70 removed
Provenance
- Commit
f516eee- Tree
d456bd4- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d27f3a6
12 files changed+171 added−70 removed
modified:click/__init__.py+2 added-2 removed
31 unmodified lines32 format_filename, get_app_dir33 34 # Terminal functions35 from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \36- progressbar, clear36+ progressbar, clear, style, unstyle37 38 # Exceptions39 from .exceptions import ClickException, UsageError, BadParameter, \40 FileError, Abort24 unmodified lines65 'get_app_dir',66 67 # Terminal functions68 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',69- 'progressbar', 'clear',69+ 'progressbar', 'clear', 'style', 'unstyle',70 71 # Exceptions72 'ClickException', 'UsageError', 'BadParameter', 'FileError',73 'Abort',10 unmodified linesmodified:click/_compat.py+25 added-20 removed
439 unmodified lines440 return repr(self._f)441 442 443 auto_wrap_for_ansi = None444+colorama = None445 446 447+# If we're on windows we provide transparent integration through448+# colorama. This will make ansi colors through the echo function449+# work automatically.450+if sys.platform.startswith('win'):446-try:447- import colorama448-except ImportError:449- colorama = None450-else:451- _ansi_stream_wrappers = WeakKeyDictionary()451+ try:452+ import colorama453+ except ImportError:454+ pass455+ else:456+ _ansi_stream_wrappers = WeakKeyDictionary()457 453- def auto_wrap_for_ansi(stream):454- try:455- cached = _ansi_stream_wrappers.get(stream)456- except Exception:457- cached = None458- if cached is not None:459- return cached460- strip = not isatty(stream)461- rv = colorama.AnsiToWin32(stream, strip=strip).stream462- try:463- _ansi_stream_wrappers[stream] = rv464- except Exception:465- pass466- return rv458+ def auto_wrap_for_ansi(stream):459+ try:460+ cached = _ansi_stream_wrappers.get(stream)461+ except Exception:462+ cached = None463+ if cached is not None:464+ return cached465+ strip = not isatty(stream)466+ rv = colorama.AnsiToWin32(stream, strip=strip).stream467+ try:468+ _ansi_stream_wrappers[stream] = rv469+ except Exception:470+ pass471+ return rv472 473 474 def strip_ansi(value):475 return _ansi_re.sub('', value)42 unmodified linesmodified:click/formatting.py+13 added-8 removed
1 import textwrap2 from contextlib import contextmanager3 4 from .termui import get_terminal_size5+from ._compat import strip_ansi6 7 8+def term_len(x):9+ return len(strip_ansi(x))10+11+12 def measure_table(rows):13 widths = {}14 for row in rows:15 for idx, col in enumerate(row):11- widths[idx] = max(widths.get(idx, 0), len(col))16+ widths[idx] = max(widths.get(idx, 0), term_len(col))17 return tuple(y for x, y in sorted(widths.items()))18 19 20 def iter_rows(rows, col_count):6 unmodified lines27 28 def _cutdown(self, ucstr, space_left):29 l = 030 for i in xrange(len(ucstr)):26- l += len(ucstr[i])31+ l += term_len(ucstr[i])32 if space_left < l:33 return (ucstr[:i], ucstr[i:])34 return ucstr, ''35 74 unmodified lines110 _flush_par()111 indent = None112 else:113 if indent is None:109- orig_len = len(line)114+ orig_len = term_len(line)115 line = line.lstrip()111- indent = orig_len - len(line)116+ indent = orig_len - term_len(line)117 buf.append(line)118 _flush_par()119 120 rv = []48 unmodified lines169 """170 prefix = '%*s%s' % (self.current_indent, prefix, prog)171 self.write(prefix)172 168- text_width = max(self.width - self.current_indent - len(prefix), 10)169- indent = ' ' * (len(prefix) + 1)173+ text_width = max(self.width - self.current_indent - term_len(prefix), 10)174+ indent = ' ' * (term_len(prefix) + 1)175 self.write(wrap_text(args, text_width,176 initial_indent=' ',177 subsequent_indent=indent))178 40 unmodified lines219 self.write('%*s%s' % (self.current_indent, '', first))220 if not second:221 self.write('\n')222 continue218- if len(first) <= first_col - col_spacing:219- self.write(' ' * (first_col - len(first)))223+ if term_len(first) <= first_col - col_spacing:224+ self.write(' ' * (first_col - term_len(first)))225 else:226 self.write('\n')227 self.write(' ' * (first_col + self.current_indent))228 37 unmodified linesmodified:click/termui.py+81 added-1 removed
1 unmodified line2 import sys3 import struct4 5 from ._compat import raw_input, PY2, text_type, string_types, \6- get_best_encoding, colorama, isatty6+ get_best_encoding, colorama, isatty, strip_ansi7 from .utils import echo8 from .exceptions import Abort, UsageError9 from .types import convert_type10 1 unmodified line12 # The prompt functions to use. The doc tools currently override these13 # functions to customize how they work.14 visible_prompt_func = raw_input15 16+_ansi_colors = ('black', 'red', 'green', 'yellow', 'blue', 'magenta',17+ 'cyan', 'white', 'reset')18+_ansi_reset_all = '\033[0m'19 20+21 def hidden_prompt_func(prompt):22 import getpass23 return getpass.getpass(prompt)24 246 unmodified lines271 if sys.platform.startswith('win') and colorama is None:272 os.system('cls')273 else:274 sys.stdout.write('\033[2J\033[1;1H')275+276+277+def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,278+ blink=None, reverse=None, reset=True):279+ """Styles a text with ANSI styles and returns the new string. By280+ default the styling is self contained which means that at the end281+ of the string a reset code is issued. This can be prevented by282+ passing ``reset=False``.283+284+ Examples::285+286+ click.echo(click.style('Hello World!', fg='green'))287+ click.echo(click.style('ATTENTION!', blink=True))288+ click.echo(click.style('Some things', reverse=True, fg='cyan'))289+290+ Supported color names:291+292+ * ``black`` (might be a gray)293+ * ``red``294+ * ``green``295+ * ``yellow`` (might be an orange)296+ * ``blue``297+ * ``magenta``298+ * ``cyan``299+ * ``white`` (might be light gray)300+ * ``reset`` (reset the color code only)301+302+ :param text: the string to style with ansi codes.303+ :param fg: if provided this will become the foreground color.304+ :param bg: if provided this will become the background color.305+ :param bold: if provided this will enable or disable bold mode.306+ :param dim: if provided this will enable or disable dim mode.307+ :param underline: if provided this will enable or disable underline.308+ :param blink: if provided this will enable or disable blinking.309+ :param reverse: if provided this will enable or disable inverse310+ rendering (foreground becomes background and the311+ other way round).312+ :param reset: by default a reset-all code is added at the end of the313+ string which means that styles do not carry over. This314+ can be disabled to compose styles.315+ """316+ bits = []317+ if fg:318+ try:319+ bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30))320+ except ValueError:321+ raise TypeError('Unknown color %r' % fg)322+ if bg:323+ try:324+ bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40))325+ except ValueError:326+ raise TypeError('Unknown color %r' % bg)327+ if bold is not None:328+ bits.append('\033[%dm' % (1 if bold else 22))329+ if dim is not None:330+ bits.append('\033[%dm' % (2 if bold else 22))331+ if underline is not None:332+ bits.append('\033[%dm' % (4 if underline else 24))333+ if blink is not None:334+ bits.append('\033[%dm' % (5 if blink else 25))335+ if reverse is not None:336+ bits.append('\033[%dm' % (7 if reverse else 27))337+ bits.append(text)338+ if reset:339+ bits.append(_ansi_reset_all)340+ return ''.join(bits)341+342+343+def unstyle(text):344+ """Removes ANSI styling information from a string. Usually it's not345+ necessary to use this function as click's echo function will346+ automatically remove styling if necessary.347+348+ :param text: the text to remove style information from.349+ """350+ return strip_ansi(text)modified:click/utils.py+7 added-9 removed
242 unmodified lines243 binary_file.write(b'\n')244 binary_file.flush()245 return246 247- # If we have colorama support we wrap the stream to handle colors248- # for us. In case colorama is not supported and our output stream249- # is not a terminal, we strip the ansi codes ourselves. We also250- # do not do the stripping if we're dealing with true bytes (this will251- # only ever be reached on python 2 where is_bytes is true for buffers252- # and bytearrays but not for regular strings).247+ # ANSI style support. If there is no message or we are dealing with248+ # bytes nothing is happening. If we are connected to a file we want249+ # to strip colors. If we have support for wrapping streams (windows250+ # through colorama) we want to do that.251 if message and not is_bytes(message):254- if auto_wrap_for_ansi is not None:255- file = auto_wrap_for_ansi(file)256- elif not isatty(file):252+ if not isatty(file):253 message = strip_ansi(message)254+ elif auto_wrap_for_ansi is not None:255+ file = auto_wrap_for_ansi(file)256 257 if message:258 file.write(message)259 if nl:103 unmodified linesmodified:docs/quickstart.rst+3 added-2 removed
87 unmodified lines88 correction in case the terminal is misconfigured instead of dying with an89 :exc:`UnicodeError`.90 91 As an added benefit, starting with click 2.0 the echo function also92-supports portable ANSI coloring if colorama is installed. See93-:ref:`ansi-colors` for more information.92+has good support for ANSI colors. It will automatically strip ANSI codes93+if the output stream is a file and if colorama is supported, ANSI colors94+will also work on Windows. See :ref:`ansi-colors` for more information.95 96 If you don't need this, you can also use the `print()` construct /97 function.98 66 unmodified linesmodified:docs/utils.rst+10 added-11 removed
36 unmodified lines37 -----------38 39 .. versionadded:: 2.040 41-Starting with click 2.0 the :func:`echo` function gained a bit of extra42-functionality to deal with ANSI colors. This functionality is only43-available if `colorama`_ is installed. If it is installed then ANSI codes44-are intelligently handled.41+Starting with click 2.0 the :func:`echo` function gained extra42+functionality to deal with ANSI colors and styles. Note that on Windows43+this functionality is only available if `colorama`_ is installed. If it44+is installed then ANSI codes are intelligently handled.45 46 Primarily this means that:47 48 - click's echo function will automatically strip ANSI color codes if the2 unmodified lines51 Windows and translate ANSI codes to terminal API calls. This means52 that colors will work on Windows the same way they do on other53 operating systems.54 55-Click will automatically detect when `colorama` is available and use it.56-You do not have to call ``colorama.init()``. In fact, it's strongly57-recommended you not doing that as colorama will change the default output58-streams which is not a good idea.55+Note for colorama support: click will automatically detect when `colorama`56+is available and use it. Do *not* call ``colorama.init()``!57 58 To install colorama run this command::59 60 $ pip install colorama61 64-Example that prints green text::62+For styling a string the :func:`style` function can be used::63 64 import click67- from colorama import Fore65 69- click.echo(Fore.GREEN + 'Hello World!' + Fore.RESET)66+ click.echo(click.style('Hello World!', fg='green'))67+ click.echo(click.style('Some more text', bg='blue', fg='white'))68+ click.echo(click.style('ATTENTION', blink=True))69 70 71 .. _colorama: https://pypi.python.org/pypi/colorama72 133 unmodified linesmodified:examples/colors/colors.py+18 added-6 removed
1 import click2-from colorama import Fore2 3 4+all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \5+ 'cyan', 'white'6+7+8 @click.command()9 def cli():7- """This script prints some colors through colorama. This will give8- colors on OS X, Linux and Windows but it will automatically disable9- those colors if stdout is redirected to a file.10+ """This script prints some colors. If colorama is installed this will11+ also work on Windows. It will also automatically remove all ANSI12+ styles if data is piped into a file.13 14 Give it a try!15 """13- click.echo(Fore.YELLOW + 'Hello World!' + Fore.RESET)14- click.echo(Fore.RED + 'Goodbye World!' + Fore.RESET)16+ for color in all_colors:17+ click.echo(click.style('I am colored %s' % color, fg=color))18+ for color in all_colors:19+ click.echo(click.style('I am colored %s and bold' % color,20+ fg=color, bold=True))21+ for color in all_colors:22+ click.echo(click.style('I am reverse colored %s' % color, fg=color,23+ reverse=True))24+25+ click.echo(click.style('I am blinking', blink=True))26+ click.echo(click.style('I am underlined', underline=True))modified:examples/colors/README+3 added-1 removed
1 $ colors_2 3 colors is a simple example that shows how you can4- colorize text with the built-in colorama integration.4+ colorize text.5 6+ For this to work on Windows, colorama is required.7+8 Usage:9 10 $ pip install --editable .11 $ colorsmodified:examples/colors/setup.py+1 added
5 unmodified lines6 py_modules=['colors'],7 include_package_data=True,8 install_requires=[9 'Click',10+ # Colorama is only required for windows.11 'colorama',12 ],13 entry_points='''14 [console_scripts]3 unmodified linesmodified:examples/termui/setup.py+1 added
5 unmodified lines6 py_modules=['termui'],7 include_package_data=True,8 install_requires=[9 'Click',10+ # Colorama is only required for windows.11 'colorama',12 ],13 entry_points='''14 [console_scripts]3 unmodified linesmodified:examples/termui/termui.py+7 added-10 removed
1 # coding: utf-82 import click3 import time4 import random5-from colorama import Fore5 6 try:7 range_type = xrange8 except NameError:8 unmodified lines17 18 @cli.command()19 def colordemo():20 """Demonstrates ANSI color support."""22- click.echo(Fore.YELLOW + 'Hello World!' + Fore.RESET)21+ for color in 'red', 'green', 'blue':22+ click.echo(click.style('I am colored %s' % color, fg=color))23+ click.echo(click.style('I am background colored %s' % color, bg=color))24 25 26 @cli.command()27 def pager():28 """Demonstrates using the pager."""29 lines = []30 for x in xrange(200):30- lines.append('%s%d%s. Hello World!' % (31- Fore.GREEN,32- x,33- Fore.RESET34- ))31+ lines.append('%s. Hello World!' % click.style(str(x), fg='green'))32 click.echo_via_pager('\n'.join(lines))33 34 35 @cli.command()11 unmodified lines47 if random.random() > 0.3:48 yield item49 50 with click.progressbar(items, label='Processing user accounts',54- fill_char=Fore.GREEN + '#' + Fore.RESET) as bar:51+ fill_char=click.style('#', fg='green')) as bar:52 for item in bar:53 process_slowly(item)54 55 def show_item(item):56 if item is not None:57 return 'Item #%d' % item58 59 with click.progressbar(filter(items), label='Committing transaction',63- fill_char=Fore.YELLOW + '#' + Fore.RESET,60+ fill_char=click.style('#', fg='yellow'),61 item_show_func=show_item) as bar:62 for item in bar:63 process_slowly(item)64 65 with click.progressbar(length=count, label='Counting',66 bar_template='%(label)s %(bar)s | %(info)s',70- fill_char=Fore.BLUE + u'█' + Fore.RESET,67+ fill_char=click.style(u'█', fg='cyan'),68 empty_char=' ') as bar:69 for item in bar:70 process_slowly(item)71 5 unmodified lines