Added support for explicit color control.
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 e413626 · Browse files · 9 files·+95 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+95 added−26 removed
- tests:+27 added−0 removed
- other:+68 added−26 removed
Provenance
- Commit
5cf7f2d- Tree
7648f8f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e413626
9 files changed+95 added−26 removed
modified:click/_compat.py+14 added-6 removed
454 unmodified lines455 colorama = None456 get_winterm_size = None457 458 459+def strip_ansi(value):460+ return _ansi_re.sub('', value)461+462+463+def should_strip_ansi(stream=None, color=None):464+ if color is None:465+ if stream is None:466+ stream = sys.stdin467+ return not isatty(stream)468+ return not color469+470+471 # If we're on Windows, we provide transparent integration through472 # colorama. This will make ANSI colors through the echo function473 # work automatically.474 if WIN:6 unmodified lines481 pass482 else:483 _ansi_stream_wrappers = WeakKeyDictionary()484 473- def auto_wrap_for_ansi(stream):485+ def auto_wrap_for_ansi(stream, color=None):486 """This function wraps a stream so that calls through colorama487 are issued to the win32 console API to recolor on demand. It488 also ensures to reset the colors if a write call is interrupted489 to not destroy the console afterwards.3 unmodified lines493 except Exception:494 cached = None495 if cached is not None:496 return cached485- strip = not isatty(stream)497+ strip = should_strip_ansi(stream, color)498 ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)499 rv = ansi_wrapper.stream500 _write = rv.write501 16 unmodified lines518 colorama.win32.STDOUT).srWindow519 return win.Right - win.Left, win.Bottom - win.Top520 521 510-def strip_ansi(value):511- return _ansi_re.sub('', value)512-513-522 def term_len(x):523 return len(strip_ansi(x))524 525 43 unmodified linesmodified:click/_termui_impl.py+4 added-3 removed
50 unmodified lines51 52 def __init__(self, iterable, length=None, fill_char='#', empty_char=' ',53 bar_template='%(bar)s', info_sep=' ', show_eta=True,54 show_percent=None, show_pos=False, item_show_func=None,55- label=None, file=None, width=30):55+ label=None, file=None, color=None, width=30):56 self.fill_char = fill_char57 self.empty_char = empty_char58 self.bar_template = bar_template59 self.info_sep = info_sep4 unmodified lines64 self.label = label or ''65 if file is None:66 file = _default_text_stdout()67 self.file = file68+ self.color = color69 self.width = width70 self.autowidth = width == 071 72 if length is None:107 unmodified lines180 def render_progress(self):181 from .termui import get_terminal_size182 183 if self.is_hidden:183- echo(self.label, file=self.file)184+ echo(self.label, file=self.file, color=self.color)185 self.file.flush()186 return187 188 # Update width in case the terminal has been resized17 unmodified lines206 line_len = term_len(line)207 if self.max_width is None or self.max_width < line_len:208 self.max_width = line_len209 # Use echo here so that we get colorama support.209- echo(line, file=self.file, nl=False)210+ echo(line, file=self.file, nl=False, color=self.color)211 self.file.write(' ' * (clear_width - line_len))212 self.file.flush()213 214 def make_step(self):295 unmodified linesmodified:click/core.py+18 added-3 removed
105 unmodified lines106 .. versionadded:: 3.0107 Added the `allow_extra_args` and `allow_interspersed_args`108 parameters.109 110+ .. versionadded:: 4.0111+ Added the `color` parameter.112+113 :param command: the command class for this context.114 :param parent: the parent context.115 :param info_name: the info name for this invokation. Generally this116 is the most descriptive name for the script or29 unmodified lines146 :param token_normalize_func: an optional function that is used to147 normalize tokens (options, choices,148 etc.). This for instance can be used to149 implement case insensitive behavior.150+ :param color: controls if the terminal supports ANSI colors or not. The151+ default is autodetection. This is only needed if ANSI152+ codes are used in texts that Click prints which is by153+ default not the case. This for instance would affect154+ help output.155 """156 157 def __init__(self, command, parent=None, info_name=None, obj=None,158 auto_envvar_prefix=None, default_map=None,159 terminal_width=None, resilient_parsing=False,160 allow_extra_args=None, allow_interspersed_args=None,153- help_option_names=None, token_normalize_func=None):161+ help_option_names=None, token_normalize_func=None,162+ color=None):163 #: the parent context or `None` if none exists.164 self.parent = parent165 #: the :class:`Command` for this context.166 self.command = command77 unmodified lines244 else:245 self.auto_envvar_prefix = auto_envvar_prefix.upper()246 self.auto_envvar_prefix = auto_envvar_prefix247 248+ if color is None and parent is not None:249+ color = parent.color250+251+ #: Controls if styling output is wanted or not.252+ self.color = color253+254 self._close_callbacks = []255 self._depth = 0256 257 def __enter__(self):450 unmodified lines708 return709 710 def show_help(ctx, param, value):711 if value and not ctx.resilient_parsing:697- echo(ctx.get_help())712+ echo(ctx.get_help(), color=ctx.color)713 ctx.exit()714 return Option(help_options, is_flag=True,715 is_eager=True, expose_value=False,716 callback=show_help,190 unmodified lines907 formatter.write_dl(rows)908 909 def parse_args(self, ctx, args):910 if not args and self.no_args_is_help and not ctx.resilient_parsing:896- echo(ctx.get_help())911+ echo(ctx.get_help(), color=ctx.color)912 ctx.exit()913 return Command.parse_args(self, ctx, args)914 915 def invoke(self, ctx):671 unmodified linesmodified:click/decorators.py+2 added-2 removed
251 unmodified lines252 raise RuntimeError('Could not determine version')253 echo(message % {254 'prog': prog,255 'version': ver,256- })256+ }, color=ctx.color)257 ctx.exit()258 259 attrs.setdefault('is_flag', True)260 attrs.setdefault('expose_value', False)16 unmodified lines277 """278 def decorator(f):279 def callback(ctx, param, value):280 if value and not ctx.resilient_parsing:281- echo(ctx.get_help())281+ echo(ctx.get_help(), color=ctx.color)282 ctx.exit()283 attrs.setdefault('is_flag', True)284 attrs.setdefault('expose_value', False)285 attrs.setdefault('help', 'Show this message and exit.')8 unmodified linesmodified:click/exceptions.py+4 added-2 removed
39 unmodified lines40 41 def show(self, file=None):42 if file is None:43 file = get_text_stderr()44+ color = None45 if self.ctx is not None:46+ color = self.ctx.color45- echo(self.ctx.get_usage() + '\n', file=file)46- echo('Error: %s' % self.format_message(), file=file)47+ echo(self.ctx.get_usage() + '\n', file=file, color=color)48+ echo('Error: %s' % self.format_message(), file=file, color=color)49 50 51 class BadParameter(UsageError):52 """An exception that formats out a standardized error message for a51 unmodified linesmodified:click/termui.py+11 added-5 removed
195 unmodified lines196 def progressbar(iterable=None, length=None, label=None, show_eta=True,197 show_percent=None, show_pos=False,198 item_show_func=None, fill_char='#', empty_char='-',199 bar_template='%(label)s [%(bar)s] %(info)s',200- info_sep=' ', width=36, file=None):200+ info_sep=' ', width=36, file=None, color=None):201 """This function creates an iterable context manager that can be used202 to iterate over something while showing a progress bar. It will203 either iterate over the `iterable` or `length` items (that are counted204 up). While iteration happens, this function will print a rendered17 unmodified lines222 do_something_with(item)223 224 .. versionadded:: 2.0225 226+ .. versionadded:: 4.0227+ Added the `color` parameter.228+229 :param iterable: an iterable to iterate over. If not provided the length230 is required.231 :param length: the number of items to iterate over. By default the232 progressbar will attempt to ask the iterator about its26 unmodified lines259 :param width: the width of the progress bar in characters, 0 means full260 terminal width261 :param file: the file to write to. If this is not a terminal then262 only the label is printed.263+ :param color: controls if the terminal supports ANSI colors or not. The264+ default is autodetection. This is only needed if ANSI265+ codes are included anywhere in the progress bar output266+ which is not the case by default.267 """268 from ._termui_impl import ProgressBar269 return ProgressBar(iterable=iterable, length=length, show_eta=show_eta,270 show_percent=show_percent, show_pos=show_pos,271 item_show_func=item_show_func, fill_char=fill_char,272 empty_char=empty_char, bar_template=bar_template,273 info_sep=info_sep, file=file, label=label,267- width=width)274+ width=width, color=color)275 276 277 def clear():278 """Clears the terminal screen. This will have the effect of clearing93 unmodified lines372 """373 return strip_ansi(text)374 375 369-def secho(text, file=None, nl=True, err=False, **styles):376+def secho(text, file=None, nl=True, err=False, color=None, **styles):377 """This function combines :func:`echo` and :func:`style` into one378 call. As such the following two calls are the same::379 380 click.secho('Hello World!', fg='green')3 unmodified lines384 depending on which one they go with.385 386 .. versionadded:: 2.0387 """381- text = style(text, **styles)382- return echo(text, file=file, nl=nl, err=err)388+ return echo(style(text, **styles), file=file, nl=nl, err=err, color=color)389 390 391 def edit(text=None, editor=None, env=None, require_save=True,392 extension='.txt', filename=None):110 unmodified linesmodified:click/utils.py+10 added-5 removed
2 unmodified lines3 from collections import deque4 5 from ._compat import text_type, open_stream, get_streerror, string_types, \6 PY2, binary_streams, text_streams, filename_to_ui, \7- auto_wrap_for_ansi, strip_ansi, isatty, _default_text_stdout, \8- _default_text_stderr, is_bytes, WIN7+ auto_wrap_for_ansi, strip_ansi, should_strip_ansi, \8+ _default_text_stdout, _default_text_stderr, is_bytes, WIN9 10 if not PY2:11 from ._compat import _find_binary_writer12 196 unmodified lines209 def __repr__(self):210 return repr(self._file)211 212 213-def echo(message=None, file=None, nl=True, err=False):213+def echo(message=None, file=None, nl=True, err=False, color=None):214 """Prints a message plus a newline to the given file or stdout. On215 first sight, this looks like the print function, but it has improved216 support for handling Unicode and binary data that does not fail no217 matter how badly configured the system is.19 unmodified lines237 238 .. versionadded:: 3.0239 The `err` parameter was added.240 241+ .. versionchanged:: 4.0242+ Added the `color` flag.243+244 :param message: the message to print245 :param file: the file to write to (defaults to ``stdout``)246 :param err: if set to true the file defaults to ``stderr`` instead of247 ``stdout``. This is faster and easier than calling248 :func:`get_text_stderr` yourself.249 :param nl: if set to `True` (the default) a newline is printed afterwards.250+ :param color: controls if the terminal supports ANSI colors or not. The251+ default is autodetection.252 """253 if file is None:254 if err:255 file = _default_text_stderr()24 unmodified lines280 # to strip colors. If we are on windows we either wrap the stream281 # to strip the color or we use the colorama support to translate the282 # ansi codes to API calls.283 if message and not is_bytes(message):279- if not isatty(file):284+ if should_strip_ansi(file, color):285 message = strip_ansi(message)286 elif WIN:287 if auto_wrap_for_ansi is not None:288 file = auto_wrap_for_ansi(file)284- else:289+ elif not color:290 message = strip_ansi(message)291 292 if message:293 file.write(message)137 unmodified linesmodified:tests/test_utils.py+27 added
122 unmodified lines123 out, err = capfd.readouterr()124 assert out == 'haha\n'125 126 127+def test_echo_color_flag(monkeypatch, capfd):128+ isatty = True129+ monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty)130+131+ text = 'foo'132+ styled_text = click.style(text, fg='red')133+ assert styled_text == '\x1b[31mfoo\x1b[0m'134+135+ click.echo(styled_text, color=False)136+ out, err = capfd.readouterr()137+ assert out == text + '\n'138+139+ click.echo(styled_text, color=True)140+ out, err = capfd.readouterr()141+ assert out == styled_text + '\n'142+143+ isatty = True144+ click.echo(styled_text)145+ out, err = capfd.readouterr()146+ assert out == styled_text + '\n'147+148+ isatty = False149+ click.echo(styled_text)150+ out, err = capfd.readouterr()151+ assert out == text + '\n'152+153+154 def test_open_file(runner):155 with runner.isolated_filesystem():156 with open('hello.txt', 'w') as f:157 f.write('Cool stuff')15 unmodified linesmodified:CHANGES+5 added
6 unmodified lines7 -----------8 9 (codename to be selected, release date to be decided)10 11+- Added `color` parameters to lots of interfaces that directly or indirectly12+ call into echoing. This previously was always autodetection (which the13+ exception of the `echo_via_pager` function). Now you can forcefully14+ enable or disable it, overriding the auto detection of Click.15+16 Version 3.217 -----------18 19 (bugfix release, release date to be decided)162 unmodified lines