Skip to content
Myr

Merge branch 'master' into upstream

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by JosiahDub · committed by GitHub · parents 9261af6, 16da1e9 · Browse files · 35 files+894 added−227 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

35 files+894 added−227 removed

  • tests:+340 added−37 removed
  • other:+554 added−190 removed

35 files+894 added−227 removed

modified:click/_termui_impl.py+94 added-75 removed
11 unmodified lines
12import os13import sys14import time15import math16import contextlib17from ._compat import _default_text_stdout, range_type, PY2, isatty, \18 open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \19 CYGWIN20from .utils import echo
68 unmodified lines
89 self.entered = False90 self.current_item = None91 self.is_hidden = not isatty(self.file)92 self._last_line = None93 self.short_limit = 0.59495 def __enter__(self):96 self.entered = True97 self.render_progress()
5 unmodified lines
103 def __iter__(self):104 if not self.entered:105 raise RuntimeError('You need to use progress bars in a with block.')106 self.render_progress()105 return self107 return self.generator()108109 def is_fast(self):110 return time.time() - self.start <= self.short_limit111112 def render_finish(self):108 if self.is_hidden:113 if self.is_hidden or self.is_fast():114 return115 self.file.write(AFTER_BAR)116 self.file.flush()117
16 unmodified lines
134 return 0.0135136 def format_eta(self):137 if self.eta_known:133 t = self.eta + 1138 t = int(self.eta)139 seconds = t % 60135 t /= 60140 t //= 60141 minutes = t % 60137 t /= 60142 t //= 60143 hours = t % 24139 t /= 24144 t //= 24145 if t > 0:146 days = t147 return '%dd %02d:%02d:%02d' % (days, hours, minutes, seconds)148 else:
47 unmodified lines
196 }).rstrip()197198 def render_progress(self):199 from .termui import get_terminal_size195 nl = False200201 if self.is_hidden:198 buf = [self.label]199 nl = True200 else:201 buf = []202 # Update width in case the terminal has been resized203 if self.autowidth:204 old_width = self.width205 self.width = 0206 clutter_length = term_len(self.format_progress_line())207 new_width = max(0, get_terminal_size()[0] - clutter_length)208 if new_width < old_width:209 buf.append(BEFORE_BAR)210 buf.append(' ' * self.max_width)211 self.max_width = new_width212 self.width = new_width202 return203214 clear_width = self.width215 if self.max_width is not None:216 clear_width = self.max_width204 buf = []205 # Update width in case the terminal has been resized206 if self.autowidth:207 old_width = self.width208 self.width = 0209 clutter_length = term_len(self.format_progress_line())210 new_width = max(0, get_terminal_size()[0] - clutter_length)211 if new_width < old_width:212 buf.append(BEFORE_BAR)213 buf.append(' ' * self.max_width)214 self.max_width = new_width215 self.width = new_width216218 buf.append(BEFORE_BAR)219 line = self.format_progress_line()220 line_len = term_len(line)221 if self.max_width is None or self.max_width < line_len:222 self.max_width = line_len223 buf.append(line)217 clear_width = self.width218 if self.max_width is not None:219 clear_width = self.max_width220225 buf.append(' ' * (clear_width - line_len))226 line = ''.join(buf)221 buf.append(BEFORE_BAR)222 line = self.format_progress_line()223 line_len = term_len(line)224 if self.max_width is None or self.max_width < line_len:225 self.max_width = line_len226227 buf.append(line)228 buf.append(' ' * (clear_width - line_len))229 line = ''.join(buf)230 # Render the line only if it changed.231229 if line != self._last_line:232 if line != self._last_line and not self.is_fast():233 self._last_line = line231 echo(line, file=self.file, color=self.color, nl=nl)234 echo(line, file=self.file, color=self.color, nl=True)235 self.file.flush()236237 def make_step(self, n_steps):238 self.pos += n_steps
16 unmodified lines
255 self.eta_known = 0256 self.current_item = None257 self.finished = True258256 def next(self):259 def generator(self):260 """261 Returns a generator which yields the items added to the bar during262 construction, and updates the progress bar *after* the yielded block263 returns.264 """265 if not self.entered:266 raise RuntimeError('You need to use progress bars in a with block.')267268 if self.is_hidden:258 return next(self.iter)259 try:260 rv = next(self.iter)261 self.current_item = rv262 except StopIteration:269 for rv in self.iter:270 yield rv271 else:272 for rv in self.iter:273 self.current_item = rv274 yield rv275 self.update(1)276 self.finish()277 self.render_progress()265 raise StopIteration()266 else:267 self.update(1)268 return rv278270 if not PY2:271 __next__ = next272 del next279274275def pager(text, color=None):280def pager(generator, color=None):281 """Decide what method to use for paging through text."""282 stdout = _default_text_stdout()283 if not isatty(sys.stdin) or not isatty(stdout):279 return _nullpager(stdout, text, color)284 return _nullpager(stdout, generator, color)285 pager_cmd = (os.environ.get('PAGER', None) or '').strip()286 if pager_cmd:287 if WIN:283 return _tempfilepager(text, pager_cmd, color)284 return _pipepager(text, pager_cmd, color)288 return _tempfilepager(generator, pager_cmd, color)289 return _pipepager(generator, pager_cmd, color)290 if os.environ.get('TERM') in ('dumb', 'emacs'):286 return _nullpager(stdout, text, color)291 return _nullpager(stdout, generator, color)292 if WIN or sys.platform.startswith('os2'):288 return _tempfilepager(text, 'more <', color)293 return _tempfilepager(generator, 'more <', color)294 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:290 return _pipepager(text, 'less', color)295 return _pipepager(generator, 'less', color)296297 import tempfile298 fd, filename = tempfile.mkstemp()299 os.close(fd)300 try:301 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:297 return _pipepager(text, 'more', color)298 return _nullpager(stdout, text, color)302 return _pipepager(generator, 'more', color)303 return _nullpager(stdout, generator, color)304 finally:305 os.unlink(filename)306307303def _pipepager(text, cmd, color):308def _pipepager(generator, cmd, color):309 """Page through text by feeding it to another program. Invoking a310 pager through this might support colors.311 """312 import subprocess
9 unmodified lines
322 color = True323 elif 'r' in less_flags or 'R' in less_flags:324 color = True325321 if not color:322 text = strip_ansi(text)323326 c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,327 env=env)328 encoding = get_best_encoding(c.stdin)329 try:328 c.stdin.write(text.encode(encoding, 'replace'))329 c.stdin.close()330 for text in generator:331 if not color:332 text = strip_ansi(text)333334 c.stdin.write(text.encode(encoding, 'replace'))335 except (IOError, KeyboardInterrupt):336 pass337 else:338 c.stdin.close()339340 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting341 # search or other commands inside less).342 #
10 unmodified lines
353 else:354 break355356350def _tempfilepager(text, cmd, color):357def _tempfilepager(generator, cmd, color):358 """Page through text by invoking a program on a temporary file."""359 import tempfile360 filename = tempfile.mktemp()361 # TODO: This never terminates if the passed generator never terminates.362 text = "".join(generator)363 if not color:364 text = strip_ansi(text)365 encoding = get_best_encoding(sys.stdout)366 with open_stream(filename, 'wb')[0] as f:
3 unmodified lines
370 finally:371 os.unlink(filename)372373365def _nullpager(stream, text, color):374def _nullpager(stream, generator, color):375 """Simply print unformatted text. This is the ultimate fallback."""376 for text in generator:367 if not color:368 text = strip_ansi(text)369 stream.write(text)377 if not color:378 text = strip_ansi(text)379 stream.write(text)380381382class Editor(object):383
140 unmodified lines
524525if WIN:526 import msvcrt527528 @contextlib.contextmanager529 def raw_terminal():530 yield531532 def getchar(echo):533 rv = msvcrt.getch()534 if echo:535 msvcrt.putchar(rv)
8 unmodified lines
544else:545 import tty546 import termios547534 def getchar(echo):548 @contextlib.contextmanager549 def raw_terminal():550 if not isatty(sys.stdin):551 f = open('/dev/tty')552 fd = f.fileno()553 else:
2 unmodified lines
556 try:557 old_settings = termios.tcgetattr(fd)558 try:559 tty.setraw(fd)545 ch = os.read(fd, 32)546 if echo and isatty(sys.stdout):547 sys.stdout.write(ch)560 yield fd561 finally:562 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)563 sys.stdout.flush()564 if f is not None:565 f.close()566 except termios.error:567 pass568569 def getchar(echo):570 with raw_terminal() as fd:571 ch = os.read(fd, 32)572 if echo and isatty(sys.stdout):573 sys.stdout.write(ch)555 _translate_ch_to_exc(ch)556 return ch.decode(get_best_encoding(sys.stdin), 'replace')574 _translate_ch_to_exc(ch)575 return ch.decode(get_best_encoding(sys.stdin), 'replace')
modified:click/core.py+81 added-17 removed
1import errno2import inspect3import os4import sys5from contextlib import contextmanager6from itertools import repeat
2 unmodified lines
9from .types import convert_type, IntRange, BOOL10from .utils import make_str, make_default_short_help, echo, get_os_args11from .exceptions import ClickException, UsageError, BadParameter, Abort, \12 MissingParameter12from .termui import prompt, confirm13from .termui import prompt, confirm, style14from .formatting import HelpFormatter, join_options15from .parser import OptionParser, split_opt16from .globals import push_context, pop_context1717from ._compat import PY2, isidentifier, iteritems18from ._compat import PY2, isidentifier, iteritems, string_types19from ._unicodefun import _check_for_unicode_literals, _verify_python3_env202122_missing = object()
1 unmodified line
2425SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'26SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'2728DEPRECATED_HELP_NOTICE = ' (DEPRECATED)'29DEPRECATED_INVOKE_NOTICE = 'DeprecationWarning: ' + \30 'The command %(name)s is deprecated.'313233def _maybe_show_deprecated_notice(cmd):34 if cmd.deprecated:35 echo(style(DEPRECATED_INVOKE_NOTICE % {'name': cmd.name}, fg='red'), err=True)363738def fast_exit(code):39 """Exit without garbage collection, this speeds up exit by about 10ms for40 things like bash completion.41 """
346 unmodified lines
388389 @property390 def meta(self):391 """This is a dictionary which is shared with all the contexts382 that are nested. It exists so that click utiltiies can store some392 that are nested. It exists so that click utilities can store some393 state here if they need to. It is however the responsibility of394 that code to manage this dictionary well.395396 The keys are supposed to be unique dotted strings. For instance
363 unmodified lines
760 shown on the command listing of the parent command.761 :param add_help_option: by default each command registers a ``--help``762 option. This can be disabled by this parameter.763 :param hidden: hide this command from help outputs.764765 :param deprecated: issues a message indicating that766 the command is deprecated.767 """768769 def __init__(self, name, context_settings=None, callback=None,770 params=None, help=None, epilog=None, short_help=None,771 options_metavar='[OPTIONS]', add_help_option=True,759 hidden=False):772 hidden=False, deprecated=False):773 BaseCommand.__init__(self, name, context_settings)774 #: the callback to execute when the command fires. This might be775 #: `None` in which case nothing happens.776 self.callback = callback
4 unmodified lines
781 self.help = help782 self.epilog = epilog783 self.options_metavar = options_metavar784 if short_help is None and help:785 if (context_settings is not None and786 'short_help_width' in context_settings):787 short_width = context_settings.get('short_help_width')788 short_help = make_default_short_help(help, short_width)789 else:772 short_help = make_default_short_help(help)790 short_help = make_default_short_help(help)791 self.short_help = short_help792 self.add_help_option = add_help_option793 self.hidden = hidden794 self.deprecated = deprecated795796 def get_usage(self, ctx):797 formatter = ctx.make_formatter()798 self.format_usage(ctx, formatter)
45 unmodified lines
844845 def make_parser(self, ctx):846 """Creates the underlying option parser for this command."""847 parser = OptionParser(ctx)829 parser.allow_interspersed_args = ctx.allow_interspersed_args830 parser.ignore_unknown_options = ctx.ignore_unknown_options848 for param in self.get_params(ctx):849 param.add_to_parser(parser, ctx)850 return parser851
24 unmodified lines
876 """Writes the help text to the formatter if it exists."""877 if self.help:878 formatter.write_paragraph()879 with formatter.indentation():880 help_text = self.help881 if self.deprecated:882 help_text += DEPRECATED_HELP_NOTICE863 formatter.write_text(self.help)883 formatter.write_text(help_text)884 elif self.deprecated:885 formatter.write_paragraph()886 with formatter.indentation():887 formatter.write_text(DEPRECATED_HELP_NOTICE)888889 def format_options(self, ctx, formatter):890 """Writes all the options into the formatter if they exist."""891 opts = []
32 unmodified lines
924 def invoke(self, ctx):925 """Given a context, this invokes the attached callback (if it exists)926 in the right way.927 """928 _maybe_show_deprecated_notice(self)929 if self.callback is not None:930 return ctx.invoke(self.callback, **ctx.params)931932
107 unmodified lines
1040 if cmd.hidden:1041 continue10421043 help = cmd.short_help or ''1044 if cmd.deprecated:1045 help += DEPRECATED_HELP_NOTICE1046 rows.append((subcommand, help))10471048 if rows:1049 with formatter.section('Commands'):
304 unmodified lines
13541355 def add_to_parser(self, parser, ctx):1356 pass135713581359 def consume_value(self, ctx, opts):1360 value = opts.get(self.name)1361 if value is None:1334 value = ctx.lookup_default(self.name)1335 if value is None:1362 value = self.value_from_envvar(ctx)1363 if value is None:1364 value = ctx.lookup_default(self.name)1365 return value13661367 def type_cast_value(self, ctx, value):1368 """Given a value this runs it properly through the type system.
88 unmodified lines
14571458 def get_usage_pieces(self, ctx):1459 return []14601461 def get_error_hint(self, ctx):1462 """Get a stringified version of the param for use in error messages to1463 indicate which param caused the error.1464 """1465 hint_list = self.opts or [self.human_readable_name]1466 return ' / '.join('"%s"' % x for x in hint_list)146714681469class Option(Parameter):1470 """Options are usually optional values on the command line and1471 have some extra features that arguments don't have.14721473 All other parameters are passed onwards to the parameter constructor.14741475 :param show_default: controls if the default value should be shown on the1441 help page. Normally, defaults are not shown.1476 help page. Normally, defaults are not shown. If this1477 value is a string, it shows the string instead of the1478 value. This is particularly useful for dynamic options.1479 :param show_envvar: controls if an environment variable should be shown on1480 the help page. Normally, environment variables1481 are not shown.1482 :param prompt: if set to `True` or a non empty string then the user will be1483 prompted for input. If set to `True` the prompt will be the1484 option name capitalized.1485 :param confirmation_prompt: if set then the value will need to be confirmed
23 unmodified lines
1509 def __init__(self, param_decls=None, show_default=False,1510 prompt=False, confirmation_prompt=False,1511 hide_input=False, is_flag=None, flag_value=None,1512 multiple=False, count=False, allow_from_autoenv=True,1473 type=None, help=None, hidden=False, show_choices=True, **attrs):1513 type=None, help=None, hidden=False, show_choices=True,1514 show_envvar=False, **attrs):1515 default_is_missing = attrs.get('default', _missing) is _missing1516 Parameter.__init__(self, param_decls, type=type, **attrs)15171518 if prompt is True:
38 unmodified lines
1557 self.allow_from_autoenv = allow_from_autoenv1558 self.help = help1559 self.show_default = show_default1560 self.show_choices = show_choices1561 self.show_envvar = show_envvar15621563 # Sanity check for stuff we don't support1564 if __debug__:1565 if self.nargs < 0:
105 unmodified lines
1671 rv.append(_write_opts(self.secondary_opts))16721673 help = self.help or ''1674 extra = []1675 if self.show_envvar:1676 envvar = self.envvar1677 if envvar is None:1678 if self.allow_from_autoenv and \1679 ctx.auto_envvar_prefix is not None:1680 envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1681 if envvar is not None:1682 extra.append('env var: %s' % (1683 ', '.join('%s' % d for d in envvar)1684 if isinstance(envvar, (list, tuple))1685 else envvar, ))1686 if self.default is not None and self.show_default:1634 extra.append('default: %s' % (1635 ', '.join('%s' % d for d in self.default)1636 if isinstance(self.default, (list, tuple))1637 else self.default, ))1687 if isinstance(self.show_default, string_types):1688 default_string = '({})'.format(self.show_default)1689 elif isinstance(self.default, (list, tuple)):1690 default_string = ', '.join('%s' % d for d in self.default)1691 elif inspect.isfunction(self.default):1692 default_string = "(dynamic)"1693 else:1694 default_string = self.default1695 extra.append('default: {}'.format(default_string))16961697 if self.required:1698 extra.append('required')1699 if extra:1700 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))
86 unmodified lines
17871788 def make_metavar(self):1789 if self.metavar is not None:1790 return self.metavar1791 var = self.type.get_metavar(self)1792 if not var:1732 var = self.name.upper()1793 var = self.name.upper()1794 if not self.required:1795 var = '[%s]' % var1796 if self.nargs != 1:1797 var += '...'
16 unmodified lines
18141815 def get_usage_pieces(self, ctx):1816 return [self.make_metavar()]18171818 def get_error_hint(self, ctx):1819 return '"%s"' % self.make_metavar()18201821 def add_to_parser(self, parser, ctx):1822 parser.add_argument(dest=self.name, nargs=self.nargs,1823 obj=self)1824
3 unmodified lines
modified:click/decorators.py+7 added-4 removed
162 unmodified lines
163 :param cls: the option class to instantiate. This defaults to164 :class:`Option`.165 """166 def decorator(f):167 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=168 option_attrs = attrs.copy()169167 if 'help' in attrs:168 attrs['help'] = inspect.cleandoc(attrs['help'])169 OptionClass = attrs.pop('cls', Option)170 _param_memo(f, OptionClass(param_decls, **attrs))170 if 'help' in option_attrs:171 option_attrs['help'] = inspect.cleandoc(option_attrs['help'])172 OptionClass = option_attrs.pop('cls', Option)173 _param_memo(f, OptionClass(param_decls, **option_attrs))174 return f175 return decorator176177
134 unmodified lines
modified:click/exceptions.py+11 added-6 removed
1from ._compat import PY2, filename_to_ui, get_text_stderr2from .utils import echo345def _join_param_hints(param_hint):6 if isinstance(param_hint, (tuple, list)):7 return ' / '.join('"%s"' % x for x in param_hint)8 return param_hint91011class ClickException(Exception):12 """An exception that Click can handle and show to the user."""1314 #: The exit code for this exception
82 unmodified lines
97 def format_message(self):98 if self.param_hint is not None:99 param_hint = self.param_hint100 elif self.param is not None:95 param_hint = self.param.opts or [self.param.human_readable_name]101 param_hint = self.param.get_error_hint(self.ctx)102 else:103 return 'Invalid value: %s' % self.message98 if isinstance(param_hint, (tuple, list)):99 param_hint = ' / '.join('"%s"' % x for x in param_hint)104 param_hint = _join_param_hints(param_hint)105106 return 'Invalid value for %s: %s' % (param_hint, self.message)107108109class MissingParameter(BadParameter):
16 unmodified lines
126 def format_message(self):127 if self.param_hint is not None:128 param_hint = self.param_hint129 elif self.param is not None:124 param_hint = self.param.opts or [self.param.human_readable_name]130 param_hint = self.param.get_error_hint(self.ctx)131 else:132 param_hint = None127 if isinstance(param_hint, (tuple, list)):128 param_hint = ' / '.join('"%s"' % x for x in param_hint)133 param_hint = _join_param_hints(param_hint)134135 param_type = self.param_type136 if param_type is None and self.param is not None:137 param_type = self.param.param_type_name
88 unmodified lines
modified:click/termui.py+64 added-12 removed
1import os2import sys3import struct4import inspect5import itertools67from ._compat import raw_input, text_type, string_types, \8 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN9from .utils import echo
5 unmodified lines
15# The prompt functions to use. The doc tools currently override these16# functions to customize how they work.17visible_prompt_func = raw_input1817_ansi_colors = ('black', 'red', 'green', 'yellow', 'blue', 'magenta',18 'cyan', 'white', 'reset')19_ansi_colors = {20 'black': 30,21 'red': 31,22 'green': 32,23 'yellow': 33,24 'blue': 34,25 'magenta': 35,26 'cyan': 36,27 'white': 37,28 'reset': 39,29 'bright_black': 90,30 'bright_red': 91,31 'bright_green': 92,32 'bright_yellow': 93,33 'bright_blue': 94,34 'bright_magenta': 95,35 'bright_cyan': 96,36 'bright_white': 97,37}38_ansi_reset_all = '\033[0m'394041def hidden_prompt_func(prompt):
150 unmodified lines
192 if shutil_get_terminal_size:193 sz = shutil_get_terminal_size()194 return sz.columns, sz.lines195196 # We provide a sensible default for get_winterm_size() when being invoked197 # inside a subprocess. Without this, it would not provide a useful input.198 if get_winterm_size is not None:178 return get_winterm_size()199 size = get_winterm_size()200 if size == (0, 0):201 return (79, 24)202 else:203 return size204205 def ioctl_gwinsz(fd):206 try:207 import fcntl
19 unmodified lines
227 os.environ.get('COLUMNS', DEFAULT_COLUMNS))228 return int(cr[1]), int(cr[0])229230206def echo_via_pager(text, color=None):231def echo_via_pager(text_or_generator, color=None):232 """This function takes a text and shows it via an environment specific233 pager on stdout.234235 .. versionchanged:: 3.0236 Added the `color` flag.237213 :param text: the text to page.238 :param text_or_generator: the text to page, or alternatively, a239 generator emitting the text to page.240 :param color: controls if the pager supports ANSI colors or not. The241 default is autodetection.242 """243 color = resolve_color_default(color)218 if not isinstance(text, string_types):219 text = text_type(text)244245 if inspect.isgeneratorfunction(text_or_generator):246 i = text_or_generator()247 elif isinstance(text_or_generator, string_types):248 i = [text_or_generator]249 else:250 i = iter(text_or_generator)251252 # convert every element of i to a text type if necessary253 text_generator = (el if isinstance(el, string_types) else text_type(el)254 for el in i)255256 from ._termui_impl import pager221 return pager(text + '\n', color)257 return pager(itertools.chain(text_generator, "\n"), color)258259260def progressbar(iterable=None, length=None, label=None, show_eta=True,261 show_percent=None, show_pos=False,
128 unmodified lines
390 * ``blue``391 * ``magenta``392 * ``cyan``393 * ``white`` (might be light gray)394 * ``bright_black``395 * ``bright_red``396 * ``bright_green``397 * ``bright_yellow``398 * ``bright_blue``399 * ``bright_magenta``400 * ``bright_cyan``401 * ``bright_white``402 * ``reset`` (reset the color code only)403404 .. versionadded:: 2.0405406 .. versionadded:: 7.0407 Added support for bright colors.408409 :param text: the string to style with ansi codes.410 :param fg: if provided this will become the foreground color.411 :param bg: if provided this will become the background color.412 :param bold: if provided this will enable or disable bold mode.
10 unmodified lines
423 """424 bits = []425 if fg:426 try:380 bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30))381 except ValueError:427 bits.append('\033[%dm' % (_ansi_colors[fg]))428 except KeyError:429 raise TypeError('Unknown color %r' % fg)430 if bg:431 try:385 bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40))386 except ValueError:432 bits.append('\033[%dm' % (_ansi_colors[bg] + 10))433 except KeyError:434 raise TypeError('Unknown color %r' % bg)435 if bold is not None:436 bits.append('\033[%dm' % (1 if bold else 22))437 if dim is not None:
128 unmodified lines
566 from ._termui_impl import getchar as f567 return f(echo)568569570def raw_terminal():571 from ._termui_impl import raw_terminal as f572 return f()573574575def pause(info='Press any key to continue ...', err=False):576 """This command stops execution and waits for the user to press any577 key to continue. This is similar to the Windows batch "pause"578 command. If the program is not run through a terminal, this command
23 unmodified lines
modified:click/testing.py+58 added-17 removed
71 unmodified lines
7273class Result(object):74 """Holds the captured result of an invoked CLI script."""7576 def __init__(self, runner, output_bytes, exit_code, exception,77 exc_info=None):76 def __init__(self, runner, stdout_bytes, stderr_bytes, exit_code,77 exception, exc_info=None):78 #: The runner that created the result79 self.runner = runner80 #: The output as bytes.81 self.output_bytes = output_bytes80 #: The standard output as bytes.81 self.stdout_bytes = stdout_bytes82 #: The standard error as bytes, or False(y) if not available83 self.stderr_bytes = stderr_bytes84 #: The exit code as integer.85 self.exit_code = exit_code86 #: The exception that happend if one did.87 self.exception = exception
1 unmodified line
89 self.exc_info = exc_info9091 @property92 def output(self):91 """The output as unicode string."""92 return self.output_bytes.decode(self.runner.charset, 'replace') \93 """The (standard) output as unicode string."""94 return self.stdout9596 @property97 def stdout(self):98 """The standard output as unicode string."""99 return self.stdout_bytes.decode(self.runner.charset, 'replace') \100 .replace('\r\n', '\n')101102 @property103 def stderr(self):104 """The standard error as unicode string."""105 if not self.stderr_bytes:106 raise ValueError("stderr not separately captured")107 return self.stderr_bytes.decode(self.runner.charset, 'replace') \108 .replace('\r\n', '\n')109110111 def __repr__(self):96 return '<Result %s>' % (112 return '<%s %s>' % (113 type(self).__name__,114 self.exception and repr(self.exception) or 'okay',115 )116117
10 unmodified lines
128 :param echo_stdin: if this is set to `True`, then reading from stdin writes129 to stdout. This is useful for showing examples in130 some circumstances. Note that regular prompts131 will automatically echo the input.132 :param mix_stderr: if this is set to `False`, then stdout and stderr are133 preserved as independent streams. This is useful for134 Unix-philosophy apps that have predictable stdout and135 noisy stderr, such that each may be measured136 independently137 """138117 def __init__(self, charset=None, env=None, echo_stdin=False):139 def __init__(self, charset=None, env=None, echo_stdin=False,140 mix_stderr=True):141 if charset is None:142 charset = 'utf-8'143 self.charset = charset144 self.env = env or {}145 self.echo_stdin = echo_stdin146 self.mix_stderr = mix_stderr147148 def get_default_prog_name(self, cli):149 """Given a command object it will return the default program name150 for it. The default is the `name` attribute or ``"root"`` if not
36 unmodified lines
187188 env = self.make_env(env)189190 if PY2:167 sys.stdout = sys.stderr = bytes_output = StringIO()191 bytes_output = StringIO()192 if self.echo_stdin:193 input = EchoingStdin(input, bytes_output)194 sys.stdout = bytes_output195 if not self.mix_stderr:196 bytes_error = StringIO()197 sys.stderr = bytes_error198 else:199 bytes_output = io.BytesIO()200 if self.echo_stdin:201 input = EchoingStdin(input, bytes_output)202 input = io.TextIOWrapper(input, encoding=self.charset)175 sys.stdout = sys.stderr = io.TextIOWrapper(203 sys.stdout = io.TextIOWrapper(204 bytes_output, encoding=self.charset)205 if not self.mix_stderr:206 bytes_error = io.BytesIO()207 sys.stderr = io.TextIOWrapper(208 bytes_error, encoding=self.charset)209210 if self.mix_stderr:211 sys.stderr = sys.stdout212213 sys.stdin = input214215 def visible_input(prompt=None):216 sys.stdout.write(prompt or '')
40 unmodified lines
257 except Exception:258 pass259 else:260 os.environ[key] = value226 yield bytes_output261 yield (bytes_output, not self.mix_stderr and bytes_error)262 finally:263 for key, value in iteritems(old_env):264 if value is None:265 try:
11 unmodified lines
277 clickpkg.utils.should_strip_ansi = old_should_strip_ansi278 clickpkg.formatting.FORCED_WIDTH = old_forced_width279280 def invoke(self, cli, args=None, input=None, env=None,246 catch_exceptions=True, color=False, **extra):281 catch_exceptions=True, color=False, mix_stderr=False, **extra):282 """Invokes a command in an isolated environment. The arguments are283 forwarded directly to the command line script, the `extra` keyword284 arguments are passed to the :meth:`~clickpkg.Command.main` function of285 the command.
23 unmodified lines
309 :param color: whether the output should contain color codes. The310 application can still override this explicitly.311 """312 exc_info = None278 with self.isolation(input=input, env=env, color=color) as out:313 with self.isolation(input=input, env=env, color=color) as outstreams:314 exception = None315 exit_code = 0316317 if isinstance(args, string_types):318 args = shlex.split(args)319320 try:286 cli.main(args=args or (),287 prog_name=self.get_default_prog_name(cli), **extra)321 prog_name = extra.pop("prog_name")322 except KeyError:323 prog_name = self.get_default_prog_name(cli)324325 try:326 cli.main(args=args or (), prog_name=prog_name, **extra)327 except SystemExit as e:328 exc_info = sys.exc_info()329 exit_code = e.code330 if exit_code is None:
14 unmodified lines
345 exit_code = 1346 exc_info = sys.exc_info()347 finally:348 sys.stdout.flush()310 output = out.getvalue()349 stdout = outstreams[0].getvalue()350 stderr = outstreams[1] and outstreams[1].getvalue()351352 return Result(runner=self,313 output_bytes=output,353 stdout_bytes=stdout,354 stderr_bytes=stderr,355 exit_code=exit_code,356 exception=exception,357 exc_info=exc_info)358
16 unmodified lines
modified:click/types.py+23 added-7 removed
131 unmodified lines
132 You should only pass *choices* as list or tuple. Other iterables (like133 generators) may lead to surprising results.134135 See :ref:`choice-opts` for an example.136137 :param case_sensitive: Set to false to make choices case insensitive.138 Defaults to true.139 """140 name = 'choice'141139 def __init__(self, choices):142 def __init__(self, choices, case_sensitive=True):143 self.choices = choices144 self.case_sensitive = case_sensitive145146 def get_metavar(self, param):147 return '[%s]' % '|'.join(self.choices)148
4 unmodified lines
153 # Exact match154 if value in self.choices:155 return value156153 # Match through normalization157 # Match through normalization and case sensitivity158 # first do token_normalize_func, then lowercase159 # preserve original `value` to produce an accurate message in160 # `self.fail`161 normed_value = value162 normed_choices = self.choices163164 if ctx is not None and \165 ctx.token_normalize_func is not None:156 value = ctx.token_normalize_func(value)157 for choice in self.choices:158 if ctx.token_normalize_func(choice) == value:159 return choice166 normed_value = ctx.token_normalize_func(value)167 normed_choices = [ctx.token_normalize_func(choice) for choice in168 self.choices]169170 if not self.case_sensitive:171 normed_value = normed_value.lower()172 normed_choices = [choice.lower() for choice in normed_choices]173174 if normed_value in normed_choices:175 return normed_value176177 self.fail('invalid choice: %s. (choose from %s)' %178 (value, ', '.join(self.choices)), param, ctx)179180 def __repr__(self):
111 unmodified lines
292 def convert(self, value, param, ctx):293 if isinstance(value, bool):294 return bool(value)295 value = value.lower()280 if value in ('true', 't,' '1', 'yes', 'y'):296 if value in ('true', 't', '1', 'yes', 'y'):297 return True298 elif value in ('false', 'f', '0', 'no', 'n'):299 return False300 self.fail('%s is not a valid boolean' % value, param, ctx)
310 unmodified lines
modified:click/utils.py+1 added-1 removed
182 unmodified lines
183 - add transparent handling of ANSI color codes on Windows.184 - hide ANSI codes automatically if the destination file is not a185 terminal.186187 .. _colorama: http://pypi.python.org/pypi/colorama187 .. _colorama: https://pypi.org/project/colorama/188189 .. versionchanged:: 6.0190 As of Click 6.0 the echo function will properly support unicode191 output on the windows console. Not that click does not modify
225 unmodified lines
modified:docs/_templates/sidebarintro.html+1 added-1 removed
5 unmodified lines
6</p>7<h3>Useful Links</h3>8<ul>9 <li><a href="http://click.pocoo.org/">The Click Website</a></li>10 <li><a href="http://pypi.python.org/pypi/click">click @ PyPI</a></li>10 <li><a href="https://pypi.org/project/click/">click @ PyPI</a></li>11 <li><a href="http://github.com/pallets/click">click @ github</a></li>12 <li><a href="http://github.com/pallets/click/issues">Issue Tracker</a></li>13</ul>
modified:docs/advanced.rst+2 added-2 removed
293 unmodified lines
294 ))295 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')296 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)297 def cli(verbose, timeit_args):298 """A wrapper around Python's timeit."""299 cmdline = ['python', '-mtimeit'] + list(timeit_args)298 """A fake wrapper around Python's timeit."""299 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)300 if verbose:301 click.echo('Invoking: %s' % ' '.join(cmdline))302 call(cmdline)303
76 unmodified lines
modified:docs/arguments.rst+18 added
241 unmodified lines
242243.. click:run::244245 invoke(touch, ['--', '-foo.txt', 'bar.txt'])246247If you don't like the ``--`` marker, you can set ignore_unknown_options to248True to avoid checking unknown options:249250.. click:example::251252 @click.command(context_settings={"ignore_unknown_options": True})253 @click.argument('files', nargs=-1, type=click.Path())254 def touch(files):255 for filename in files:256 click.echo(filename)257258And from the command line:259260.. click:run::261262 invoke(touch, ['-foo.txt', 'bar.txt'])263
modified:docs/bashcomplete.rst+1 added-1 removed
93 unmodified lines
9495 . /path/to/foo-bar-complete.sh9697Zsh Compatibility98----------------98-----------------99100To enable Bash completion in Zsh, add the following lines to your .zshrc:101102 autoload bashcompinit
4 unmodified lines
modified:docs/clickdoctools.py+9 added-2 removed
13 unmodified lines
14from docutils import nodes15from docutils.statemachine import ViewList1617from sphinx.domains import Domain18from sphinx.util.compat import Directive18from docutils.parsers.rst import Directive1920PY2 = sys.version_info[0] == 22122if PY2:23 text_type = unicode24else:25 text_type = str26 2728class EchoingStdin(object):2930 def __init__(self, input, output):31 self._input = input
44 unmodified lines
767778@contextlib.contextmanager79def isolation(input=None, env=None):73 if isinstance(input, unicode):80 if isinstance(input, text_type):81 input = input.encode('utf-8')82 input = StringIO(input or '')83 output = StringIO()84 sys.stdin = EchoingStdin(input, output)
198 unmodified lines
modified:docs/complex.rst+5 added-5 removed
151 unmodified lines
152One obvious way to remedy this is to store a reference to the repo in the153plugin, but then a command needs to be aware that it's attached below such a154plugin.155156There is a much better system that can built by taking advantage of the linked157nature of contexts. We know that the plugin context is linked to the context158that created our repo. Because of that, we can start a search for the last159level where the object stored by the context was a repo.156There is a much better system that can be built by taking advantage of the157linked nature of contexts. We know that the plugin context is linked to the158context that created our repo. Because of that, we can start a search for159the last level where the object stored by the context was a repo.160161Built-in support for this is provided by the :func:`make_pass_decorator`162factory, which will create decorators for us that find objects (it163internally calls into :meth:`Context.find_object`). In our case, we
45 unmodified lines
209210 @click.command()211 @pass_repo212 def cp(repo):213 click.echo(repo)213 click.echo(isinstance(repo, Repo))214215As you can see:216217.. click:run::
2 unmodified lines
modified:docs/options.rst+28 added
43 unmodified lines
4445In this case the option is of type :data:`INT` because the default value46is an integer.4748To show the default values when showing command help, use ``show_default=True``4950.. click:example::5152 @click.command()53 @click.option('--n', default=1, show_default=True)54 def dots(n):55 click.echo('.' * n)5657.. click:run::5859 invoke(dots, args=['--help'])6061Multi Value Options62-------------------6364Sometimes, you have options that take more than one argument. For options,
336 unmodified lines
401 default=lambda: os.environ.get('USER', ''))402 def hello(username):403 print("Hello,", username)404405To describe what the default value will be, set it in ``show_default``.406407.. click:example::408409 @click.command()410 @click.option('--username', prompt=True,411 default=lambda: os.environ.get('USER', ''),412 show_default='current user')413 def hello(username):414 print("Hello,", username)415416.. click:run::417418 invoke(hello, args=['--help'])419420Callbacks and Eager Options421---------------------------422423Sometimes, you want a parameter to completely change the execution flow.
315 unmodified lines
modified:docs/python3.rst+1 added-1 removed
4 unmodified lines
56Click supports Python 3, but like all other command line utility libraries,7it suffers from the Unicode text model in Python 3. All examples in the8documentation were written so that they could run on both Python 2.x and9Python 3.3 or higher.9Python 3.4 or higher.1011At the moment, it is strongly recommended to use Python 2 for Click12utilities unless Python 3 is a hard requirement.13
170 unmodified lines
modified:docs/utils.rst+14 added-3 removed
39 unmodified lines
40.. versionadded:: 6.04142Click now emulates output streams on Windows to support unicode to the43Windows console through separate APIs. For more information see44`wincmd`_.44:doc:`wincmd`.4546.. versionadded:: 3.04748Starting with Click 3.0 you can also easily print to standard error by
45 unmodified lines
94 click.secho('Some more text', bg='blue', fg='white')95 click.secho('ATTENTION', blink=True, bold=True)969798.. _colorama: https://pypi.python.org/pypi/colorama98.. _colorama: https://pypi.org/project/colorama/99100Pager Support101-------------102
10 unmodified lines
113 def less():114 click.echo_via_pager('\n'.join('Line %d' % idx115 for idx in range(200)))116117If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:118119.. click:example::120 def _generate_output():121 for idx in range(50000):122 yield "Line %d\n" % idx123124 @click.command()125 def less():126 click.echo_via_pager(_generate_output())127128129Screen Clearing130---------------131132.. versionadded:: 2.0
160 unmodified lines
293.. versionadded:: 6.0294295Click now emulates output streams on Windows to support unicode to the296Windows console through separate APIs. For more information see286`wincmd`_.297:doc:`wincmd`.298299300Intelligent File Opening301------------------------
108 unmodified lines
modified:docs/why.rst+1 added-1 removed
6 unmodified lines
7This question is easy to answer: because there is not a single command8line utility for Python out there which ticks the following boxes:910* is lazily composable without restrictions11* fully follows the Unix command line conventions11* supports implementation of Unix/POSIX command line conventions12* supports loading values from environment variables out of the box13* supports for prompting of custom values14* is fully nestable and composable15* works the same in Python 2 and 3
137 unmodified lines
modified:examples/colors/colors.py+3 added-1 removed
1import click234all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \5 'cyan', 'white'5 'cyan', 'white', 'bright_black', 'bright_red', \6 'bright_green', 'bright_yellow', 'bright_blue', \7 'bright_magenta', 'bright_cyan', 'bright_white'8910@click.command()11def cli():
17 unmodified lines
modified:tests/test_arguments.py+2 added-2 removed
186 unmodified lines
187 click.echo('arg:' + '|'.join(arg))188189 result = runner.invoke(cmd2, [])190 assert result.exit_code == 2191 assert 'Missing argument "arg"' in result.output191 assert 'Missing argument "ARG..."' in result.output192193194def test_missing_arg(runner):195 @click.command()
2 unmodified lines
198 click.echo('arg:' + arg)199200 result = runner.invoke(cmd, [])201 assert result.exit_code == 2202 assert 'Missing argument "arg".' in result.output202 assert 'Missing argument "ARG".' in result.output203204205def test_implicit_non_required(runner):206 @click.command()
83 unmodified lines
modified:tests/test_basic.py+1 added-1 removed
185 unmodified lines
186 @click.option('--flag', default=default, type=bool)187 def cli(flag):188 click.echo(flag)189190 for value in 'true', 't,' '1', 'yes', 'y':190 for value in 'true', 't', '1', 'yes', 'y':191 result = runner.invoke(cli, ['--flag', value])192 assert not result.exception193 assert result.output == 'True\n'194
304 unmodified lines
modified:tests/test_commands.py+30 added-10 removed
1# -*- coding: utf-8 -*-2import re34import click5import pytest678def test_other_command_invoke(runner):9 @click.command()
48 unmodified lines
58 def long():59 """This is a long text that is too long to show as short help60 and will be truncated instead."""6162 @cli.command(context_settings={'short_help_width': 20})63 def width():64 """This is a long text that is too long to show as short help65 and will be truncated instead."""6667 result = runner.invoke(cli, ['--help'])68 assert re.search(69 r'Commands:\n\s+'70 r'long\s+This is a long text that is too long to show\.\.\.\n\s+'71 r'short\s+This is a short text\.\n\s+'65 r'special-chars\s+Login and store the token in ~/.netrc\.\s*',72 r'special-chars\s+Login and store the token in ~/.netrc\.\s+'73 r'width\s+This is a long text\.\.\.\n\s*',74 result.output) is not None757677def test_default_maps(runner):
184 unmodified lines
262 'Args: -foo|-x|--muhaha|x|y|-x',263 ]264265258def test_subcommand_naming(runner):259 @click.group()260 def cli():266def test_deprecated_in_help_messages(runner):267 @click.command(deprecated=True)268 def cmd_with_help():269 """CLI HELP"""270 pass271263 @cli.command()264 def foo_bar():265 click.echo('foo-bar')272 result = runner.invoke(cmd_with_help, ['--help'])273 assert '(DEPRECATED)' in result.output274267 result = runner.invoke(cli, ['foo-bar'])268 assert not result.exception269 assert result.output.splitlines() == ['foo-bar']275 @click.command(deprecated=True)276 def cmd_without_help():277 pass278279 result = runner.invoke(cmd_without_help, ['--help'])280 assert '(DEPRECATED)' in result.output281282283def test_deprecated_in_invocation(runner):284 @click.command(deprecated=True)285 def deprecated_cmd():286 debug()287288 result = runner.invoke(deprecated_cmd)289 assert 'DeprecationWarning:' in result.output
modified:tests/test_formatting.py+60 added-4 removed
157 unmodified lines
158 assert result.output.splitlines() == [159 'Usage: cmd [OPTIONS] ARG',160 'Try "cmd --help" for help.',161 '',162 'Error: Missing argument "arg".'162 'Error: Missing argument "ARG".'163 ]164165166def test_formatting_usage_error_metavar_missing_arg(runner):167 """168 :author: @r-m-n169 Including attribution to #612170 """171 @click.command()172 @click.argument('arg', metavar='metavar')173 def cmd(arg):174 pass175176 result = runner.invoke(cmd, [])177 assert result.exit_code == 2178 assert result.output.splitlines() == [179 'Usage: cmd [OPTIONS] metavar',180 'Try "cmd --help" for help.',181 '',182 'Error: Missing argument "metavar".'183 ]184185186def test_formatting_usage_error_metavar_bad_arg(runner):187 @click.command()188 @click.argument('arg', type=click.INT, metavar='metavar')189 def cmd(arg):190 pass191192 result = runner.invoke(cmd, ['3.14'])193 assert result.exit_code == 2194 assert result.output.splitlines() == [195 'Usage: cmd [OPTIONS] metavar',196 'Try "cmd --help" for help.',197 '',198 'Error: Invalid value for "metavar": 3.14 is not a valid integer'199 ]200201202def test_formatting_usage_error_nested(runner):203 @click.group()204 def cmd():205 pass
8 unmodified lines
214 assert result.output.splitlines() == [215 'Usage: cmd foo [OPTIONS] BAR',216 'Try "cmd foo --help" for help.',217 '',182 'Error: Missing argument "bar".'218 'Error: Missing argument "BAR".'219 ]220221222def test_formatting_usage_error_no_help(runner):
6 unmodified lines
229 assert result.exit_code == 2230 assert result.output.splitlines() == [231 'Usage: cmd [OPTIONS] ARG',232 '',197 'Error: Missing argument "arg".'233 'Error: Missing argument "ARG".'234 ]235236237def test_formatting_usage_custom_help(runner):
7 unmodified lines
245 assert result.output.splitlines() == [246 'Usage: cmd [OPTIONS] ARG',247 'Try "cmd --man" for help.',248 '',213 'Error: Missing argument "arg".'249 'Error: Missing argument "ARG".'250 ]251252def test_formatting_custom_type_metavar(runner):253 class MyType(click.ParamType):254 def get_metavar(self, param):255 return "MY_TYPE"256257 @click.command("foo")258 @click.help_option()259 @click.argument("param", type=MyType())260 def cmd(param):261 pass262263 result = runner.invoke(cmd, '--help')264 assert not result.exception265 assert result.output.splitlines() == [266 'Usage: foo [OPTIONS] MY_TYPE',267 '',268 'Options:',269 ' --help Show this message and exit.'270 ]
modified:tests/test_imports.py+1 added-1 removed
30 unmodified lines
3132ALLOWED_IMPORTS = set([33 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',35 'threading', 'colorama', 'errno'35 'threading', 'colorama', 'errno', 'fcntl'36])3738if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',
16 unmodified lines
modified:tests/test_options.py+111 added-1 removed
172 unmodified lines
173 result = runner.invoke(cmd, '--arg1 a b --arg1 test 1 --arg2 2 '174 'two --arg2 4 four'.split())175 assert not result.exception176177def test_dynamic_default_help_unset(runner):178 @click.command()179 @click.option('--username', prompt=True,180 default=lambda: os.environ.get('USER', ''),181 show_default=True)182 def cmd(username):183 print("Hello,", username)184185 result = runner.invoke(cmd, ['--help'])186 assert result.exit_code == 0187 assert '--username' in result.output188 assert 'lambda' not in result.output189 assert '(dynamic)' in result.output190191def test_dynamic_default_help_text(runner):192 @click.command()193 @click.option('--username', prompt=True,194 default=lambda: os.environ.get('USER', ''),195 show_default='current user')196 def cmd(username):197 print("Hello,", username)198199 result = runner.invoke(cmd, ['--help'])200 assert result.exit_code == 0201 assert '--username' in result.output202 assert 'lambda' not in result.output203 assert '(current user)' in result.output204205def test_nargs_envvar(runner):206 @click.command()207 @click.option('--arg', nargs=2)208 def cmd(arg):
15 unmodified lines
224 assert not result.exception225 assert result.output == 'x|1\ny|2\n'226227228def test_show_envvar(runner):229 @click.command()230 @click.option('--arg1', envvar='ARG1',231 show_envvar=True)232 def cmd(arg):233 pass234235 result = runner.invoke(cmd, ['--help'])236 assert not result.exception237 assert 'ARG1' in result.output238239240def test_show_envvar_auto_prefix(runner):241 @click.command()242 @click.option('--arg1', show_envvar=True)243 def cmd(arg):244 pass245246 result = runner.invoke(cmd, ['--help'],247 auto_envvar_prefix='TEST')248 assert not result.exception249 assert 'TEST_ARG1' in result.output250251252def test_custom_validation(runner):253 def validate_pos_int(ctx, param, value):254 if value < 0:255 raise click.BadParameter('Value needs to be positive')
53 unmodified lines
309 assert 'Error: Missing option "--foo". Choose from foo, bar.' \310 in result.output311312313def test_case_insensitive_choice(runner):314 @click.command()315 @click.option('--foo', type=click.Choice(316 ['Orange', 'Apple'], case_sensitive=False))317 def cmd(foo):318 click.echo(foo)319320 result = runner.invoke(cmd, ['--foo', 'apple'])321 assert result.exit_code == 0322323 result = runner.invoke(cmd, ['--foo', 'oRANGe'])324 assert result.exit_code == 0325326 result = runner.invoke(cmd, ['--foo', 'Apple'])327 assert result.exit_code == 0328329 @click.command()330 @click.option('--foo', type=click.Choice(['Orange', 'Apple']))331 def cmd2(foo):332 click.echo(foo)333334 result = runner.invoke(cmd2, ['--foo', 'apple'])335 assert result.exit_code == 2336337 result = runner.invoke(cmd2, ['--foo', 'oRANGe'])338 assert result.exit_code == 2339340 result = runner.invoke(cmd2, ['--foo', 'Apple'])341 assert result.exit_code == 0342343344def test_multiline_help(runner):345 @click.command()346 @click.option('--foo', help="""347 hello
11 unmodified lines
359 assert ' --foo TEXT hello' in out360 assert ' i am' in out361 assert ' multiline' in out362281363def test_argument_custom_class(runner):364 class CustomArgument(click.Argument):365 def get_default(self, ctx):366 '''a dumb override of a default value for testing'''
24 unmodified lines
391 assert 'I am a help text' in result.output392 assert 'you wont see me' not in result.output393394395def test_option_custom_class_reusable(runner):396 """Ensure we can reuse a custom class option. See Issue #926"""397398 class CustomOption(click.Option):399 def get_help_record(self, ctx):400 '''a dumb override of a help text for testing'''401 return ('--help', 'I am a help text')402403 # Assign to a variable to re-use the decorator.404 testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')405406 @click.command()407 @testoption408 def cmd1(testoption):409 click.echo(testoption)410411 @click.command()412 @testoption413 def cmd2(testoption):414 click.echo(testoption)415416 # Both of the commands should have the --help option now.417 for cmd in (cmd1, cmd2):418419 result = runner.invoke(cmd, ['--help'])420 assert 'I am a help text' in result.output421 assert 'you wont see me' not in result.output422423424def test_aliases_for_flags(runner):425 @click.command()426 @click.option('--warnings/--no-warnings', ' /-W', default=True)427 def cli(warnings):
46 unmodified lines
modified:tests/test_termui.py+63 added-4 removed
1import click2import time345class FakeClock(object):6 def __init__(self):7 self.now = time.time()89 def advance_time(self, seconds=1):10 self.now += seconds1112 def time(self):13 return self.now141516def test_progressbar_strip_regression(runner, monkeypatch):17 fake_clock = FakeClock()18 label = ' padded line'1920 @click.command()21 def cli():22 with click.progressbar(tuple(range(10)), label=label) as progress:23 for thing in progress:11 pass24 fake_clock.advance_time()2526 monkeypatch.setattr(time, 'time', fake_clock.time)27 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)28 assert label in runner.invoke(cli, []).output2930
15 unmodified lines
46 raise StopIteration4748 next = __next__4950 fake_clock = FakeClock()5152 @click.command()53 def cli():54 with click.progressbar(Hinted(10), label='test') as progress:55 for thing in progress:40 pass56 fake_clock.advance_time()5758 monkeypatch.setattr(time, 'time', fake_clock.time)59 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)60 result = runner.invoke(cli, [])61 assert result.exception is None626364def test_progressbar_hidden(runner, monkeypatch):65 fake_clock = FakeClock()66 label = 'whatever'6768 @click.command()69 def cli():70 with click.progressbar(tuple(range(10)), label=label) as progress:71 for thing in progress:72 fake_clock.advance_time()7374 monkeypatch.setattr(time, 'time', fake_clock.time)75 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)76 assert runner.invoke(cli, []).output == ''777879def test_choices_list_in_prompt(runner, monkeypatch):80 @click.command()81 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),82 prompt=True)
13 unmodified lines
96 assert '(none, day, week, month)' not in result.output979899def test_secho(runner):68 with runner.isolation() as out:100 with runner.isolation() as outstreams:101 click.secho(None, nl=False)70 bytes = out.getvalue()102 bytes = outstreams[0].getvalue()103 assert bytes == b''104105106def test_progressbar_yields_all_items(runner):107 with click.progressbar(range(3)) as progress:108 assert len(list(progress)) == 3109110111def test_progressbar_update(runner, monkeypatch):112 fake_clock = FakeClock()113114 @click.command()115 def cli():116 with click.progressbar(range(4)) as progress:117 for _ in progress:118 fake_clock.advance_time()119 print("")120121 monkeypatch.setattr(time, 'time', fake_clock.time)122 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)123 output = runner.invoke(cli, []).output124125 lines = [line for line in output.split('\n') if '[' in line]126127 assert ' 25% 00:00:03' in lines[0]128 assert ' 50% 00:00:02' in lines[1]129 assert ' 75% 00:00:01' in lines[2]130 assert '100% ' in lines[3]
modified:tests/test_testing.py+35 added
202 unmodified lines
203204 assert os.environ == env_orig205206207def test_stderr():208 @click.command()209 def cli_stderr():210 click.echo("stdout")211 click.echo("stderr", err=True)212213 runner = CliRunner(mix_stderr=False)214215 result = runner.invoke(cli_stderr)216217 assert result.output == 'stdout\n'218 assert result.stdout == 'stdout\n'219 assert result.stderr == 'stderr\n'220221 runner_mix = CliRunner(mix_stderr=True)222 result_mix = runner_mix.invoke(cli_stderr)223224 assert result_mix.output == 'stdout\nstderr\n'225 assert result_mix.stdout == 'stdout\nstderr\n'226227 with pytest.raises(ValueError):228 result_mix.stderr229230231@pytest.mark.parametrize('args, expected_output', [232 (None, 'bar\n'),233 ([], 'bar\n'),234 ('', 'bar\n'),
10 unmodified lines
245 runner = CliRunner()246 result = runner.invoke(cli_args, args=args)247 assert result.exit_code == 0248 assert result.output == expected_output249250251def test_setting_prog_name_in_extra():252 @click.command()253 def cli():254 click.echo("ok")255256 runner = CliRunner()257 result = runner.invoke(cli, prog_name="foobar")258 assert not result.exception259 assert result.output == 'ok\n'
modified:tests/test_utils.py+37 added-14 removed
8 unmodified lines
9from click._compat import WIN, PY2101112def test_echo(runner):13 with runner.isolation() as out:13 with runner.isolation() as outstreams:14 click.echo(u'\N{SNOWMAN}')15 click.echo(b'\x44\x44')16 click.echo(42, nl=False)17 click.echo(b'a', nl=False)18 click.echo('\x1b[31mx\x1b[39m', nl=False)19 bytes = out.getvalue().replace(b'\r\n', b'\n')19 bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')20 assert bytes == b'\xe2\x98\x83\nDD\n42ax'2122 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 3
10 unmodified lines
34 @click.command()35 def cli():36 click.echo(b'\xf6')37 result = runner.invoke(cli, [])38 assert result.output_bytes == b'\xf6\n'38 assert result.stdout_bytes == b'\xf6\n'3940 # Ensure we do not strip for bytes.41 with runner.isolation() as out:41 with runner.isolation() as outstreams:42 click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)43 assert out.getvalue() == b'\x1b[31mx\x1b[39m'43 assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'444546def test_echo_custom_file():47 import io
97 unmodified lines
145 out, err = capsys.readouterr()146 assert out == 'Password: \nScrew you.\n'147148149def _test_gen_func():150 yield 'a'151 yield 'b'152 yield 'c'153 yield 'abc'154155156@pytest.mark.skipif(WIN, reason='Different behavior on windows.')157@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])158@pytest.mark.parametrize('test', [159 # We need lambda here, because pytest will160 # reuse the parameters, and then the generators161 # are already used and will not yield anymore162 ('just text\n', lambda: 'just text'),163 ('iterable\n', lambda: ["itera", "ble"]),164 ('abcabc\n', lambda: _test_gen_func),165 ('abcabc\n', lambda: _test_gen_func()),166 ('012345\n', lambda: (c for c in range(6))),167])151def test_echo_via_pager(monkeypatch, capfd, cat):168def test_echo_via_pager(monkeypatch, capfd, cat, test):169 monkeypatch.setitem(os.environ, 'PAGER', cat)170 monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)171172 expected_output = test[0]173 test_input = test[1]()174154 click.echo_via_pager('haha')175 click.echo_via_pager(test_input)176177 out, err = capfd.readouterr()156 assert out == 'haha\n'178 assert out == expected_output179180181@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')182def test_echo_color_flag(monkeypatch, capfd):
106 unmodified lines
289def test_iter_keepopenfile(tmpdir):290 expected = list(map(str, range(10)))291 p = tmpdir.mkdir('testdir').join('testfile')292 p.write(os.linesep.join(expected))271 f = p.open()272 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):273 assert e_line == a_line.strip()293 with p.open() as f:294 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):295 assert e_line == a_line.strip()296297298@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')299def test_iter_lazyfile(tmpdir):300 expected = list(map(str, range(10)))301 p = tmpdir.mkdir('testdir').join('testfile')302 p.write(os.linesep.join(expected))303 with p.open() as f:281 f = p.open()282 for e_line, a_line in zip(expected, click.utils.LazyFile(f.name)):283 assert e_line == a_line.strip()304 with click.utils.LazyFile(f.name) as lf:305 for e_line, a_line in zip(expected, lf):306 assert e_line == a_line.strip()
modified:.gitignore+1 added
6 unmodified lines
7dist8build9docs/_build10click.egg-info11venv/12.tox13.cache14.ropeproject15.idea
modified:.travis.yml-2 removed
1sudo: false2language: python3python:4 - "2.6"4 - "2.7"6 - "3.3"5 - "3.4"6 - "3.5"7 - "3.6"8 - "pypy"
35 unmodified lines
modified:CHANGES+4 added-2 removed
5 unmodified lines
6Version 7.07-----------89(upcoming release with new features, release date to be decided)1011- Added support for bash completions containing spaces. See #773.12- Added support for dynamic bash completion from a user-supplied callback.13 See #755.14- Added support for bash completion of type=click.Choice for Options and
8 unmodified lines
23- Usage errors now hint at the `--help` option.24- ``launch`` now works properly under Cygwin. See #650.25- `CliRunner.invoke` now may receive `args` as a string representing26 a Unix shell command. See #664.26- Fix bug that caused bashcompletion to give improper completions on 27- Fix bug that caused bashcompletion to give improper completions on28 chained commands. See #774.29- Add support for bright colors.28- 't' and 'f' are now converted to True and False. 30- 't' and 'f' are now converted to True and False.31- Fix bug that caused bashcompletion to give improper completions on32 chained commands when a required option/argument was being completed.33 See #790.34- Allow autocompletion function to determine whether or not to return
370 unmodified lines
deleted:README-20 removed
1$ click_23 Click is a Python package for creating beautiful command line interfaces4 in a composable way with as little code as necessary. It's the "Command5 Line Interface Creation Kit". It's highly configurable but comes with6 sensible defaults out of the box.78 It aims to make the process of writing command line tools quick and fun9 while also preventing any frustration caused by the inability to implement10 an intended CLI API.1112 Click in three points:1314 - arbitrary nesting of commands15 - automatic help page generation16 - supports lazy loading of subcommands at runtime1718 Read the docs at http://click.pocoo.org/1920 This library is stable and active. Feedback is always welcome!
added:README.rst+91 added
1\$ click\_2==========34What's Click?5-------------67Click is a Python package for creating beautiful command line interfaces8in a composable way with as little code as necessary. It's the "Command9Line Interface Creation Kit". It's highly configurable but comes with10sensible defaults out of the box.1112It aims to make the process of writing command line tools quick and fun13while also preventing any frustration caused by the inability to implement14an intended CLI API.1516Click in three points:17 - arbitrary nesting of commands18 - automatic help page generation19 - supports lazy loading of subcommands at runtime202122Installing23----------2425Install and update using `pip`_:2627.. code-block:: text2829 $ pip install click3031Click supports Python 3.4 and newer, Python 2.7, and PyPy3233A Simple Example34----------------3536What does it look like? Here is an example of a simple Click program:3738.. code-block:: python3940 import click41 42 @click.command()43 @click.option('--count', default=1, help='Number of greetings.')44 @click.option('--name', prompt='Your name',45 help='The person to greet.')46 def hello(count, name):47 """Simple program that greets NAME for a total of COUNT times."""48 for x in range(count):49 click.echo('Hello %s!' % name)50 51 if __name__ == '__main__':52 hello()5354And what it looks like when run:5556.. code-block:: text5758 $ python hello.py --count=359 Your name: John60 Hello John!61 Hello John!62 Hello John!6364Donate65------6667The Pallets organization develops and supports Flask and the libraries68it uses. In order to grow the community of contributors and users, and69allow the maintainers to devote more time to the projects, `please70donate today`_.7172.. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=20737475Links76-----7778* Website: https://www.palletsprojects.com/p/click/79* Documentation: http://click.pocoo.org/80* License: `BSD <https://github.com/pallets/click/blob/master/LICENSE>`_81* Releases: https://pypi.org/project/click/82* Code: https://github.com/pallets/click83* Issue tracker: https://github.com/pallets/click/issues84* Test status:8586 * Linux, Mac: https://travis-ci.org/pallets/click87 * Windows: https://ci.appveyor.com/project/pallets/click8889* Test coverage: https://codecov.io/gh/pallets/click9091.. _pip: https://pip.pypa.io/en/stable/quickstart/
modified:setup.py+33 added-6 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import io4import re2import ast5from setuptools import setup678_version_re = re.compile(r'__version__\s+=\s+(.*)')9109with open('click/__init__.py', 'rb') as f:10 version = str(ast.literal_eval(_version_re.search(11 f.read().decode('utf-8')).group(1)))11with io.open('README.rst', 'rt', encoding='utf8') as f:12 readme = f.read()1314with io.open('click/__init__.py', 'rt', encoding='utf8') as f:15 version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)1617setup(18 name='click',19 version=version,20 url='https://www.palletsprojects.com/p/click/',21 author='Armin Ronacher',22 author_email='armin.ronacher@active-4.com',18 version=version,19 url='http://github.com/pallets/click',23 maintainer='Pallets team',24 maintainer_email='contact@palletsprojects.com',25 long_description=readme,26 packages=['click'],27 description='A simple wrapper around optparse for '28 'powerful command line utilities.',29 license='BSD',30 extras_require={31 'dev': [32 'pytest>=3',33 'coverage',34 'tox',35 'sphinx',36 ],37 'docs': [38 'sphinx',39 ]40 },41 classifiers=[42 'Development Status :: 5 - Production/Stable',43 'Intended Audience :: Developers',44 'License :: OSI Approved :: BSD License',45 'Operating System :: OS Independent'46 'Programming Language :: Python',47 'Programming Language :: Python :: 2',48 'Programming Language :: Python :: 2.7',49 'Programming Language :: Python :: 3',50 'Programming Language :: Python :: 3.4',51 'Programming Language :: Python :: 3.5',52 'Programming Language :: Python :: 3.6',53 ],54 python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",55)
modified:tox.ini+3 added-4 removed
1[tox]2envlist = py{26,27,33,34,35,36,py}2envlist = py27,py34,py35,py36,pypy3skip_missing_interpreters = true45[testenv]6passenv = LANG7commands = {env:TEST_RUNNER:pytest} {posargs}8deps =8 {env:_CLICK_TEST_PYTEST_DEP:pytest}9 pytest10 colorama: colorama11 coverage: coverage12setenv =13 coverage: TEST_RUNNER=coverage run -m pytest13 # pytest 3.3+ does not support Python 2.6 and 3.3 anymore.14 py26,py33: _CLICK_TEST_PYTEST_DEP=pytest<3.3