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
Provenance
- Commit
a4b6bbd- Tree
331e1cb- Author
JosiahDub <josiahwhite@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9261af6- Parent 2
16da1e9
35 files changed+894 added−227 removed
modified:click/_termui_impl.py+94 added-75 removed
11 unmodified lines12 import os13 import sys14 import time15 import math16+import contextlib17 from ._compat import _default_text_stdout, range_type, PY2, isatty, \18 open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \19 CYGWIN20 from .utils import echo68 unmodified lines89 self.entered = False90 self.current_item = None91 self.is_hidden = not isatty(self.file)92 self._last_line = None93+ self.short_limit = 0.594 95 def __enter__(self):96 self.entered = True97 self.render_progress()5 unmodified lines103 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()108 109+ def is_fast(self):110+ return time.time() - self.start <= self.short_limit111+112 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 lines134 return 0.0135 136 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 lines196 }).rstrip()197 198 def render_progress(self):199 from .termui import get_terminal_size195- nl = False200 201 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+ return203 214- 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_width216 218- 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_width220 225- 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_len226 227+ buf.append(line)228+ buf.append(' ' * (clear_width - line_len))229+ line = ''.join(buf)230 # Render the line only if it changed.231+229- 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()236 237 def make_step(self, n_steps):238 self.pos += n_steps16 unmodified lines255 self.eta_known = 0256 self.current_item = None257 self.finished = True258 256- 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.')267+268 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 rv278 270- if not PY2:271- __next__ = next272- del next279 274-275-def pager(text, color=None):280+def 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)296 297 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)306 307 303-def _pipepager(text, cmd, color):308+def _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 subprocess9 unmodified lines322 color = True323 elif 'r' in less_flags or 'R' in less_flags:324 color = True325 321- if not color:322- text = strip_ansi(text)323-326 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)333+334+ c.stdin.write(text.encode(encoding, 'replace'))335 except (IOError, KeyboardInterrupt):336 pass337+ else:338+ c.stdin.close()339 340 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting341 # search or other commands inside less).342 #10 unmodified lines353 else:354 break355 356 350-def _tempfilepager(text, cmd, color):357+def _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 lines370 finally:371 os.unlink(filename)372 373 365-def _nullpager(stream, text, color):374+def _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)380 381 382 class Editor(object):383 140 unmodified lines524 525 if WIN:526 import msvcrt527 528+ @contextlib.contextmanager529+ def raw_terminal():530+ yield531+532 def getchar(echo):533 rv = msvcrt.getch()534 if echo:535 msvcrt.putchar(rv)8 unmodified lines544 else:545 import tty546 import termios547 534- 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 lines556 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 pass568+569+ 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
1 import errno2+import inspect3 import os4 import sys5 from contextlib import contextmanager6 from itertools import repeat2 unmodified lines9 from .types import convert_type, IntRange, BOOL10 from .utils import make_str, make_default_short_help, echo, get_os_args11 from .exceptions import ClickException, UsageError, BadParameter, Abort, \12 MissingParameter12-from .termui import prompt, confirm13+from .termui import prompt, confirm, style14 from .formatting import HelpFormatter, join_options15 from .parser import OptionParser, split_opt16 from .globals import push_context, pop_context17 17-from ._compat import PY2, isidentifier, iteritems18+from ._compat import PY2, isidentifier, iteritems, string_types19 from ._unicodefun import _check_for_unicode_literals, _verify_python3_env20 21 22 _missing = object()1 unmodified line24 25 SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'26 SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'27 28+DEPRECATED_HELP_NOTICE = ' (DEPRECATED)'29+DEPRECATED_INVOKE_NOTICE = 'DeprecationWarning: ' + \30+ 'The command %(name)s is deprecated.'31 32+33+def _maybe_show_deprecated_notice(cmd):34+ if cmd.deprecated:35+ echo(style(DEPRECATED_INVOKE_NOTICE % {'name': cmd.name}, fg='red'), err=True)36+37+38 def fast_exit(code):39 """Exit without garbage collection, this speeds up exit by about 10ms for40 things like bash completion.41 """346 unmodified lines388 389 @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.395 396 The keys are supposed to be unique dotted strings. For instance363 unmodified lines760 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.764+765+ :param deprecated: issues a message indicating that766+ the command is deprecated.767 """768 769 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 = callback4 unmodified lines781 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 = deprecated795 796 def get_usage(self, ctx):797 formatter = ctx.make_formatter()798 self.format_usage(ctx, formatter)45 unmodified lines844 845 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 lines876 """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)888 889 def format_options(self, ctx, formatter):890 """Writes all the options into the formatter if they exist."""891 opts = []32 unmodified lines924 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)931 932 107 unmodified lines1040 if cmd.hidden:1041 continue1042 1043 help = cmd.short_help or ''1044+ if cmd.deprecated:1045+ help += DEPRECATED_HELP_NOTICE1046 rows.append((subcommand, help))1047 1048 if rows:1049 with formatter.section('Commands'):304 unmodified lines1354 1355 def add_to_parser(self, parser, ctx):1356 pass1357 1358+1359 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 value1366 1367 def type_cast_value(self, ctx, value):1368 """Given a value this runs it properly through the type system.88 unmodified lines1457 1458 def get_usage_pieces(self, ctx):1459 return []1460 1461+ 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)1467 1468+1469 class Option(Parameter):1470 """Options are usually optional values on the command line and1471 have some extra features that arguments don't have.1472 1473 All other parameters are passed onwards to the parameter constructor.1474 1475 :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 confirmed23 unmodified lines1509 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)1517 1518 if prompt is True:38 unmodified lines1557 self.allow_from_autoenv = allow_from_autoenv1558 self.help = help1559 self.show_default = show_default1560 self.show_choices = show_choices1561+ self.show_envvar = show_envvar1562 1563 # Sanity check for stuff we don't support1564 if __debug__:1565 if self.nargs < 0:105 unmodified lines1671 rv.append(_write_opts(self.secondary_opts))1672 1673 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))1696+1697 if self.required:1698 extra.append('required')1699 if extra:1700 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))86 unmodified lines1787 1788 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 lines1814 1815 def get_usage_pieces(self, ctx):1816 return [self.make_metavar()]1817 1818+ def get_error_hint(self, ctx):1819+ return '"%s"' % self.make_metavar()1820+1821 def add_to_parser(self, parser, ctx):1822 parser.add_argument(dest=self.name, nargs=self.nargs,1823 obj=self)1824 3 unmodified linesmodified:click/decorators.py+7 added-4 removed
162 unmodified lines163 :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()169+167- 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 decorator176 177 134 unmodified linesmodified:click/exceptions.py+11 added-6 removed
1 from ._compat import PY2, filename_to_ui, get_text_stderr2 from .utils import echo3 4 5+def _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_hint9+10+11 class ClickException(Exception):12 """An exception that Click can handle and show to the user."""13 14 #: The exit code for this exception82 unmodified lines97 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)105+106 return 'Invalid value for %s: %s' % (param_hint, self.message)107 108 109 class MissingParameter(BadParameter):16 unmodified lines126 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)134 135 param_type = self.param_type136 if param_type is None and self.param is not None:137 param_type = self.param.param_type_name88 unmodified linesmodified:click/termui.py+64 added-12 removed
1 import os2 import sys3 import struct4+import inspect5+import itertools6 7 from ._compat import raw_input, text_type, string_types, \8 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN9 from .utils import echo5 unmodified lines15 # The prompt functions to use. The doc tools currently override these16 # functions to customize how they work.17 visible_prompt_func = raw_input18 17-_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'39 40 41 def hidden_prompt_func(prompt):150 unmodified lines192 if shutil_get_terminal_size:193 sz = shutil_get_terminal_size()194 return sz.columns, sz.lines195 196+ # 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 size204 205 def ioctl_gwinsz(fd):206 try:207 import fcntl19 unmodified lines227 os.environ.get('COLUMNS', DEFAULT_COLUMNS))228 return int(cr[1]), int(cr[0])229 230 206-def echo_via_pager(text, color=None):231+def echo_via_pager(text_or_generator, color=None):232 """This function takes a text and shows it via an environment specific233 pager on stdout.234 235 .. versionchanged:: 3.0236 Added the `color` flag.237 213- :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)244+245+ 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)251+252+ # 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)255+256 from ._termui_impl import pager221- return pager(text + '\n', color)257+ return pager(itertools.chain(text_generator, "\n"), color)258 259 260 def progressbar(iterable=None, length=None, label=None, show_eta=True,261 show_percent=None, show_pos=False,128 unmodified lines390 * ``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)403 404 .. versionadded:: 2.0405 406+ .. versionadded:: 7.0407+ Added support for bright colors.408+409 :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 lines423 """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 lines566 from ._termui_impl import getchar as f567 return f(echo)568 569 570+def raw_terminal():571+ from ._termui_impl import raw_terminal as f572+ return f()573+574+575 def 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 command23 unmodified linesmodified:click/testing.py+58 added-17 removed
71 unmodified lines72 73 class Result(object):74 """Holds the captured result of an invoked CLI script."""75 76- 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 = exception1 unmodified line89 self.exc_info = exc_info90 91 @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.stdout95+96+ @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')101 102+ @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')109+110+111 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 )116 117 10 unmodified lines128 :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 """138 117- 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_stderr147 148 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 not36 unmodified lines187 188 env = self.make_env(env)189 190 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)209 210+ if self.mix_stderr:211+ sys.stderr = sys.stdout212+213 sys.stdin = input214 215 def visible_input(prompt=None):216 sys.stdout.write(prompt or '')40 unmodified lines257 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 lines277 clickpkg.utils.should_strip_ansi = old_should_strip_ansi278 clickpkg.formatting.FORCED_WIDTH = old_forced_width279 280 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 lines309 :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 = 0316 317 if isinstance(args, string_types):318 args = shlex.split(args)319 320 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)324+325+ 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 lines345 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()351 352 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 linesmodified:click/types.py+23 added-7 removed
131 unmodified lines132 You should only pass *choices* as list or tuple. Other iterables (like133 generators) may lead to surprising results.134 135 See :ref:`choice-opts` for an example.136+137+ :param case_sensitive: Set to false to make choices case insensitive.138+ Defaults to true.139 """140 name = 'choice'141 139- def __init__(self, choices):142+ def __init__(self, choices, case_sensitive=True):143 self.choices = choices144+ self.case_sensitive = case_sensitive145 146 def get_metavar(self, param):147 return '[%s]' % '|'.join(self.choices)148 4 unmodified lines153 # Exact match154 if value in self.choices:155 return value156 153- # 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.choices163+164 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]169 170+ if not self.case_sensitive:171+ normed_value = normed_value.lower()172+ normed_choices = [choice.lower() for choice in normed_choices]173+174+ if normed_value in normed_choices:175+ return normed_value176+177 self.fail('invalid choice: %s. (choose from %s)' %178 (value, ', '.join(self.choices)), param, ctx)179 180 def __repr__(self):111 unmodified lines292 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 linesmodified:click/utils.py+1 added-1 removed
182 unmodified lines183 - add transparent handling of ANSI color codes on Windows.184 - hide ANSI codes automatically if the destination file is not a185 terminal.186 187- .. _colorama: http://pypi.python.org/pypi/colorama187+ .. _colorama: https://pypi.org/project/colorama/188 189 .. 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 modify225 unmodified linesmodified:docs/_templates/sidebarintro.html+1 added-1 removed
5 unmodified lines6 </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 lines294 ))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 linesmodified:docs/arguments.rst+18 added
241 unmodified lines242 243 .. click:run::244 245 invoke(touch, ['--', '-foo.txt', 'bar.txt'])246+247+If you don't like the ``--`` marker, you can set ignore_unknown_options to248+True to avoid checking unknown options:249+250+.. click:example::251+252+ @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)257+258+And from the command line:259+260+.. click:run::261+262+ invoke(touch, ['-foo.txt', 'bar.txt'])263+modified:docs/bashcomplete.rst+1 added-1 removed
93 unmodified lines94 95 . /path/to/foo-bar-complete.sh96 97 Zsh Compatibility98-----------------98+-----------------99 100 To enable Bash completion in Zsh, add the following lines to your .zshrc:101 102 autoload bashcompinit4 unmodified linesmodified:docs/clickdoctools.py+9 added-2 removed
13 unmodified lines14 from docutils import nodes15 from docutils.statemachine import ViewList16 17 from sphinx.domains import Domain18-from sphinx.util.compat import Directive18+from docutils.parsers.rst import Directive19 20+PY2 = sys.version_info[0] == 221 22+if PY2:23+ text_type = unicode24+else:25+ text_type = str26+ 27+28 class EchoingStdin(object):29 30 def __init__(self, input, output):31 self._input = input44 unmodified lines76 77 78 @contextlib.contextmanager79 def 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 linesmodified:docs/complex.rst+5 added-5 removed
151 unmodified lines152 One obvious way to remedy this is to store a reference to the repo in the153 plugin, but then a command needs to be aware that it's attached below such a154 plugin.155 156-There is a much better system that can built by taking advantage of the linked157-nature of contexts. We know that the plugin context is linked to the context158-that created our repo. Because of that, we can start a search for the last159-level where the object stored by the context was a repo.156+There is a much better system that can be built by taking advantage of the157+linked nature of contexts. We know that the plugin context is linked to the158+context that created our repo. Because of that, we can start a search for159+the last level where the object stored by the context was a repo.160 161 Built-in support for this is provided by the :func:`make_pass_decorator`162 factory, which will create decorators for us that find objects (it163 internally calls into :meth:`Context.find_object`). In our case, we45 unmodified lines209 210 @click.command()211 @pass_repo212 def cp(repo):213- click.echo(repo)213+ click.echo(isinstance(repo, Repo))214 215 As you can see:216 217 .. click:run::2 unmodified linesmodified:docs/options.rst+28 added
43 unmodified lines44 45 In this case the option is of type :data:`INT` because the default value46 is an integer.47 48+To show the default values when showing command help, use ``show_default=True``49+50+.. click:example::51+52+ @click.command()53+ @click.option('--n', default=1, show_default=True)54+ def dots(n):55+ click.echo('.' * n)56+57+.. click:run::58+59+ invoke(dots, args=['--help'])60+61 Multi Value Options62 -------------------63 64 Sometimes, you have options that take more than one argument. For options,336 unmodified lines401 default=lambda: os.environ.get('USER', ''))402 def hello(username):403 print("Hello,", username)404 405+To describe what the default value will be, set it in ``show_default``.406+407+.. click:example::408+409+ @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)415+416+.. click:run::417+418+ invoke(hello, args=['--help'])419+420 Callbacks and Eager Options421 ---------------------------422 423 Sometimes, you want a parameter to completely change the execution flow.315 unmodified linesmodified:docs/python3.rst+1 added-1 removed
4 unmodified lines5 6 Click supports Python 3, but like all other command line utility libraries,7 it suffers from the Unicode text model in Python 3. All examples in the8 documentation were written so that they could run on both Python 2.x and9-Python 3.3 or higher.9+Python 3.4 or higher.10 11 At the moment, it is strongly recommended to use Python 2 for Click12 utilities unless Python 3 is a hard requirement.13 170 unmodified linesmodified:docs/utils.rst+14 added-3 removed
39 unmodified lines40 .. versionadded:: 6.041 42 Click now emulates output streams on Windows to support unicode to the43 Windows console through separate APIs. For more information see44-`wincmd`_.44+:doc:`wincmd`.45 46 .. versionadded:: 3.047 48 Starting with Click 3.0 you can also easily print to standard error by45 unmodified lines94 click.secho('Some more text', bg='blue', fg='white')95 click.secho('ATTENTION', blink=True, bold=True)96 97 98-.. _colorama: https://pypi.python.org/pypi/colorama98+.. _colorama: https://pypi.org/project/colorama/99 100 Pager Support101 -------------102 10 unmodified lines113 def less():114 click.echo_via_pager('\n'.join('Line %d' % idx115 for idx in range(200)))116 117+If 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:118 119+.. click:example::120+ def _generate_output():121+ for idx in range(50000):122+ yield "Line %d\n" % idx123+124+ @click.command()125+ def less():126+ click.echo_via_pager(_generate_output())127+128+129 Screen Clearing130 ---------------131 132 .. versionadded:: 2.0160 unmodified lines293 .. versionadded:: 6.0294 295 Click now emulates output streams on Windows to support unicode to the296 Windows console through separate APIs. For more information see286-`wincmd`_.297+:doc:`wincmd`.298 299 300 Intelligent File Opening301 ------------------------108 unmodified linesmodified:docs/why.rst+1 added-1 removed
6 unmodified lines7 This question is easy to answer: because there is not a single command8 line utility for Python out there which ticks the following boxes:9 10 * 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 3137 unmodified linesmodified:examples/colors/colors.py+3 added-1 removed
1 import click2 3 4 all_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'8 9 10 @click.command()11 def cli():17 unmodified linesmodified:tests/test_arguments.py+2 added-2 removed
186 unmodified lines187 click.echo('arg:' + '|'.join(arg))188 189 result = runner.invoke(cmd2, [])190 assert result.exit_code == 2191- assert 'Missing argument "arg"' in result.output191+ assert 'Missing argument "ARG..."' in result.output192 193 194 def test_missing_arg(runner):195 @click.command()2 unmodified lines198 click.echo('arg:' + arg)199 200 result = runner.invoke(cmd, [])201 assert result.exit_code == 2202- assert 'Missing argument "arg".' in result.output202+ assert 'Missing argument "ARG".' in result.output203 204 205 def test_implicit_non_required(runner):206 @click.command()83 unmodified linesmodified:tests/test_basic.py+1 added-1 removed
185 unmodified lines186 @click.option('--flag', default=default, type=bool)187 def cli(flag):188 click.echo(flag)189 190- 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 linesmodified:tests/test_commands.py+30 added-10 removed
1 # -*- coding: utf-8 -*-2 import re3+4 import click5+import pytest6 7 8 def test_other_command_invoke(runner):9 @click.command()48 unmodified lines58 def long():59 """This is a long text that is too long to show as short help60 and will be truncated instead."""61 62+ @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."""66+67 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 None75 76 77 def test_default_maps(runner):184 unmodified lines262 'Args: -foo|-x|--muhaha|x|y|-x',263 ]264 265 258-def test_subcommand_naming(runner):259- @click.group()260- def cli():266+def test_deprecated_in_help_messages(runner):267+ @click.command(deprecated=True)268+ def cmd_with_help():269+ """CLI HELP"""270 pass271 263- @cli.command()264- def foo_bar():265- click.echo('foo-bar')272+ result = runner.invoke(cmd_with_help, ['--help'])273+ assert '(DEPRECATED)' in result.output274 267- 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+ pass278+279+ result = runner.invoke(cmd_without_help, ['--help'])280+ assert '(DEPRECATED)' in result.output281+282+283+def test_deprecated_in_invocation(runner):284+ @click.command(deprecated=True)285+ def deprecated_cmd():286+ debug()287+288+ result = runner.invoke(deprecated_cmd)289+ assert 'DeprecationWarning:' in result.outputmodified:tests/test_formatting.py+60 added-4 removed
157 unmodified lines158 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 ]164 165 166+def 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+ pass175+176+ 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+ ]184+185+186+def 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+ pass191+192+ 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+ ]200+201+202 def test_formatting_usage_error_nested(runner):203 @click.group()204 def cmd():205 pass8 unmodified lines214 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 ]220 221 222 def test_formatting_usage_error_no_help(runner):6 unmodified lines229 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 ]235 236 237 def test_formatting_usage_custom_help(runner):7 unmodified lines245 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 ]251+252+def test_formatting_custom_type_metavar(runner):253+ class MyType(click.ParamType):254+ def get_metavar(self, param):255+ return "MY_TYPE"256+257+ @click.command("foo")258+ @click.help_option()259+ @click.argument("param", type=MyType())260+ def cmd(param):261+ pass262+263+ 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 lines31 32 ALLOWED_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 ])37 38 if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',16 unmodified linesmodified:tests/test_options.py+111 added-1 removed
172 unmodified lines173 result = runner.invoke(cmd, '--arg1 a b --arg1 test 1 --arg2 2 '174 'two --arg2 4 four'.split())175 assert not result.exception176 177+def 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)184 185+ 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.output190+191+def 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)198+199+ 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.output204+205 def test_nargs_envvar(runner):206 @click.command()207 @click.option('--arg', nargs=2)208 def cmd(arg):15 unmodified lines224 assert not result.exception225 assert result.output == 'x|1\ny|2\n'226 227 228+def test_show_envvar(runner):229+ @click.command()230+ @click.option('--arg1', envvar='ARG1',231+ show_envvar=True)232+ def cmd(arg):233+ pass234+235+ result = runner.invoke(cmd, ['--help'])236+ assert not result.exception237+ assert 'ARG1' in result.output238+239+240+def test_show_envvar_auto_prefix(runner):241+ @click.command()242+ @click.option('--arg1', show_envvar=True)243+ def cmd(arg):244+ pass245+246+ result = runner.invoke(cmd, ['--help'],247+ auto_envvar_prefix='TEST')248+ assert not result.exception249+ assert 'TEST_ARG1' in result.output250+251+252 def 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 lines309 assert 'Error: Missing option "--foo". Choose from foo, bar.' \310 in result.output311 312 313+def 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)319+320+ result = runner.invoke(cmd, ['--foo', 'apple'])321+ assert result.exit_code == 0322+323+ result = runner.invoke(cmd, ['--foo', 'oRANGe'])324+ assert result.exit_code == 0325+326+ result = runner.invoke(cmd, ['--foo', 'Apple'])327+ assert result.exit_code == 0328+329+ @click.command()330+ @click.option('--foo', type=click.Choice(['Orange', 'Apple']))331+ def cmd2(foo):332+ click.echo(foo)333+334+ result = runner.invoke(cmd2, ['--foo', 'apple'])335+ assert result.exit_code == 2336+337+ result = runner.invoke(cmd2, ['--foo', 'oRANGe'])338+ assert result.exit_code == 2339+340+ result = runner.invoke(cmd2, ['--foo', 'Apple'])341+ assert result.exit_code == 0342+343+344 def test_multiline_help(runner):345 @click.command()346 @click.option('--foo', help="""347 hello11 unmodified lines359 assert ' --foo TEXT hello' in out360 assert ' i am' in out361 assert ' multiline' in out362 281-363 def 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 lines391 assert 'I am a help text' in result.output392 assert 'you wont see me' not in result.output393 394 395+def test_option_custom_class_reusable(runner):396+ """Ensure we can reuse a custom class option. See Issue #926"""397+398+ 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')402+403+ # Assign to a variable to re-use the decorator.404+ testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')405+406+ @click.command()407+ @testoption408+ def cmd1(testoption):409+ click.echo(testoption)410+411+ @click.command()412+ @testoption413+ def cmd2(testoption):414+ click.echo(testoption)415+416+ # Both of the commands should have the --help option now.417+ for cmd in (cmd1, cmd2):418+419+ result = runner.invoke(cmd, ['--help'])420+ assert 'I am a help text' in result.output421+ assert 'you wont see me' not in result.output422+423+424 def test_aliases_for_flags(runner):425 @click.command()426 @click.option('--warnings/--no-warnings', ' /-W', default=True)427 def cli(warnings):46 unmodified linesmodified:tests/test_termui.py+63 added-4 removed
1 import click2+import time3 4 5+class FakeClock(object):6+ def __init__(self):7+ self.now = time.time()8+9+ def advance_time(self, seconds=1):10+ self.now += seconds11+12+ def time(self):13+ return self.now14+15+16 def test_progressbar_strip_regression(runner, monkeypatch):17+ fake_clock = FakeClock()18 label = ' padded line'19 20 @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()25 26+ monkeypatch.setattr(time, 'time', fake_clock.time)27 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)28 assert label in runner.invoke(cli, []).output29 30 15 unmodified lines46 raise StopIteration47 48 next = __next__49 50+ fake_clock = FakeClock()51+52 @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()57 58+ 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 None62 63 64+def test_progressbar_hidden(runner, monkeypatch):65+ fake_clock = FakeClock()66+ label = 'whatever'67+68+ @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()73+74+ monkeypatch.setattr(time, 'time', fake_clock.time)75+ monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)76+ assert runner.invoke(cli, []).output == ''77+78+79 def 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 lines96 assert '(none, day, week, month)' not in result.output97 98 99 def 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''104+105+106+def test_progressbar_yields_all_items(runner):107+ with click.progressbar(range(3)) as progress:108+ assert len(list(progress)) == 3109+110+111+def test_progressbar_update(runner, monkeypatch):112+ fake_clock = FakeClock()113+114+ @click.command()115+ def cli():116+ with click.progressbar(range(4)) as progress:117+ for _ in progress:118+ fake_clock.advance_time()119+ print("")120+121+ monkeypatch.setattr(time, 'time', fake_clock.time)122+ monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)123+ output = runner.invoke(cli, []).output124+125+ lines = [line for line in output.split('\n') if '[' in line]126+127+ 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 lines203 204 assert os.environ == env_orig205 206 207+def test_stderr():208+ @click.command()209+ def cli_stderr():210+ click.echo("stdout")211+ click.echo("stderr", err=True)212+213+ runner = CliRunner(mix_stderr=False)214+215+ result = runner.invoke(cli_stderr)216+217+ assert result.output == 'stdout\n'218+ assert result.stdout == 'stdout\n'219+ assert result.stderr == 'stderr\n'220+221+ runner_mix = CliRunner(mix_stderr=True)222+ result_mix = runner_mix.invoke(cli_stderr)223+224+ assert result_mix.output == 'stdout\nstderr\n'225+ assert result_mix.stdout == 'stdout\nstderr\n'226+227+ with pytest.raises(ValueError):228+ result_mix.stderr229+230+231 @pytest.mark.parametrize('args, expected_output', [232 (None, 'bar\n'),233 ([], 'bar\n'),234 ('', 'bar\n'),10 unmodified lines245 runner = CliRunner()246 result = runner.invoke(cli_args, args=args)247 assert result.exit_code == 0248 assert result.output == expected_output249+250+251+def test_setting_prog_name_in_extra():252+ @click.command()253+ def cli():254+ click.echo("ok")255+256+ 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 lines9 from click._compat import WIN, PY210 11 12 def 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'21 22 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 310 unmodified lines34 @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'39 40 # 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'44 45 46 def test_echo_custom_file():47 import io97 unmodified lines145 out, err = capsys.readouterr()146 assert out == 'Password: \nScrew you.\n'147 148 149+def _test_gen_func():150+ yield 'a'151+ yield 'b'152+ yield 'c'153+ yield 'abc'154+155+156 @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+])151-def test_echo_via_pager(monkeypatch, capfd, cat):168+def 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)171+172+ expected_output = test[0]173+ test_input = test[1]()174+154- click.echo_via_pager('haha')175+ click.echo_via_pager(test_input)176+177 out, err = capfd.readouterr()156- assert out == 'haha\n'178+ assert out == expected_output179 180 181 @pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')182 def test_echo_color_flag(monkeypatch, capfd):106 unmodified lines289 def 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()296 297 298 @pytest.mark.xfail(WIN and not PY2, reason='God knows ...')299 def 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 lines7 dist8 build9 docs/_build10 click.egg-info11+venv/12 .tox13 .cache14 .ropeproject15 .ideamodified:.travis.yml-2 removed
1 sudo: false2 language: python3 python:4- - "2.6"4 - "2.7"6- - "3.3"5 - "3.4"6 - "3.5"7 - "3.6"8 - "pypy"35 unmodified linesmodified:CHANGES+4 added-2 removed
5 unmodified lines6 Version 7.07 -----------8 9 (upcoming release with new features, release date to be decided)10+11 - 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 and8 unmodified lines23 - 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 return370 unmodified linesdeleted:README-20 removed
1-$ click_2-3- 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.7-8- 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.11-12- Click in three points:13-14- - arbitrary nesting of commands15- - automatic help page generation16- - supports lazy loading of subcommands at runtime17-18- Read the docs at http://click.pocoo.org/19-20- This library is stable and active. Feedback is always welcome!added:README.rst+91 added
1+\$ click\_2+==========3+4+What's Click?5+-------------6+7+Click is a Python package for creating beautiful command line interfaces8+in a composable way with as little code as necessary. It's the "Command9+Line Interface Creation Kit". It's highly configurable but comes with10+sensible defaults out of the box.11+12+It aims to make the process of writing command line tools quick and fun13+while also preventing any frustration caused by the inability to implement14+an intended CLI API.15+16+Click in three points:17+ - arbitrary nesting of commands18+ - automatic help page generation19+ - supports lazy loading of subcommands at runtime20+21+22+Installing23+----------24+25+Install and update using `pip`_:26+27+.. code-block:: text28+29+ $ pip install click30+31+Click supports Python 3.4 and newer, Python 2.7, and PyPy32+33+A Simple Example34+----------------35+36+What does it look like? Here is an example of a simple Click program:37+38+.. code-block:: python39+40+ 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()53+54+And what it looks like when run:55+56+.. code-block:: text57+58+ $ python hello.py --count=359+ Your name: John60+ Hello John!61+ Hello John!62+ Hello John!63+64+Donate65+------66+67+The Pallets organization develops and supports Flask and the libraries68+it uses. In order to grow the community of contributors and users, and69+allow the maintainers to devote more time to the projects, `please70+donate today`_.71+72+.. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=2073+74+75+Links76+-----77+78+* 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:85+86+ * Linux, Mac: https://travis-ci.org/pallets/click87+ * Windows: https://ci.appveyor.com/project/pallets/click88+89+* Test coverage: https://codecov.io/gh/pallets/click90+91+.. _pip: https://pip.pypa.io/en/stable/quickstart/modified:setup.py+33 added-6 removed
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+import io4 import re2-import ast5 from setuptools import setup6 7 8 _version_re = re.compile(r'__version__\s+=\s+(.*)')9 10 9-with open('click/__init__.py', 'rb') as f:10- version = str(ast.literal_eval(_version_re.search(11- f.read().decode('utf-8')).group(1)))11+with io.open('README.rst', 'rt', encoding='utf8') as f:12+ readme = f.read()13 14+with io.open('click/__init__.py', 'rt', encoding='utf8') as f:15+ version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)16 17 setup(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]2-envlist = py{26,27,33,34,35,36,py}2+envlist = py27,py34,py35,py36,pypy3+skip_missing_interpreters = true4 5 [testenv]6 passenv = LANG7 commands = {env:TEST_RUNNER:pytest} {posargs}8 deps =8- {env:_CLICK_TEST_PYTEST_DEP:pytest}9+ pytest10 colorama: colorama11 coverage: coverage12 setenv =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