Fix test for delayed progress bar display
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jan Christoph Bischko · committed by Jan Christoph Bischko · parent 6126661 · Browse files · 50 files·+1983 added−364 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
50 files+1983 added−364 removed
- tests:+851 added−33 removed
- other:+1132 added−331 removed
Provenance
- Commit
82f9c62- Tree
51ecf3a- Author
Jan Christoph Bischko <jbischko@barracuda.com>- Committer
Jan Christoph Bischko <jbischko@barracuda.com>- Parent
6126661
50 files changed+1983 added−364 removed
modified:click/__init__.py+2 added-2 removed
26 unmodified lines27 password_option, version_option, help_option28 29 # Types30 from .types import ParamType, File, Path, Choice, IntRange, Tuple, \31- STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED31+ STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange32 33 # Utilities34 from .utils import echo, get_binary_stream, get_text_stream, open_file, \35 format_filename, get_app_dir, get_os_args29 unmodified lines65 'version_option', 'help_option',66 67 # Types68 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple', 'STRING',69- 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',69+ 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED', 'FloatRange',70 71 # Utilities72 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',73 'format_filename', 'get_app_dir', 'get_os_args',25 unmodified linesmodified:click/_bashcomplete.py+163 added-24 removed
1+import collections2+import copy3 import os4 import re5+6 from .utils import echo7 from .parser import split_arg_string5-from .core import MultiCommand, Option8+from .core import MultiCommand, Option, Argument9+from .types import Choice10 11+WORDBREAK = '='12 13 COMPLETION_SCRIPT = '''14 %(complete_func)s() {15+ local IFS=$'\n'16 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\17 COMP_CWORD=$COMP_CWORD \\18 %(autocomplete_var)s=complete $1 ) )19 return 014 unmodified lines34 }).strip() + ';'35 36 37 def resolve_ctx(cli, prog_name, args):38+ """39+ Parse into a hierarchy of contexts. Contexts are connected through the parent variable.40+ :param cli: command definition41+ :param prog_name: the program that is running42+ :param args: full list of args43+ :return: the final context/command parsed44+ """45 ctx = cli.make_context(prog_name, args, resilient_parsing=True)46+ args_remaining = ctx.protected_args + ctx.args47+ while ctx is not None and args_remaining:33- while ctx.args and isinstance(ctx.command, MultiCommand):34- cmd = ctx.command.get_command(ctx, ctx.args[0])35- if cmd is None:36- return None37- ctx = cmd.make_context(ctx.args[0], ctx.args[1:], parent=ctx,38- resilient_parsing=True)48+ if isinstance(ctx.command, MultiCommand):49+ cmd = ctx.command.get_command(ctx, args_remaining[0])50+ if cmd is None:51+ return None52+ ctx = cmd.make_context(53+ args_remaining[0], args_remaining[1:], parent=ctx, resilient_parsing=True)54+ args_remaining = ctx.protected_args + ctx.args55+ else:56+ ctx = ctx.parent57+58 return ctx59 60 61+def start_of_option(param_str):62+ """63+ :param param_str: param_str to check64+ :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")65+ """66+ return param_str and param_str[:1] == '-'67+68+69+def is_incomplete_option(all_args, cmd_param):70+ """71+ :param all_args: the full original list of args supplied72+ :param cmd_param: the current command paramter73+ :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and74+ corresponds to this cmd_param. In other words whether this cmd_param option can still accept75+ values76+ """77+ if not isinstance(cmd_param, Option):78+ return False79+ if cmd_param.is_flag:80+ return False81+ last_option = None82+ for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])):83+ if index + 1 > cmd_param.nargs:84+ break85+ if start_of_option(arg_str):86+ last_option = arg_str87+88+ return True if last_option and last_option in cmd_param.opts else False89+90+91+def is_incomplete_argument(current_params, cmd_param):92+ """93+ :param current_params: the current params and values for this argument as already entered94+ :param cmd_param: the current command parameter95+ :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In96+ other words whether or not the this cmd_param argument can still accept values97+ """98+ if not isinstance(cmd_param, Argument):99+ return False100+ current_param_values = current_params[cmd_param.name]101+ if current_param_values is None:102+ return True103+ if cmd_param.nargs == -1:104+ return True105+ if isinstance(current_param_values, collections.Iterable) \106+ and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:107+ return True108+ return False109+110+111+def get_user_autocompletions(ctx, args, incomplete, cmd_param):112+ """113+ :param ctx: context associated with the parsed command114+ :param args: full list of args115+ :param incomplete: the incomplete text to autocomplete116+ :param cmd_param: command definition117+ :return: all the possible user-specified completions for the param118+ """119+ if isinstance(cmd_param.type, Choice):120+ return [c for c in cmd_param.type.choices if c.startswith(incomplete)]121+ elif cmd_param.autocompletion is not None:122+ return cmd_param.autocompletion(ctx=ctx,123+ args=args,124+ incomplete=incomplete)125+ else:126+ return []127+128+129+def add_subcommand_completions(ctx, incomplete, completions_out):130+ # Add subcommand completions.131+ if isinstance(ctx.command, MultiCommand):132+ completions_out.extend(133+ [c for c in ctx.command.list_commands(ctx) if c.startswith(incomplete)])134+135+ # Walk up the context list and add any other completion possibilities from chained commands136+ while ctx.parent is not None:137+ ctx = ctx.parent138+ if isinstance(ctx.command, MultiCommand) and ctx.command.chain:139+ remaining_commands = sorted(140+ set(ctx.command.list_commands(ctx)) - set(ctx.protected_args))141+ completions_out.extend(142+ [c for c in remaining_commands if c.startswith(incomplete)])143+144+145+def get_choices(cli, prog_name, args, incomplete):146+ """147+ :param cli: command definition148+ :param prog_name: the program that is running149+ :param args: full list of args150+ :param incomplete: the incomplete text to autocomplete151+ :return: all the possible completions for the incomplete152+ """153+ all_args = copy.deepcopy(args)154+155+ ctx = resolve_ctx(cli, prog_name, args)156+ if ctx is None:157+ return []158+159+ # In newer versions of bash long opts with '='s are partitioned, but it's easier to parse160+ # without the '='161+ if start_of_option(incomplete) and WORDBREAK in incomplete:162+ partition_incomplete = incomplete.partition(WORDBREAK)163+ all_args.append(partition_incomplete[0])164+ incomplete = partition_incomplete[2]165+ elif incomplete == WORDBREAK:166+ incomplete = ''167+168+ completions = []169+ if start_of_option(incomplete):170+ # completions for partial options171+ for param in ctx.command.params:172+ if isinstance(param, Option):173+ param_opts = [param_opt for param_opt in param.opts +174+ param.secondary_opts if param_opt not in all_args or param.multiple]175+ completions.extend(176+ [c for c in param_opts if c.startswith(incomplete)])177+ return completions178+ # completion for option values from user supplied values179+ for param in ctx.command.params:180+ if is_incomplete_option(all_args, param):181+ return get_user_autocompletions(ctx, all_args, incomplete, param)182+ # completion for argument values from user supplied values183+ for param in ctx.command.params:184+ if is_incomplete_argument(ctx.params, param):185+ completions.extend(get_user_autocompletions(186+ ctx, all_args, incomplete, param))187+ # Stop looking for other completions only if this argument is required.188+ if param.required:189+ return completions190+ break191+192+ add_subcommand_completions(ctx, incomplete, completions)193+ return completions194+195+196 def do_complete(cli, prog_name):197 cwords = split_arg_string(os.environ['COMP_WORDS'])198 cword = int(os.environ['COMP_CWORD'])199 args = cwords[1:cword]1 unmodified line201 incomplete = cwords[cword]202 except IndexError:203 incomplete = ''204 51- ctx = resolve_ctx(cli, prog_name, args)52- if ctx is None:53- return True205+ for item in get_choices(cli, prog_name, args, incomplete):206+ echo(item)207 55- choices = []56- if incomplete and not incomplete[:1].isalnum():57- for param in ctx.command.params:58- if not isinstance(param, Option):59- continue60- choices.extend(param.opts)61- choices.extend(param.secondary_opts)62- elif isinstance(ctx.command, MultiCommand):63- choices.extend(ctx.command.list_commands(ctx))64-65- for item in choices:66- if item.startswith(incomplete):67- echo(item)68-208 return True209 210 211 def bashcomplete(cli, prog_name, complete_var, complete_instr):6 unmodified linesmodified:click/_compat.py+71 added-21 removed
6 unmodified lines7 8 9 PY2 = sys.version_info[0] == 210 WIN = sys.platform.startswith('win')11+CYGWIN = sys.platform.startswith('cygwin')12 DEFAULT_COLUMNS = 8013 14 14-_ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')15+_ansi_re = re.compile(r'\033\[((?:\d|;)*)([a-zA-Z])')16 17 18 def get_filesystem_encoding():19 return sys.getfilesystemencoding() or sys.getdefaultencoding()20 21 21-def _make_text_stream(stream, encoding, errors):22+def _make_text_stream(stream, encoding, errors,23+ force_readable=False, force_writable=False):24 if encoding is None:25 encoding = get_best_encoding(stream)26 if errors is None:27 errors = 'replace'28 return _NonClosingTextIOWrapper(stream, encoding, errors,27- line_buffering=True)29+ line_buffering=True,30+ force_readable=force_readable,31+ force_writable=force_writable)32 33 34 def is_ascii_encoding(encoding):35 """Checks if a given encoding is ascii."""12 unmodified lines48 49 50 class _NonClosingTextIOWrapper(io.TextIOWrapper):51 48- def __init__(self, stream, encoding, errors, **extra):49- self._stream = stream = _FixupStream(stream)52+ def __init__(self, stream, encoding, errors,53+ force_readable=False, force_writable=False, **extra):54+ self._stream = stream = _FixupStream(stream, force_readable,55+ force_writable)56 io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)57 58 # The io module is a place where the Python 3 text behavior59 # was forced upon Python 2, so we need to unbreak26 unmodified lines86 class _FixupStream(object):87 """The new io interface needs more from streams than streams88 traditionally implement. As such, this fix-up code is necessary in89 some circumstances.90+91+ The forcing of readable and writable flags are there because some tools92+ put badly patched objects on sys (one such offender are certain version93+ of jupyter notebook).94 """95 86- def __init__(self, stream):96+ def __init__(self, stream, force_readable=False, force_writable=False):97 self._stream = stream98+ self._force_readable = force_readable99+ self._force_writable = force_writable100 101 def __getattr__(self, name):102 return getattr(self._stream, name)103 8 unmodified lines112 return self._stream.readline(size)113 return self._stream.read(size)114 115 def readable(self):116+ if self._force_readable:117+ return True118 x = getattr(self._stream, 'readable', None)119 if x is not None:120 return x()121 try:2 unmodified lines124 return False125 return True126 127 def writable(self):128+ if self._force_writable:129+ return True130 x = getattr(self._stream, 'writable', None)131 if x is not None:132 return x()133 try:42 unmodified lines176 # correct option here.177 #178 # This code also lives in _winconsole for the fallback to the console179 # emulation stream.164- if WIN:180+ #181+ # There are also Windows environments where the `msvcrt` module is not182+ # available (which is why we use try-catch instead of the WIN variable183+ # here), such as the Google App Engine development server on Windows. In184+ # those cases there is just nothing we can do.185+ def set_binary_mode(f):186+ return f187+188+ try:189 import msvcrt190+191 def set_binary_mode(f):192 try:193 fileno = f.fileno()194 except Exception:195 pass196 else:197 msvcrt.setmode(fileno, os.O_BINARY)198 return f174- else:175- set_binary_mode = lambda x: x199+ except ImportError:200+ pass201 202+ try:203+ import fcntl204+205+ def set_binary_mode(f):206+ try:207+ fileno = f.fileno()208+ except Exception:209+ pass210+ else:211+ flags = fcntl.fcntl(fileno, fcntl.F_GETFL)212+ fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)213+ return f214+ except ImportError:215+ pass216+217 def isidentifier(x):218 return _identifier_re.search(x) is not None219 220 def get_binary_stdin():8 unmodified lines229 def get_text_stdin(encoding=None, errors=None):230 rv = _get_windows_console_stream(sys.stdin, encoding, errors)231 if rv is not None:232 return rv193- return _make_text_stream(sys.stdin, encoding, errors)233+ return _make_text_stream(sys.stdin, encoding, errors,234+ force_readable=True)235 236 def get_text_stdout(encoding=None, errors=None):237 rv = _get_windows_console_stream(sys.stdout, encoding, errors)238 if rv is not None:239 return rv199- return _make_text_stream(sys.stdout, encoding, errors)240+ return _make_text_stream(sys.stdout, encoding, errors,241+ force_writable=True)242 243 def get_text_stderr(encoding=None, errors=None):244 rv = _get_windows_console_stream(sys.stderr, encoding, errors)245 if rv is not None:246 return rv205- return _make_text_stream(sys.stderr, encoding, errors)247+ return _make_text_stream(sys.stderr, encoding, errors,248+ force_writable=True)249 250 def filename_to_ui(value):251 if isinstance(value, bytes):252 value = value.decode(get_filesystem_encoding(), 'replace')83 unmodified lines336 return stream_encoding is not None337 338 return False339 297- def _force_correct_text_reader(text_reader, encoding, errors):340+ def _force_correct_text_reader(text_reader, encoding, errors,341+ force_readable=False):342 if _is_binary_reader(text_reader, False):343 binary_reader = text_reader344 else:345 # If there is no target encoding set, we need to verify that the17 unmodified lines363 # because nobody handles those errors anyways and at this point364 # we're so fundamentally fucked that nothing can repair it.365 if errors is None:366 errors = 'replace'323- return _make_text_stream(binary_reader, encoding, errors)367+ return _make_text_stream(binary_reader, encoding, errors,368+ force_readable=force_readable)369 325- def _force_correct_text_writer(text_writer, encoding, errors):370+ def _force_correct_text_writer(text_writer, encoding, errors,371+ force_writable=False):372 if _is_binary_writer(text_writer, False):373 binary_writer = text_writer374 else:375 # If there is no target encoding set, we need to verify that the17 unmodified lines393 # because nobody handles those errors anyways and at this point394 # we're so fundamentally fucked that nothing can repair it.395 if errors is None:396 errors = 'replace'351- return _make_text_stream(binary_writer, encoding, errors)397+ return _make_text_stream(binary_writer, encoding, errors,398+ force_writable=force_writable)399 400 def get_binary_stdin():401 reader = _find_binary_reader(sys.stdin)402 if reader is None:18 unmodified lines421 def get_text_stdin(encoding=None, errors=None):422 rv = _get_windows_console_stream(sys.stdin, encoding, errors)423 if rv is not None:424 return rv378- return _force_correct_text_reader(sys.stdin, encoding, errors)425+ return _force_correct_text_reader(sys.stdin, encoding, errors,426+ force_readable=True)427 428 def get_text_stdout(encoding=None, errors=None):429 rv = _get_windows_console_stream(sys.stdout, encoding, errors)430 if rv is not None:431 return rv384- return _force_correct_text_writer(sys.stdout, encoding, errors)432+ return _force_correct_text_writer(sys.stdout, encoding, errors,433+ force_writable=True)434 435 def get_text_stderr(encoding=None, errors=None):436 rv = _get_windows_console_stream(sys.stderr, encoding, errors)437 if rv is not None:438 return rv390- return _force_correct_text_writer(sys.stderr, encoding, errors)439+ return _force_correct_text_writer(sys.stderr, encoding, errors,440+ force_writable=True)441 442 def filename_to_ui(value):443 if isinstance(value, bytes):444 value = value.decode(get_filesystem_encoding(), 'replace')20 unmodified lines465 atomic=False):466 # Standard streams first. These are simple because they don't need467 # special handling for the atomic flag. It's entirely ignored.468 if filename == '-':419- if 'w' in mode:469+ if any(m in mode for m in ['w', 'a', 'x']):470 if 'b' in mode:471 return get_binary_stdout(), False472 return get_text_stdout(encoding=encoding, errors=errors), False473 if 'b' in mode:31 unmodified lines505 f = io.open(fd, mode, encoding=encoding, errors=errors)506 else:507 f = os.fdopen(fd, mode)508 459- return _AtomicFile(f, tmp_filename, filename), True509+ return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True510 511 512 # Used in a destructor call, needs extra protection from interpreter cleanup.513 if hasattr(os, 'replace'):181 unmodified linesmodified:click/_termui_impl.py+83 added-69 removed
11 unmodified lines12 import os13 import sys14 import time15 import math16+17 from ._compat import _default_text_stdout, range_type, PY2, isatty, \17- open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types18+ open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \19+ CYGWIN20 from .utils import echo21 from .exceptions import ClickException22 23 8 unmodified lines32 def _length_hint(obj):33 """Returns the length hint of an object."""34 try:35 return len(obj)34- except TypeError:36+ except (AttributeError, TypeError):37 try:38 get_hint = type(obj).__length_hint__39 except AttributeError:40 return None62 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 22 unmodified lines134 return 0.0135 136 def format_eta(self):137 if self.eta_known:136- t = self.eta + 1138+ t = int(self.eta)139 seconds = t % 60138- t /= 60140+ t //= 60141 minutes = t % 60140- t /= 60142+ t //= 60143 hours = t % 24142- 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_size198- nl = False200 201 if self.is_hidden:201- buf = [self.label]202- nl = True203- else:204- 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_width202+ return203 217- clear_width = self.width218- if self.max_width is not None:219- 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 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- buf.append(line)217+ clear_width = self.width218+ if self.max_width is not None:219+ clear_width = self.max_width220 228- buf.append(' ' * (clear_width - line_len))229- 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 232 if line != self._last_line and not self.is_fast():233 self._last_line = line235- 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 260- 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:262- return next(self.iter)263- try:264- rv = next(self.iter)265- self.current_item = rv266- 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()269- raise StopIteration()270- else:271- self.update(1)272- return rv278 274- if not PY2:275- __next__ = next276- del next279 278-279-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):283- 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:287- return _tempfilepager(text, pager_cmd, color)288- 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'):290- return _nullpager(stdout, text, color)291+ return _nullpager(stdout, generator, color)292 if WIN or sys.platform.startswith('os2'):292- return _tempfilepager(text, 'more <', color)293+ return _tempfilepager(generator, 'more <', color)294 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:294- 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:301- return _pipepager(text, 'more', color)302- 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 307-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 325- if not color:326- text = strip_ansi(text)327-326 c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,327 env=env)328 encoding = get_best_encoding(c.stdin)329 try:332- c.stdin.write(text.encode(encoding, 'replace'))333- 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 354-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 369-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:371- if not color:372- text = strip_ansi(text)373- stream.write(text)377+ if not color:378+ text = strip_ansi(text)379+ stream.write(text)380 381 382 class Editor(object):383 104 unmodified lines488 else:489 args = 'start %s "" "%s"' % (490 wait and '/WAIT' or '', url.replace('"', ''))491 return os.system(args)492+ elif CYGWIN:493+ if locate:494+ url = _unquote_file(url)495+ args = 'cygstart "%s"' % (os.path.dirname(url).replace('"', ''))496+ else:497+ args = 'cygstart %s "%s"' % (498+ wait and '-w' or '', url.replace('"', ''))499+ return os.system(args)500 501 try:502 if locate:503 url = os.path.dirname(_unquote_file(url)) or '.'63 unmodified linesmodified:click/_unicodefun.py+10 added-6 removed
12 unmodified lines13 14 15 def _find_unicode_literals_frame():16 import __future__17+ if not hasattr(sys, '_getframe'): # not all Python implementations have it18+ return 019 frm = sys._getframe(1)20 idx = 121 while frm is not None:22 if frm.f_globals.get('__name__', '').startswith('click.'):38 unmodified lines61 62 extra = ''63 if os.name == 'posix':64 import subprocess65+ try:63- rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,64- stderr=subprocess.PIPE).communicate()[0]66+ rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,67+ stderr=subprocess.PIPE).communicate()[0]68+ except OSError:69+ rv = b''70 good_locales = set()71 has_c_utf8 = False72 73 # Make sure we're operating on text here.24 unmodified lines98 )99 else:100 extra += (101 'This system lists a couple of UTF-8 supporting locales that\n'97- 'you can pick from. The following suitable locales where\n'102+ 'you can pick from. The following suitable locales were\n'103 'discovered: %s'104 ) % ', '.join(sorted(good_locales))105 106 bad_locale = None11 unmodified lines118 ) % bad_locale119 120 raise RuntimeError('Click will abort further execution because Python 3 '121 'was configured to use ASCII as encoding for the '117- 'environment. Either run this under Python 2 or '118- 'consult http://click.pocoo.org/python3/ for '119- 'mitigation steps.' + extra)122+ 'environment. Consult http://click.pocoo.org/python3/ '123+ 'for mitigation steps.' + extra)modified:click/_winconsole.py+24 added-15 removed
14 unmodified lines15 import time16 import ctypes17 import msvcrt18 from click._compat import _NonClosingTextIOWrapper, text_type, PY219-from ctypes import byref, POINTER, pythonapi, c_int, c_char, c_char_p, \19+from ctypes import byref, POINTER, c_int, c_char, c_char_p, \20 c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE21+try:22+ from ctypes import pythonapi23+ PyObject_GetBuffer = pythonapi.PyObject_GetBuffer24+ PyBuffer_Release = pythonapi.PyBuffer_Release25+except ImportError:26+ pythonapi = None27 from ctypes.wintypes import LPWSTR, LPCWSTR28 29 30 c_ssize_p = POINTER(c_ssize_t)31 26-PyObject_GetBuffer = pythonapi.PyObject_GetBuffer27-PyBuffer_Release = pythonapi.PyBuffer_Release28-32 kernel32 = windll.kernel3233 GetStdHandle = kernel32.GetStdHandle34 ReadConsoleW = kernel32.ReadConsoleW35 WriteConsoleW = kernel32.WriteConsoleW43 unmodified lines79 if PY2:80 _fields_.insert(-1, ('smalltable', c_ssize_t * 2))81 82 83+# On PyPy we cannot get buffers so our ability to operate here is84+# serverly limited.85+if pythonapi is None:86+ get_buffer = None87+else:80-def get_buffer(obj, writable=False):81- buf = Py_buffer()82- flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE83- PyObject_GetBuffer(py_object(obj), byref(buf), flags)84- try:85- buffer_type = c_char * buf.len86- return buffer_type.from_address(buf.buf)87- finally:88- PyBuffer_Release(byref(buf))88+ def get_buffer(obj, writable=False):89+ buf = Py_buffer()90+ flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE91+ PyObject_GetBuffer(py_object(obj), byref(buf), flags)92+ try:93+ buffer_type = c_char * buf.len94+ return buffer_type.from_address(buf.buf)95+ finally:96+ PyBuffer_Release(byref(buf))97 98 99 class _WindowsConsoleRawIOBase(io.RawIOBase):100 152 unmodified lines253 }254 255 256 def _get_windows_console_stream(f, encoding, errors):257+ if get_buffer is not None and \249- if encoding in ('utf-16-le', None) \258+ encoding in ('utf-16-le', None) \259 and errors in ('strict', None) and \260 hasattr(f, 'isatty') and f.isatty():261 func = _stream_factories.get(f.fileno())262 if func is not None:263 if not PY2:255- f = getattr(f, 'buffer')264+ f = getattr(f, 'buffer', None)265 if f is None:266 return None267 else:268 # If we are on Python 2 we need to set the stream that we5 unmodified linesmodified:click/core.py+72 added-22 removed
1+import errno2 import os3 import sys4 from contextlib import contextmanager5 from itertools import repeat18 unmodified lines24 SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'25 SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'26 27 28+def fast_exit(code):29+ """Exit without garbage collection, this speeds up exit by about 10ms for30+ things like bash completion.31+ """32+ sys.stdout.flush()33+ sys.stderr.flush()34+ os._exit(code)35+36+37 def _bashcomplete(cmd, prog_name, complete_var=None):38 """Internal handler for the bash completion support."""39 if complete_var is None:40 complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()2 unmodified lines43 return44 45 from ._bashcomplete import bashcomplete46 if bashcomplete(cmd, prog_name, complete_var, complete_instr):37- sys.exit(1)47+ fast_exit(1)48 49 50 def _check_multicommand(base_command, cmd_name, cmd, register=False):51 if not base_command.chain or not isinstance(cmd, MultiCommand):6 unmodified lines58 'that is in chain mode. This is not supported'59 raise RuntimeError('%s. Command "%s" is set to chain and "%s" was '60 'added as subcommand but it in itself is a '61 'multi command. ("%s" is a %s within a chained '52- '%s named "%s"). This restriction was supposed to '53- 'be lifted in 6.0 but the fix was flawed. This '54- 'will be fixed in Click 7.0' % (62+ '%s named "%s").' % (63 hint, base_command.name, cmd_name,64 cmd_name, cmd.__class__.__name__,65 base_command.__class__.__name__,66 base_command.name))311 unmodified lines378 379 @property380 def meta(self):381 """This is a dictionary which is shared with all the contexts374- that are nested. It exists so that click utiltiies can store some382+ that are nested. It exists so that click utilities can store some383 state here if they need to. It is however the responsibility of384 that code to manage this dictionary well.385 386 The keys are supposed to be unique dotted strings. For instance274 unmodified lines661 the program name is constructed by taking the file662 name from ``sys.argv[0]``.663 :param complete_var: the environment variable that controls the664 bash completion support. The default is657- ``"_<prog_name>_COMPLETE"`` with prog name in665+ ``"_<prog_name>_COMPLETE"`` with prog_name in666 uppercase.667 :param standalone_mode: the default behavior is to invoke the script668 in standalone mode. Click will then669 handle exceptions and convert them into6 unmodified lines676 :param extra: extra keyword arguments are forwarded to the context677 constructor. See :class:`Context` for more information.678 """679 # If we are in Python 3, we will verify that the environment is672- # sane at this point of reject further execution to avoid a680+ # sane at this point or reject further execution to avoid a681 # broken script.682 if not PY2:683 _verify_python3_env()684 else:27 unmodified lines712 if not standalone_mode:713 raise714 e.show()715 sys.exit(e.exit_code)716+ except IOError as e:717+ if e.errno == errno.EPIPE:718+ sys.exit(1)719+ else:720+ raise721 except Abort:722 if not standalone_mode:723 raise724 echo('Aborted!', file=sys.stderr)24 unmodified lines749 :param short_help: the short help to use for this command. This is750 shown on the command listing of the parent command.751 :param add_help_option: by default each command registers a ``--help``752 option. This can be disabled by this parameter.753+ :param hidden: hide this command from help outputs.754 """755 756 def __init__(self, name, context_settings=None, callback=None,757 params=None, help=None, epilog=None, short_help=None,744- options_metavar='[OPTIONS]', add_help_option=True):758+ options_metavar='[OPTIONS]', add_help_option=True,759+ hidden=False):760 BaseCommand.__init__(self, name, context_settings)761 #: the callback to execute when the command fires. This might be762 #: `None` in which case nothing happens.763 self.callback = callback7 unmodified lines771 if short_help is None and help:772 short_help = make_default_short_help(help)773 self.short_help = short_help774 self.add_help_option = add_help_option775+ self.hidden = hidden776 777 def get_usage(self, ctx):778 formatter = ctx.make_formatter()779 self.format_usage(ctx, formatter)45 unmodified lines825 826 def make_parser(self, ctx):827 """Creates the underlying option parser for this command."""828 parser = OptionParser(ctx)813- parser.allow_interspersed_args = ctx.allow_interspersed_args814- parser.ignore_unknown_options = ctx.ignore_unknown_options829 for param in self.get_params(ctx):830 param.add_to_parser(parser, ctx)831 return parser832 176 unmodified lines1009 cmd = self.get_command(ctx, subcommand)1010 # What is this, the tool lied about a command. Ignore it1011 if cmd is None:1012 continue1013+ if cmd.hidden:1014+ continue1015 1016 help = cmd.short_help or ''1017 rows.append((subcommand, help))1018 206 unmodified lines1225 return sorted(rv)1226 1227 1228 class Parameter(object):1213- """A parameter to a command comes in two versions: they are either1229+ r"""A parameter to a command comes in two versions: they are either1230 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently1231 not supported by design as some of the internals for parsing are1232 intentionally not finalized.1233 36 unmodified lines1270 param_type_name = 'parameter'1271 1272 def __init__(self, param_decls=None, type=None, required=False,1273 default=None, callback=None, nargs=None, metavar=None,1258- expose_value=True, is_eager=False, envvar=None):1274+ expose_value=True, is_eager=False, envvar=None,1275+ autocompletion=None):1276 self.name, self.opts, self.secondary_opts = \1277 self._parse_decls(param_decls or (), expose_value)1278 1279 self.type = convert_type(type, default)14 unmodified lines1294 self.default = default1295 self.is_eager = is_eager1296 self.metavar = metavar1297 self.envvar = envvar1298+ self.autocompletion = autocompletion1299 1300 @property1301 def human_readable_name(self):1302 """Returns the human readable name of this parameter. This is the22 unmodified lines1325 1326 def add_to_parser(self, parser, ctx):1327 pass1328 1329+1330 def consume_value(self, ctx, opts):1331 value = opts.get(self.name)1332 if value is None:1314- value = ctx.lookup_default(self.name)1315- if value is None:1333 value = self.value_from_envvar(ctx)1334+ if value is None:1335+ value = ctx.lookup_default(self.name)1336 return value1337 1338 def type_cast_value(self, ctx, value):1339 """Given a value this runs it properly through the type system.88 unmodified lines1428 1429 def get_usage_pieces(self, ctx):1430 return []1431 1432+ def get_error_hint(self, ctx):1433+ """Get a stringified version of the param for use in error messages to1434+ indicate which param caused the error.1435+ """1436+ hint_list = self.opts or [self.human_readable_name]1437+ return ' / '.join('"%s"' % x for x in hint_list)1438 1439+1440 class Option(Parameter):1441 """Options are usually optional values on the command line and1442 have some extra features that arguments don't have.1443 1444 All other parameters are passed onwards to the parameter constructor.1445 1446 :param show_default: controls if the default value should be shown on the1447 help page. Normally, defaults are not shown.1448+ :param show_envvar: controls if an environment variable should be shown on1449+ the help page. Normally, environment variables1450+ are not shown.1422- :param prompt: if set to `True` or a non empty string then the user will1423- be prompted for input if not set. If set to `True` the1424- prompt will be the option name capitalized.1451+ :param prompt: if set to `True` or a non empty string then the user will be1452+ prompted for input. If set to `True` the prompt will be the1453+ option name capitalized.1454 :param confirmation_prompt: if set then the value will need to be confirmed1455 if it was prompted for.1456 :param hide_input: if this is `True` then the input on the prompt will be1457 hidden from the user. This is useful for password12 unmodified lines1470 parameter will be pulled from an environment1471 variable in case a prefix is defined on the1472 context.1473 :param help: the help string.1474+ :param hidden: hide this option from help outputs.1475 """1476 param_type_name = 'option'1477 1478 def __init__(self, param_decls=None, show_default=False,1479 prompt=False, confirmation_prompt=False,1480 hide_input=False, is_flag=None, flag_value=None,1481 multiple=False, count=False, allow_from_autoenv=True,1452- type=None, help=None, **attrs):1482+ type=None, help=None, hidden=False, show_choices=True,1483+ show_envvar=False, **attrs):1484 default_is_missing = attrs.get('default', _missing) is _missing1485 Parameter.__init__(self, param_decls, type=type, **attrs)1486 1487 if prompt is True:4 unmodified lines1492 prompt_text = prompt1493 self.prompt = prompt_text1494 self.confirmation_prompt = confirmation_prompt1495 self.hide_input = hide_input1496+ self.hidden = hidden1497 1498 # Flags1499 if is_flag is None:1500 if flag_value is not None:24 unmodified lines1525 self.multiple = multiple1526 self.allow_from_autoenv = allow_from_autoenv1527 self.help = help1528 self.show_default = show_default1529+ self.show_choices = show_choices1530+ self.show_envvar = show_envvar1531 1532 # Sanity check for stuff we don't support1533 if __debug__:1534 if self.nargs < 0:40 unmodified lines1575 possible_names.append(split_opt(decl))1576 opts.append(decl)1577 1578 if name is None and possible_names:1545- possible_names.sort(key=lambda x: len(x[0]))1546- name = possible_names[-1][1].replace('-', '_').lower()1579+ possible_names.sort(key=lambda x: -len(x[0])) # group long options first1580+ name = possible_names[0][1].replace('-', '_').lower()1581 if not isidentifier(name):1582 name = None1583 1584 if name is None:37 unmodified lines1622 kwargs['action'] = action1623 parser.add_option(self.opts, **kwargs)1624 1625 def get_help_record(self, ctx):1626+ if self.hidden:1627+ return1628 any_prefix_is_slash = []1629 1630 def _write_opts(opts):1631 rv, any_slashes = join_options(opts)8 unmodified lines1640 rv.append(_write_opts(self.secondary_opts))1641 1642 help = self.help or ''1643 extra = []1644+ if self.show_envvar:1645+ envvar = self.envvar1646+ if envvar is None:1647+ if self.allow_from_autoenv and \1648+ ctx.auto_envvar_prefix is not None:1649+ envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1650+ if envvar is not None:1651+ extra.append('env var: %s' % (1652+ ', '.join('%s' % d for d in envvar)1653+ if isinstance(envvar, (list, tuple))1654+ else envvar, ))1655 if self.default is not None and self.show_default:1656 extra.append('default: %s' % (1657 ', '.join('%s' % d for d in self.default)1658 if isinstance(self.default, (list, tuple))30 unmodified lines1689 # differently.1690 if self.is_bool_flag:1691 return confirm(self.prompt, default)1692 1646- return prompt(self.prompt, default=default,1647- hide_input=self.hide_input,1693+ return prompt(self.prompt, default=default, type=self.type,1694+ hide_input=self.hide_input, show_choices=self.show_choices,1695 confirmation_prompt=self.confirmation_prompt,1696 value_proc=lambda x: self.process_value(ctx, x))1697 1698 def resolve_envvar_value(self, ctx):76 unmodified lines1775 1776 def get_usage_pieces(self, ctx):1777 return [self.make_metavar()]1778 1779+ def get_error_hint(self, ctx):1780+ return '"%s"' % self.make_metavar()1781+1782 def add_to_parser(self, parser, ctx):1783 parser.add_argument(dest=self.name, nargs=self.nargs,1784 obj=self)1785 3 unmodified linesmodified:click/decorators.py+15 added-8 removed
83 unmodified lines84 else:85 help = inspect.cleandoc(help)86 attrs['help'] = help87 _check_for_unicode_literals()88- return cls(name=name or f.__name__.lower(),88+ return cls(name=name or f.__name__.lower().replace('_', '-'),89 callback=f, params=params, **attrs)90 91 92 def command(name=None, cls=None, **attrs):93- """Creates a new :class:`Command` and uses the decorated function as93+ r"""Creates a new :class:`Command` and uses the decorated function as94 callback. This will also automatically attach all decorated95 :func:`option`\s and :func:`argument`\s as parameters to the command.96 97 The name of the command defaults to the name of the function. If you6 unmodified lines104 that can be invoked as a command line utility or be attached to a105 command :class:`Group`.106 107 :param name: the name of the command. This defaults to the function108- name.108+ name with underscores replaced by dashes.109 :param cls: the command class to instantiate. This defaults to110 :class:`Command`.111 """112 if cls is None:50 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 59 unmodified lines237 (``'%(prog)s, version %(version)s'``)238 :param others: everything else is forwarded to :func:`option`.239 """240 if version is None:241+ if hasattr(sys, '_getframe'):238- module = sys._getframe(1).f_globals.get('__name__')242+ module = sys._getframe(1).f_globals.get('__name__')243+ else:244+ module = ''245+246 def decorator(f):247 prog_name = attrs.pop('prog_name', None)248 message = attrs.pop('message', '%(prog)s, version %(version)s')249 62 unmodified linesmodified:click/exceptions.py+24 added-10 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 exception9 unmodified lines24 25 def format_message(self):26 return self.message27 22- def __unicode__(self):28+ def __str__(self):29 return self.message30 25- def __str__(self):26- return self.message.encode('utf-8')31+ if PY2:32+ __unicode__ = __str__33 34+ def __str__(self):35+ return self.message.encode('utf-8')36+37 def show(self, file=None):38 if file is None:39 file = get_text_stderr()40 echo('Error: %s' % self.format_message(), file=file)11 unmodified lines52 53 def __init__(self, message, ctx=None):54 ClickException.__init__(self, message)55 self.ctx = ctx56+ self.cmd = self.ctx and self.ctx.command or None57 58 def show(self, file=None):59 if file is None:60 file = get_text_stderr()61 color = None62+ hint = ''63+ if (self.cmd is not None and64+ self.cmd.get_help_option(self.ctx) is not None):65+ hint = ('Try "%s %s" for help.\n'66+ % (self.ctx.command_path, self.ctx.help_option_names[0]))67 if self.ctx is not None:68 color = self.ctx.color54- echo(self.ctx.get_usage() + '\n', file=file, color=color)69+ echo(self.ctx.get_usage() + '\n%s' % hint, file=file, color=color)70 echo('Error: %s' % self.format_message(), file=file, color=color)71 72 73 class BadParameter(UsageError):23 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:86- 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.message89- if isinstance(param_hint, (tuple, list)):90- 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:115- 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 = None118- if isinstance(param_hint, (tuple, list)):119- 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/globals.py+1 added-1 removed
7 unmodified lines8 """Returns the current click context. This can be used as a way to9 access the current context object from anywhere. This is a more implicit10 alternative to the :func:`pass_context` decorator. This function is11 primarily useful for helpers such as :func:`echo` which might be12- interested in changing it's behavior based on the current context.12+ interested in changing its behavior based on the current context.13 14 To push the current context, :meth:`Context.scope` can be used.15 16 .. versionadded:: 5.032 unmodified linesmodified:click/termui.py+78 added-21 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 echo10 from .exceptions import Abort, UsageError9-from .types import convert_type11+from .types import convert_type, Choice12 from .globals import resolve_color_default13 14 15 # 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):42 import getpass43 return getpass.getpass(prompt)44 45 27-def _build_prompt(text, suffix, show_default=False, default=None):46+def _build_prompt(text, suffix, show_default=False, default=None, show_choices=True, type=None):47 prompt = text48+ if type is not None and show_choices and isinstance(type, Choice):49+ prompt += ' (' + ", ".join(map(str, type.choices)) + ')'50 if default is not None and show_default:51 prompt = '%s [%s]' % (prompt, default)52 return prompt + suffix53 54 34-def prompt(text, default=None, hide_input=False,35- confirmation_prompt=False, type=None,36- value_proc=None, prompt_suffix=': ',37- show_default=True, err=False):55+def prompt(text, default=None, hide_input=False, confirmation_prompt=False,56+ type=None, value_proc=None, prompt_suffix=': ', show_default=True,57+ err=False, show_choices=True):58 """Prompts a user for input. This is a convenience function that can59 be used to prompt a user for input later.60 61 If the user aborts the input by sending a interrupt signal, this62 function will catch it and raise a :exc:`Abort` exception.63 64+ .. versionadded:: 7.065+ Added the show_choices parameter.66+67 .. versionadded:: 6.068 Added unicode support for cmd.exe on Windows.69 70 .. versionadded:: 4.012 unmodified lines83 :param prompt_suffix: a suffix that should be added to the prompt.84 :param show_default: shows or hides the default value in the prompt.85 :param err: if set to true the file defaults to ``stderr`` instead of86 ``stdout``, the same as with echo.87+ :param show_choices: Show or hide choices if the passed type is a Choice.88+ For example if type is a Choice of either day or week,89+ show_choices is true and text is "Group by" then the90+ prompt will be "Group by (day, week): ".91 """92 result = None93 94 def prompt_func(text):13 unmodified lines108 109 if value_proc is None:110 value_proc = convert_type(type, default)111 85- prompt = _build_prompt(text, prompt_suffix, show_default, default)112+ prompt = _build_prompt(text, prompt_suffix, show_default, default, show_choices, type)113 114 while 1:115 while 1:116 value = prompt_func(prompt)75 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:170- 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 198-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 205- :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)210- if not isinstance(text, string_types):211- 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 pager213- 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:372- bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30))373- 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:377- bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40))378- 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:21 unmodified lines459 """460 return strip_ansi(text)461 462 408-def secho(text, file=None, nl=True, err=False, color=None, **styles):463+def secho(message=None, file=None, nl=True, err=False, color=None, **styles):464 """This function combines :func:`echo` and :func:`style` into one465 call. As such the following two calls are the same::466 467 click.secho('Hello World!', fg='green')3 unmodified lines471 depending on which one they go with.472 473 .. versionadded:: 2.0474 """475+ if message is not None:476+ message = style(message, **styles)420- return echo(style(text, **styles), file=file, nl=nl, err=err, color=color)477+ return echo(message, file=file, nl=nl, err=err, color=color)478 479 480 def edit(text=None, editor=None, env=None, require_save=True,481 extension='.txt', filename=None):115 unmodified linesmodified:click/testing.py+77 added-25 removed
1 unmodified line2 import sys3 import shutil4 import tempfile5 import contextlib6+import shlex7 7-from ._compat import iteritems, PY28+from ._compat import iteritems, PY2, string_types9 10 11 # If someone wants to vendor click, we want to ensure the12 # correct package is discovered. Ideally we could use a59 unmodified lines72 73 class Result(object):74 """Holds the captured result of an invoked CLI script."""75 75- def __init__(self, runner, output_bytes, exit_code, exception,76- 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 = runner79- #: The output as bytes.80- 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):90- """The output as unicode string."""91- 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):95- 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 116- 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:166- 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)174- 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 '')14 unmodified lines231 sys.stdout.flush()232 return char233 234 default_color = color235+236 def should_strip_ansi(stream=None, color=None):237 if color is None:238 return not default_color239 return not color9 unmodified lines249 250 old_env = {}251 try:252 for key, value in iteritems(env):216- old_env[key] = os.environ.get(value)253+ old_env[key] = os.environ.get(key)254 if value is None:255 try:256 del os.environ[key]257 except Exception:258 pass259 else:260 os.environ[key] = value224- 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,244- 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.10 unmodified lines296 .. versionadded:: 4.0297 The ``color`` parameter was added.298 299 :param cli: the command to invoke263- :param args: the arguments to invoke300+ :param args: the arguments to invoke. It may be given as an iterable301+ or a string. When given as string it will be interpreted302+ as a Unix shell command. More details at303+ :func:`shlex.split`.304 :param input: the input data for `sys.stdin`.305 :param env: the environment overrides.306 :param catch_exceptions: Whether to catch any other exceptions than307 ``SystemExit``.1 unmodified line309 :param color: whether the output should contain color codes. The310 application can still override this explicitly.311 """312 exc_info = None273- 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:278- cli.main(args=args or (),279- prog_name=self.get_default_prog_name(cli), **extra)280- except SystemExit as e:281- if e.code != 0:282- exception = e321+ 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()285-329 exit_code = e.code330+ if exit_code is None:331+ exit_code = 0332+333+ if exit_code != 0:334+ exception = e335+336 if not isinstance(exit_code, int):337 sys.stdout.write(str(exit_code))338 sys.stdout.write('\n')339 exit_code = 1340+341 except Exception as e:342 if not catch_exceptions:343 raise344 exception = e295- exit_code = -1345+ exit_code = 1346 exc_info = sys.exc_info()347 finally:348 sys.stdout.flush()299- output = out.getvalue()349+ stdout = outstreams[0].getvalue()350+ stderr = outstreams[1] and outstreams[1].getvalue()351 352 return Result(runner=self,302- 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+87 added-43 removed
127 unmodified lines128 class Choice(ParamType):129 """The choice type allows a value to be checked against a fixed set of130 supported values. All of these values have to be strings.131 132+ 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 name = 'choice'138 77 unmodified lines216 def __repr__(self):217 return 'IntRange(%r, %r)' % (self.min, self.max)218 219 220+class FloatParamType(ParamType):221+ name = 'float'222+223+ def convert(self, value, param, ctx):224+ try:225+ return float(value)226+ except (UnicodeError, ValueError):227+ self.fail('%s is not a valid floating point value' %228+ value, param, ctx)229+230+ def __repr__(self):231+ return 'FLOAT'232+233+234+class FloatRange(FloatParamType):235+ """A parameter that works similar to :data:`click.FLOAT` but restricts236+ the value to fit into a range. The default behavior is to fail if the237+ value falls outside the range, but it can also be silently clamped238+ between the two edges.239+240+ See :ref:`ranges` for an example.241+ """242+ name = 'float range'243+244+ def __init__(self, min=None, max=None, clamp=False):245+ self.min = min246+ self.max = max247+ self.clamp = clamp248+249+ def convert(self, value, param, ctx):250+ rv = FloatParamType.convert(self, value, param, ctx)251+ if self.clamp:252+ if self.min is not None and rv < self.min:253+ return self.min254+ if self.max is not None and rv > self.max:255+ return self.max256+ if self.min is not None and rv < self.min or \257+ self.max is not None and rv > self.max:258+ if self.min is None:259+ self.fail('%s is bigger than the maximum valid value '260+ '%s.' % (rv, self.max), param, ctx)261+ elif self.max is None:262+ self.fail('%s is smaller than the minimum valid value '263+ '%s.' % (rv, self.min), param, ctx)264+ else:265+ self.fail('%s is not in the valid range of %s to %s.'266+ % (rv, self.min, self.max), param, ctx)267+ return rv268+269+ def __repr__(self):270+ return 'FloatRange(%r, %r)' % (self.min, self.max)271+272+273 class BoolParamType(ParamType):274 name = 'boolean'275 276 def convert(self, value, param, ctx):277 if isinstance(value, bool):278 return bool(value)279 value = value.lower()224- if value in ('true', '1', 'yes', 'y'):280+ if value in ('true', 't', '1', 'yes', 'y'):281 return True226- elif value in ('false', '0', 'no', 'n'):282+ elif value in ('false', 'f', '0', 'no', 'n'):283 return False284 self.fail('%s is not a valid boolean' % value, param, ctx)285 286 def __repr__(self):287 return 'BOOL'288 289 234-class FloatParamType(ParamType):235- name = 'float'236-237- def convert(self, value, param, ctx):238- try:239- return float(value)240- except (UnicodeError, ValueError):241- self.fail('%s is not a valid floating point value' %242- value, param, ctx)243-244- def __repr__(self):245- return 'FLOAT'246-247-290 class UUIDParameterType(ParamType):291 name = 'uuid'292 293 def convert(self, value, param, ctx):105 unmodified lines399 :param writable: if true, a writable check is performed.400 :param readable: if true, a readable check is performed.401 :param resolve_path: if this is true, then the path is fully resolved402 before the value is passed onwards. This means361- that it's absolute and symlinks are resolved.403+ that it's absolute and symlinks are resolved. It404+ will not expand a tilde-prefix, as this is405+ supposed to be done by the shell only.406 :param allow_dash: If this is set to `True`, a single dash to indicate407 standard streams is permitted.364- :param type: optionally a string type that should be used to365- represent the path. The default is `None` which366- means the return value will be either bytes or367- unicode depending on what makes most sense given the368- input data Click deals with.408+ :param path_type: optionally a string type that should be used to409+ represent the path. The default is `None` which410+ means the return value will be either bytes or411+ unicode depending on what makes most sense given the412+ input data Click deals with.413 """414 envvar_list_splitter = os.path.pathsep415 416 def __init__(self, exists=False, file_okay=True, dir_okay=True,10 unmodified lines427 428 if self.file_okay and not self.dir_okay:429 self.name = 'file'430 self.path_type = 'File'387- if self.dir_okay and not self.file_okay:431+ elif self.dir_okay and not self.file_okay:432 self.name = 'directory'433 self.path_type = 'Directory'434 else:435 self.name = 'path'25 unmodified lines461 self.path_type,462 filename_to_ui(value)463 ), param, ctx)464 421- if not self.file_okay and stat.S_ISREG(st.st_mode):422- self.fail('%s "%s" is a file.' % (423- self.path_type,424- filename_to_ui(value)425- ), param, ctx)426- if not self.dir_okay and stat.S_ISDIR(st.st_mode):427- self.fail('%s "%s" is a directory.' % (428- self.path_type,429- filename_to_ui(value)430- ), param, ctx)431- if self.writable and not os.access(value, os.W_OK):432- self.fail('%s "%s" is not writable.' % (433- self.path_type,434- filename_to_ui(value)435- ), param, ctx)436- if self.readable and not os.access(value, os.R_OK):437- self.fail('%s "%s" is not readable.' % (438- self.path_type,439- filename_to_ui(value)440- ), param, ctx)465+ if not self.file_okay and stat.S_ISREG(st.st_mode):466+ self.fail('%s "%s" is a file.' % (467+ self.path_type,468+ filename_to_ui(value)469+ ), param, ctx)470+ if not self.dir_okay and stat.S_ISDIR(st.st_mode):471+ self.fail('%s "%s" is a directory.' % (472+ self.path_type,473+ filename_to_ui(value)474+ ), param, ctx)475+ if self.writable and not os.access(value, os.W_OK):476+ self.fail('%s "%s" is not writable.' % (477+ self.path_type,478+ filename_to_ui(value)479+ ), param, ctx)480+ if self.readable and not os.access(value, os.R_OK):481+ self.fail('%s "%s" is not readable.' % (482+ self.path_type,483+ filename_to_ui(value)484+ ), param, ctx)485 486 return self.coerce_path_result(rv)487 488 106 unmodified linesmodified:click/utils.py+3 added-2 removed
41 unmodified lines42 return text_type(value)43 44 45 def make_default_short_help(help, max_length=45):46+ """Return a condensed version of help string."""47 words = help.split()48 total_length = 049 result = []50 done = False120 unmodified lines171 matter how badly configured the system is.172 173 Primarily it means that you can print binary data as well as Unicode174 data on both 2.x and 3.x to the given file in the most appropriate way174- possible. This is a very carefree function as in that it will try its175+ possible. This is a very carefree function in that it will try its176 best to not fail. As of Click 6.0 this includes support for unicode177 output on the Windows console.178 179 In addition to that, if `colorama`_ is installed, the echo function will3 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 186- .. _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+3 added-3 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>11- <li><a href="http://github.com/mitsuhiko/click">click @ github</a></li>12- <li><a href="http://github.com/mitsuhiko/click/issues">Issue Tracker</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+5 added-5 removed
275 unmodified lines276 command will abort with an error that there are leftover arguments.277 If you go with this solution, the extra arguments will be collected in278 :attr:`Context.args`.279 2. You can attach a :func:`argument` with ``nargs`` set to `-1` which280- will eat up all leftover arguments. In this case it's recommeded to280+ will eat up all leftover arguments. In this case it's recommended to281 set the `type` to :data:`UNPROCESSED` to avoid any string processing282 on those arguments as otherwise they are forced into unicode strings283 automatically which is often not what you want.284 9 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 16 unmodified lines320 So for instance if ``--foo=bar`` or ``--foo bar`` are passed they321 generally end up like that. Note that because the parser cannot know322 if an option will accept an argument or not, the ``bar`` part might be323 handled as an argument.324-* Unknown short options might be partially handled and reassmebled if324+* Unknown short options might be partially handled and reassembled if325 necessary. For instance in the above example there is an option326 called ``-v`` which enables verbose mode. If the command would be327 ignored with ``-va`` then the ``-v`` part would be handled by Click328 (as it is known) and ``-a`` would end up in the leftover parameters16 unmodified lines345 346 .. versionadded:: 5.0347 348 Starting with Click 5.0 it is possible to access the current context from349-anywhere within the same through through the use of the349+anywhere within the same thread through the use of the350 :func:`get_current_context` function which returns it. This is primarily351 useful for accessing the context bound object as well as some flags that352 are stored on it to customize the runtime behavior. For instance the353 :func:`echo` function does this to infer the default value of the `color`26 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+44 added-7 removed
11 unmodified lines12 13 Bash completion is only available if a script has been installed properly,14 and not executed through the ``python`` command. For information about15 how to do that, see :ref:`setuptools-integration`. Also, Click currently16-only supports completion for Bash.16+only supports completion for Bash. Zsh support is available through Zsh's17+bash completion compatibility mode.18 18-Currently, Bash completion is an internal feature that is not customizable.19-This might be relaxed in future versions.20-19 What it Completes20 -----------------21 24-Generally, the Bash completion support will complete subcommands and25-parameters. Subcommands are always listed whereas parameters only if at22+Generally, the Bash completion support will complete subcommands, options23+and any option or argument values where the type is click.Choice.24+Subcommands and choices are always listed whereas options only if at25 least a dash has been provided. Example::26 27 $ repo <TAB><TAB>28 clone commit copy delete setuser29 $ repo clone -<TAB><TAB>30 --deep --help --rev --shallow -r31 32+Additionally, custom suggestions can be provided for arguments and options with33+the ``autocompletion`` parameter. ``autocompletion`` should a callback function34+that returns a list of strings. This is useful when the suggestions need to be35+dynamically generated at bash completion time. The callback function will be36+passed 3 keyword arguments:37+38+- ``ctx`` - The current click context.39+- ``args`` - The list of arguments passed in.40+- ``incomplete`` - The partial word that is being completed, as a string. May41+ be an empty string ``''`` if no characters have been entered yet.42+43+Here is an example of using a callback function to generate dynamic suggestions:44+45+.. click:example::46+47+ import os48+49+ def get_env_vars(ctx, args, incomplete):50+ return os.environ.keys()51+52+ @click.command()53+ @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)54+ def cmd1(envvar):55+ click.echo('Environment variable: %s' % envvar)56+ click.echo('Value: %s' % os.environ[envvar])57+58+59 Activation60 ----------61 62 In order to activate Bash completion, you need to inform Bash that4 unmodified lines67 with dashes replaced by underscores.68 69 If your tool is called ``foo-bar``, then the magic variable is called70 ``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will45-spit out the activation script which can be trivally activated.71+spit out the activation script which can be trivially activated.72 73 For instance, to enable Bash completion for your ``foo-bar`` script, this74 is what you would need to put into your ``.bashrc``::75 16 unmodified lines92 93 And then you would put this into your bashrc instead::94 95 . /path/to/foo-bar-complete.sh96+97+Zsh Compatibility98+----------------99+100+To enable Bash completion in Zsh, add the following lines to your .zshrc:101+102+ autoload bashcompinit103+ bashcompinit104+105+See https://github.com/pallets/click/issues/323 for more information on106+this issue.modified: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/commands.rst+3 added-3 removed
27 unmodified lines28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))29 30 @cli.command()31 def sync():32- click.echo('Synching')32+ click.echo('Syncing')33 34 Here is what this looks like:35 36 .. click:run::379 unmodified lines416 :func:`open_file`.417 418 For a more complex example that also improves upon handling of the419 pipelines have a look at the `imagepipe multi command chaining demo420-<https://github.com/mitsuhiko/click/tree/master/examples/imagepipe>`__ in420+<https://github.com/pallets/click/tree/master/examples/imagepipe>`__ in421 the Click repository. It implements a pipeline based image editing tool422 that has a nice internal structure for the pipelines.423 424 11 unmodified lines436 you're not satisfied with the defaults.437 438 The default map can be nested arbitrarily for each subcommand and439 provided when the script is invoked. Alternatively, it can also be440-overriden at any point by commands. For instance, a top-level command could440+overridden at any point by commands. For instance, a top-level command could441 load the defaults from a configuration file.442 443 Example usage:444 114 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+17 added-2 removed
14 unmodified lines15 16 The most basic option is a value option. These options accept one17 argument which is a value. If no type is provided, the type of the default18 value is used. If no default value is provided, the type is assumed to be19-:data:`STRING`. By default, the name of the parameter is the first long20-option defined; otherwise the first short one is used.19+:data:`STRING`. Unless a name is explicitly specified, the name of the20+parameter is the first long option defined; otherwise the first short one is21+used.22 23 .. click:example::24 25 @click.command()26 @click.option('--n', default=1)27 def dots(n):28 click.echo('.' * n)29 30+.. click:example::31+32+ # How to use a Python reserved word such as `from` as a parameter33+ @click.command()34+ @click.option('--from', '-f', '_from')35+ @click.option('--to', '-t')36+ def reserved_param_name(_from, to):37+ click.echo('from %s to %s' % (_from, to))38+39 And on the command line:40 41 .. click:run::42 248 unmodified lines291 invoke(digest, args=['--hash-type=foo'])292 println()293 invoke(digest, args=['--help'])294 295+.. note::296+297+ You should only pass the choices as list or tuple. Other iterables (like298+ generators) may lead to surprising results.299+300 .. _option-prompting:301 302 Prompting303 ---------407 unmodified linesmodified:docs/parameters.rst+5 added-2 removed
45 unmodified lines46 A parameter that only accepts floating point values.47 48 ``bool`` / :data:`click.BOOL`:49 A parameter that accepts boolean values. This is automatically used50- for boolean flags. If used with string values ``1``, ``yes``, ``y``51- and ``true`` convert to `True` and ``0``, ``no``, ``n`` and ``false``50+ for boolean flags. If used with string values ``1``, ``yes``, ``y``, ``t``51+ and ``true`` convert to `True` and ``0``, ``no``, ``n``, ``f`` and ``false``52 convert to `False`.53 54 :data:`click.UUID`:55 A parameter that accepts UUID values. This is not automatically10 unmodified lines66 67 .. autoclass:: IntRange68 :noindex:69 70+.. autoclass:: FloatRange71+ :noindex:72+73 Custom parameter types can be implemented by subclassing74 :class:`click.ParamType`. For simple cases, passing a Python function that75 fails with a `ValueError` is also supported, though discouraged.76 47 unmodified linesmodified:docs/python3.rst+2 added-2 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 is to use Python 2 for Click11+At the moment, it is strongly recommended to use Python 2 for Click12 utilities unless Python 3 is a hard requirement.13 14 .. _python3-limitations:15 168 unmodified linesmodified:docs/quickstart.rst+11 added-11 removed
49 unmodified lines50 ``pip`` first. For more information about this, see `installing pip`_.51 Once you have it installed, run the ``pip`` command from above, but without52 the `sudo` prefix.53 54-.. _installing pip: http://pip.readthedocs.org/en/latest/installing.html54+.. _installing pip: https://pip.readthedocs.io/en/latest/installing.html55 56 Once you have virtualenv installed, just fire up a shell and create57 your own environment. I usually create a project folder and a `venv`58 folder within::19 unmodified lines78 And if you want to go back to the real world, use the following command::79 80 $ deactivate81 82-After doing this, the prompt of your shell should be as familar as before.82+After doing this, the prompt of your shell should be as familiar as before.83 84 Now, let's move on. Enter the following command to get Click activated in your85 virtualenv::86 14 unmodified lines101 Examples of Click applications can be found in the documentation as well102 as in the GitHub repository together with readme files:103 104 * ``inout``: `File input and output105- <https://github.com/mitsuhiko/click/tree/master/examples/inout>`_105+ <https://github.com/pallets/click/tree/master/examples/inout>`_106 * ``naval``: `Port of docopt naval example107- <https://github.com/mitsuhiko/click/tree/master/examples/naval>`_107+ <https://github.com/pallets/click/tree/master/examples/naval>`_108 * ``aliases``: `Command alias example109- <https://github.com/mitsuhiko/click/tree/master/examples/aliases>`_109+ <https://github.com/pallets/click/tree/master/examples/aliases>`_110 * ``repo``: `Git-/Mercurial-like command line interface111- <https://github.com/mitsuhiko/click/tree/master/examples/repo>`_111+ <https://github.com/pallets/click/tree/master/examples/repo>`_112 * ``complex``: `Complex example with plugin loading113- <https://github.com/mitsuhiko/click/tree/master/examples/complex>`_113+ <https://github.com/pallets/click/tree/master/examples/complex>`_114 * ``validation``: `Custom parameter validation example115- <https://github.com/mitsuhiko/click/tree/master/examples/validation>`_115+ <https://github.com/pallets/click/tree/master/examples/validation>`_116 * ``colors``: `Colorama ANSI color support117- <https://github.com/mitsuhiko/click/tree/master/examples/colors>`_117+ <https://github.com/pallets/click/tree/master/examples/colors>`_118 * ``termui``: `Terminal UI functions demo119- <https://github.com/mitsuhiko/click/tree/master/examples/termui>`_119+ <https://github.com/pallets/click/tree/master/examples/termui>`_120 * ``imagepipe``: `Multi command chaining demo121- <https://github.com/mitsuhiko/click/tree/master/examples/imagepipe>`_121+ <https://github.com/pallets/click/tree/master/examples/imagepipe>`_122 123 Basic Concepts124 --------------125 149 unmodified linesmodified:docs/upgrading.rst+1 added-1 removed
42 unmodified lines43 44 Multicommand Chaining API45 `````````````````````````46 47-Click 3 introduced multicommand chaning. This required a change in how47+Click 3 introduced multicommand chaining. This required a change in how48 Click internally dispatches. Unfortunately this change was not correctly49 implemented and it appeared that it was possible to provide an API that50 can inform the super command about all the subcommands that will be51 invoked.49 unmodified linesmodified:docs/utils.rst+13 added-2 removed
93 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.0103 unmodified lines236 237 .. versionadded:: 2.0238 239 Click supports launching applications through :func:`launch`. This can be229-used to open the default application assocated with a URL or filetype.240+used to open the default application associated with a URL or filetype.241 This can be used to launch web browsers or picture viewers, for instance.242 In addition to this, it can also launch the file manager and automatically243 select the provided file.244 165 unmodified linesadded:examples/bashcompletion/bashcompletion.py+41 added
1+import click2+import os3+4+5+@click.group()6+def cli():7+ pass8+9+10+def get_env_vars(ctx, args, incomplete):11+ for key in os.environ.keys():12+ if incomplete in key:13+ yield key14+15+16+@cli.command()17+@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)18+def cmd1(envvar):19+ click.echo('Environment variable: %s' % envvar)20+ click.echo('Value: %s' % os.environ[envvar])21+22+23+@click.group()24+def group():25+ pass26+27+28+def list_users(ctx, args, incomplete):29+ # Here you can generate completions dynamically30+ users = ['bob', 'alice']31+ for user in users:32+ if user.startswith(incomplete):33+ yield user34+35+36+@group.command()37+@click.argument("user", type=click.STRING, autocompletion=list_users)38+def subcmd(user):39+ click.echo('Chosen user is %s' % user)40+41+cli.add_command(group)added:examples/bashcompletion/README+12 added
1+$ bashcompletion2+3+ bashcompletion is a simple example of an application that4+ tries to autocomplete commands, arguments and options.5+6+ This example requires Click 2.0 or higher.7+8+Usage:9+10+ $ pip install --editable .11+ $ eval "$(_BASHCOMPLETION_COMPLETE=source bashcompletion)"12+ $ bashcompletion --helpadded:examples/bashcompletion/setup.py+15 added
1+from setuptools import setup2+3+setup(4+ name='click-example-bashcompletion',5+ version='1.0',6+ py_modules=['bashcompletion'],7+ include_package_data=True,8+ install_requires=[9+ 'click',10+ ],11+ entry_points='''12+ [console_scripts]13+ bashcompletion=bashcompletion:cli14+ ''',15+)modified: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:examples/validation/validation.py+1 added-1 removed
1 import click2 try:3- from urllib import parser as urlparse3+ from urllib import parse as urlparse4 except ImportError:5 import urlparse6 7 37 unmodified linesmodified:tests/test_arguments.py+13 added-2 removed
104 unmodified lines105 assert result.output == 'Hey!'106 assert result.exit_code == 0107 108 109+def test_path_args(runner):110+ @click.command()111+ @click.argument('input', type=click.Path(dir_okay=False, allow_dash=True))112+ def foo(input):113+ click.echo(input)114+115+ result = runner.invoke(foo, ['-'])116+ assert result.output == '-\n'117+ assert result.exit_code == 0118+119+120 def test_file_atomics(runner):121 @click.command()122 @click.argument('output', type=click.File('wb', atomic=True))123 def inout(output):63 unmodified lines187 click.echo('arg:' + '|'.join(arg))188 189 result = runner.invoke(cmd2, [])190 assert result.exit_code == 2180- 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 == 2191- 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 linesadded:tests/test_bashcomplete.py+286 added
1+# -*- coding: utf-8 -*-2+3+import click4+from click._bashcomplete import get_choices5+6+7+def test_single_command():8+ @click.command()9+ @click.option('--local-opt')10+ def cli(local_opt):11+ pass12+13+ assert list(get_choices(cli, 'lol', [], '-')) == ['--local-opt']14+ assert list(get_choices(cli, 'lol', [], '')) == []15+16+17+def test_boolean_flag():18+ @click.command()19+ @click.option('--shout/--no-shout', default=False)20+ def cli(local_opt):21+ pass22+23+ assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']24+25+26+def test_multi_value_option():27+ @click.group()28+ @click.option('--pos', nargs=2, type=float)29+ def cli(local_opt):30+ pass31+32+ @cli.command()33+ @click.option('--local-opt')34+ def sub(local_opt):35+ pass36+37+ assert list(get_choices(cli, 'lol', [], '-')) == ['--pos']38+ assert list(get_choices(cli, 'lol', ['--pos'], '')) == []39+ assert list(get_choices(cli, 'lol', ['--pos', '1.0'], '')) == []40+ assert list(get_choices(cli, 'lol', ['--pos', '1.0', '1.0'], '')) == ['sub']41+42+43+def test_multi_option():44+ @click.command()45+ @click.option('--message', '-m', multiple=True)46+ def cli(local_opt):47+ pass48+49+ assert list(get_choices(cli, 'lol', [], '-')) == ['--message', '-m']50+ assert list(get_choices(cli, 'lol', ['-m'], '')) == []51+52+53+def test_small_chain():54+ @click.group()55+ @click.option('--global-opt')56+ def cli(global_opt):57+ pass58+59+ @cli.command()60+ @click.option('--local-opt')61+ def sub(local_opt):62+ pass63+64+ assert list(get_choices(cli, 'lol', [], '')) == ['sub']65+ assert list(get_choices(cli, 'lol', [], '-')) == ['--global-opt']66+ assert list(get_choices(cli, 'lol', ['sub'], '')) == []67+ assert list(get_choices(cli, 'lol', ['sub'], '-')) == ['--local-opt']68+69+70+def test_long_chain():71+ @click.group('cli')72+ @click.option('--cli-opt')73+ def cli(cli_opt):74+ pass75+76+ @cli.group('asub')77+ @click.option('--asub-opt')78+ def asub(asub_opt):79+ pass80+81+ @asub.group('bsub')82+ @click.option('--bsub-opt')83+ def bsub(bsub_opt):84+ pass85+86+ COLORS = ['red', 'green', 'blue']87+ def get_colors(ctx, args, incomplete):88+ for c in COLORS:89+ if c.startswith(incomplete):90+ yield c91+92+ def search_colors(ctx, args, incomplete):93+ for c in COLORS:94+ if incomplete in c:95+ yield c96+97+ CSUB_OPT_CHOICES = ['foo', 'bar']98+ CSUB_CHOICES = ['bar', 'baz']99+ @bsub.command('csub')100+ @click.option('--csub-opt', type=click.Choice(CSUB_OPT_CHOICES))101+ @click.option('--csub', type=click.Choice(CSUB_CHOICES))102+ @click.option('--search-color', autocompletion=search_colors)103+ @click.argument('color', autocompletion=get_colors)104+ def csub(csub_opt, color):105+ pass106+107+ assert list(get_choices(cli, 'lol', [], '-')) == ['--cli-opt']108+ assert list(get_choices(cli, 'lol', [], '')) == ['asub']109+ assert list(get_choices(cli, 'lol', ['asub'], '-')) == ['--asub-opt']110+ assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub']111+ assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '-')) == ['--bsub-opt']112+ assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '')) == ['csub']113+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '-')) == ['--csub-opt', '--csub', '--search-color']114+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], '')) == CSUB_OPT_CHOICES115+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '--csub')) == ['--csub-opt', '--csub']116+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub'], '')) == CSUB_CHOICES117+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], 'f')) == ['foo']118+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '')) == COLORS119+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], 'b')) == ['blue']120+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--search-color'], 'een')) == ['green']121+122+123+def test_chaining():124+ @click.group('cli', chain=True)125+ @click.option('--cli-opt')126+ def cli(cli_opt):127+ pass128+129+ @cli.command('asub')130+ @click.option('--asub-opt')131+ def asub(asub_opt):132+ pass133+134+ @cli.command('bsub')135+ @click.option('--bsub-opt')136+ @click.argument('arg', type=click.Choice(['arg1', 'arg2']), required=True)137+ def bsub(bsub_opt, arg):138+ pass139+140+ @cli.command('csub')141+ @click.option('--csub-opt')142+ @click.argument('arg', type=click.Choice(['carg1', 'carg2']), required=False)143+ def csub(csub_opt, arg):144+ pass145+146+ assert list(get_choices(cli, 'lol', [], '-')) == ['--cli-opt']147+ assert list(get_choices(cli, 'lol', [], '')) == ['asub', 'bsub', 'csub']148+ assert list(get_choices(cli, 'lol', ['asub'], '-')) == ['--asub-opt']149+ assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub', 'csub']150+ assert list(get_choices(cli, 'lol', ['bsub'], '')) == ['arg1', 'arg2']151+ assert list(get_choices(cli, 'lol', ['asub', '--asub-opt'], '')) == []152+ assert list(get_choices(cli, 'lol', ['asub', '--asub-opt', '5', 'bsub'], '-')) == ['--bsub-opt']153+ assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '-')) == ['--bsub-opt']154+ assert list(get_choices(cli, 'lol', ['asub', 'csub'], '')) == ['carg1', 'carg2', 'bsub']155+ assert list(get_choices(cli, 'lol', ['asub', 'csub'], '-')) == ['--csub-opt']156+157+158+def test_argument_choice():159+ @click.command()160+ @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))161+ @click.argument('arg2', required=False, type=click.Choice(['arg21', 'arg22']))162+ @click.argument('arg3', required=False, type=click.Choice(['arg', 'argument']))163+ def cli():164+ pass165+166+ assert list(get_choices(cli, 'lol', [], '')) == ['arg11', 'arg12']167+ assert list(get_choices(cli, 'lol', [], 'arg')) == ['arg11', 'arg12']168+ assert list(get_choices(cli, 'lol', ['arg11'], '')) == ['arg21', 'arg22']169+ assert list(get_choices(cli, 'lol', ['arg12', 'arg21'], '')) == ['arg', 'argument']170+ assert list(get_choices(cli, 'lol', ['arg12', 'arg21'], 'argu')) == ['argument']171+172+173+def test_option_choice():174+ @click.command()175+ @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))176+ @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))177+ @click.option('--opt3', type=click.Choice(['opt', 'option']))178+ def cli():179+ pass180+181+ assert list(get_choices(cli, 'lol', [], '-')) == ['--opt1', '--opt2', '--opt3']182+ assert list(get_choices(cli, 'lol', [], '--opt')) == ['--opt1', '--opt2', '--opt3']183+ assert list(get_choices(cli, 'lol', [], '--opt1=')) == ['opt11', 'opt12']184+ assert list(get_choices(cli, 'lol', [], '--opt2=')) == ['opt21', 'opt22']185+ assert list(get_choices(cli, 'lol', ['--opt2'], '=')) == ['opt21', 'opt22']186+ assert list(get_choices(cli, 'lol', ['--opt2', '='], 'opt')) == ['opt21', 'opt22']187+ assert list(get_choices(cli, 'lol', ['--opt1'], '')) == ['opt11', 'opt12']188+ assert list(get_choices(cli, 'lol', ['--opt2'], '')) == ['opt21', 'opt22']189+ assert list(get_choices(cli, 'lol', ['--opt1', 'opt11', '--opt2'], '')) == ['opt21', 'opt22']190+ assert list(get_choices(cli, 'lol', ['--opt2', 'opt21'], '-')) == ['--opt1', '--opt3']191+ assert list(get_choices(cli, 'lol', ['--opt1', 'opt11'], '-')) == ['--opt2', '--opt3']192+ assert list(get_choices(cli, 'lol', ['--opt1'], 'opt')) == ['opt11', 'opt12']193+ assert list(get_choices(cli, 'lol', ['--opt3'], 'opti')) == ['option']194+195+ assert list(get_choices(cli, 'lol', ['--opt1', 'invalid_opt'], '-')) == ['--opt2', '--opt3']196+197+198+def test_option_and_arg_choice():199+ @click.command()200+ @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))201+ @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))202+ @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))203+ def cli():204+ pass205+206+ assert list(get_choices(cli, 'lol', ['--opt1'], '')) == ['opt11', 'opt12']207+ assert list(get_choices(cli, 'lol', [''], '--opt1=')) == ['opt11', 'opt12']208+ assert list(get_choices(cli, 'lol', [], '')) == ['arg11', 'arg12']209+ assert list(get_choices(cli, 'lol', ['--opt2'], '')) == ['opt21', 'opt22']210+211+212+def test_boolean_flag_choice():213+ @click.command()214+ @click.option('--shout/--no-shout', default=False)215+ @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))216+ def cli(local_opt):217+ pass218+219+ assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']220+ assert list(get_choices(cli, 'lol', ['--shout'], '')) == ['arg1', 'arg2']221+222+223+def test_multi_value_option_choice():224+ @click.command()225+ @click.option('--pos', nargs=2, type=click.Choice(['pos1', 'pos2']))226+ @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))227+ def cli(local_opt):228+ pass229+230+ assert list(get_choices(cli, 'lol', ['--pos'], '')) == ['pos1', 'pos2']231+ assert list(get_choices(cli, 'lol', ['--pos', 'pos1'], '')) == ['pos1', 'pos2']232+ assert list(get_choices(cli, 'lol', ['--pos', 'pos1', 'pos2'], '')) == ['arg1', 'arg2']233+ assert list(get_choices(cli, 'lol', ['--pos', 'pos1', 'pos2', 'arg1'], '')) == []234+235+236+def test_multi_option_choice():237+ @click.command()238+ @click.option('--message', '-m', multiple=True, type=click.Choice(['m1', 'm2']))239+ @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))240+ def cli(local_opt):241+ pass242+243+ assert list(get_choices(cli, 'lol', ['-m'], '')) == ['m1', 'm2']244+ assert list(get_choices(cli, 'lol', ['-m', 'm1', '-m'], '')) == ['m1', 'm2']245+ assert list(get_choices(cli, 'lol', ['-m', 'm1'], '')) == ['arg1', 'arg2']246+247+248+def test_variadic_argument_choice():249+ @click.command()250+ @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))251+ def cli(local_opt):252+ pass253+254+ assert list(get_choices(cli, 'lol', ['src1', 'src2'], '')) == ['src1', 'src2']255+256+257+def test_long_chain_choice():258+ @click.group()259+ def cli():260+ pass261+262+ @cli.group('sub')263+ @click.option('--sub-opt', type=click.Choice(['subopt1', 'subopt2']))264+ @click.argument('sub-arg', required=False, type=click.Choice(['subarg1', 'subarg2']))265+ def sub(sub_opt):266+ pass267+268+ @sub.command('bsub')269+ @click.option('--bsub-opt', type=click.Choice(['bsubopt1', 'bsubopt2']))270+ @click.argument('bsub-arg1', required=False, type=click.Choice(['bsubarg1', 'bsubarg2']))271+ @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))272+ def bsub(bsub_opt):273+ pass274+275+ assert list(get_choices(cli, 'lol', ['sub'], '')) == ['subarg1', 'subarg2', 'bsub']276+ assert list(get_choices(cli, 'lol', ['sub', '--sub-opt'], '')) == ['subopt1', 'subopt2']277+ assert list(get_choices(cli, 'lol', ['sub', '--sub-opt', 'subopt1'], '')) == \278+ ['subarg1', 'subarg2', 'bsub']279+ assert list(get_choices(cli, 'lol',280+ ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '-')) == ['--bsub-opt']281+ assert list(get_choices(cli, 'lol',282+ ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt'], '')) == \283+ ['bsubopt1', 'bsubopt2']284+ assert list(get_choices(cli, 'lol',285+ ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt', 'bsubopt1', 'bsubarg1'],286+ '')) == ['bbsubarg1', 'bbsubarg2']modified:tests/test_basic.py+100 added-1 removed
178 unmodified lines179 assert not result.exception180 assert result.output == '%s\n' % (default)181 182 183+def test_boolean_conversion(runner):184+ for default in True, False:185+ @click.command()186+ @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':191+ result = runner.invoke(cli, ['--flag', value])192+ assert not result.exception193+ assert result.output == 'True\n'194+195+ for value in 'false', 'f', '0', 'no', 'n':196+ result = runner.invoke(cli, ['--flag', value])197+ assert not result.exception198+ assert result.output == 'False\n'199+200+ result = runner.invoke(cli, [])201+ assert not result.exception202+ assert result.output == '%s\n' % default203+204+205 def test_file_option(runner):206 @click.command()207 @click.option('--file', type=click.File('w'))208 def input(file):155 unmodified lines364 assert not result.exception365 assert result.output == '0\n'366 367 368+def test_float_range_option(runner):369+ @click.command()370+ @click.option('--x', type=click.FloatRange(0, 5))371+ def cli(x):372+ click.echo(x)373+374+ result = runner.invoke(cli, ['--x=5.0'])375+ assert not result.exception376+ assert result.output == '5.0\n'377+378+ result = runner.invoke(cli, ['--x=6.0'])379+ assert result.exit_code == 2380+ assert 'Invalid value for "--x": 6.0 is not in the valid range of 0 to 5.\n' \381+ in result.output382+383+ @click.command()384+ @click.option('--x', type=click.FloatRange(0, 5, clamp=True))385+ def clamp(x):386+ click.echo(x)387+388+ result = runner.invoke(clamp, ['--x=5.0'])389+ assert not result.exception390+ assert result.output == '5.0\n'391+392+ result = runner.invoke(clamp, ['--x=6.0'])393+ assert not result.exception394+ assert result.output == '5\n'395+396+ result = runner.invoke(clamp, ['--x=-1.0'])397+ assert not result.exception398+ assert result.output == '0\n'399+400+401 def test_required_option(runner):402 @click.command()403 @click.option('--foo', required=True)404 def cli(foo):6 unmodified lines411 412 def test_evaluation_order(runner):413 called = []414 360- def memo(ctx, value):415+ def memo(ctx, param, value):416 called.append(value)417 return value418 419 @click.command()31 unmodified lines451 'normal3',452 'normal1',453 'missing',454 ]455+456+457+def test_hidden_option(runner):458+ @click.command()459+ @click.option('--nope', hidden=True)460+ def cli(nope):461+ click.echo(nope)462+463+ result = runner.invoke(cli, ['--help'])464+ assert result.exit_code == 0465+ assert '--nope' not in result.output466+467+468+def test_hidden_command(runner):469+ @click.group()470+ def cli():471+ pass472+473+ @cli.command(hidden=True)474+ def nope():475+ pass476+477+ result = runner.invoke(cli, ['--help'])478+ assert result.exit_code == 0479+ assert 'nope' not in result.output480+481+482+def test_hidden_group(runner):483+ @click.group()484+ def cli():485+ pass486+487+ @cli.group(hidden=True)488+ def subgroup():489+ pass490+491+ @subgroup.command()492+ def nope():493+ pass494+495+ result = runner.invoke(cli, ['--help'])496+ assert result.exit_code == 0497+ assert 'subgroup' not in result.output498+ assert 'nope' not in result.outputmodified:tests/test_commands.py+64 added-2 removed
1 # -*- coding: utf-8 -*-2 import re3+4 import click5+import pytest6 7 8 def test_other_command_invoke(runner):9 @click.command()53 unmodified lines63 assert re.search(64 r'Commands:\n\s+'65 r'long\s+This is a long text that is too long to show\.\.\.\n\s+'66 r'short\s+This is a short text\.\n\s+'65- r'special_chars\s+Login and store the token in ~/.netrc\.\s*',67+ r'special-chars\s+Login and store the token in ~/.netrc\.\s*',68 result.output) is not None69 70 71 def test_default_maps(runner):135 unmodified lines207 @click.command()208 @click.option('--foo', type=click.INT, default=42)209 @click.pass_context210 def other_cmd(ctx, foo):209- assert ctx.info_name == 'other_cmd'211+ assert ctx.info_name == 'other-cmd'212 click.echo(foo)213 214 result = runner.invoke(cli, [])215 assert not result.exception38 unmodified lines254 assert result.output.splitlines() == [255 'Verbosity: 4',256 'Args: -foo|-x|--muhaha|x|y|-x',257 ]258+259+260+def test_subcommand_naming(runner):261+ @click.group()262+ def cli():263+ pass264+265+ @cli.command()266+ def foo_bar():267+ click.echo('foo-bar')268+269+ result = runner.invoke(cli, ['foo-bar'])270+ assert not result.exception271+ assert result.output.splitlines() == ['foo-bar']272+273+274+def test_environment_variables(runner):275+ @click.group()276+ def cli():277+ pass278+279+ @cli.command()280+ @click.option('--name', envvar='CLICK_NAME')281+ def foo(name):282+ click.echo(name)283+284+ result = runner.invoke(cli, ['foo'], env={'CLICK_NAME': 'environment'})285+286+ assert not result.exception287+ assert result.output == 'environment\n'288+289+290+# Ensures the variables are read in the following order:291+# 1. CLI292+# 2. Environment293+# 3. Defaults294+variable_precedence_testdata = [295+ (['foo', '--name=cli'], {'CLICK_NAME': 'environment'}, 'cli\n'),296+ (['foo'], {'CLICK_NAME': 'environment'}, 'environment\n'),297+ (['foo'], None, 'defaults\n'),298+]299+300+301+@pytest.mark.parametrize("command,environment,expected",302+ variable_precedence_testdata)303+def test_variable_precendence_00(runner, command, environment, expected):304+ @click.group()305+ def cli():306+ pass307+308+ @cli.command()309+ @click.option('--name', envvar='CLICK_NAME')310+ def foo(name):311+ click.echo(name)312+313+ defaults = {'foo': {'name': 'defaults'}}314+ result = runner.invoke(cli, command, default_map=defaults, env=environment)315+316+ assert not result.exception317+ assert result.output == expectedmodified:tests/test_compat.py+5 added-4 removed
1 import click2+import pytest3 4 5 if click.__version__ >= '3.0':6 def test_legacy_callbacks(runner):4 unmodified lines11 @click.option('--foo', callback=legacy_callback)12 def cli(foo):13 click.echo(foo)14 14- result = runner.invoke(cli, ['--foo', 'wat'])15- assert result.exit_code == 016- assert 'WAT' in result.output17- assert 'Invoked legacy parameter callback' in result.output15+ with pytest.warns(Warning, match='Invoked legacy parameter callback'):16+ result = runner.invoke(cli, ['--foo', 'wat'])17+ assert result.exit_code == 018+ assert 'WAT' in result.output19 20 21 def test_bash_func_name():22 from click._bashcomplete import get_completion_script3 unmodified linesmodified:tests/test_formatting.py+107 added-4 removed
72 unmodified lines73 """74 75 # 54 is chosen as a length where the second line is one character76 # longer than the maximum length.77- result = runner.invoke(cli, ['a_very_long', 'command', '--help'],77+ result = runner.invoke(cli, ['a-very-long', 'command', '--help'],78 terminal_width=54)79 assert not result.exception80 assert result.output.splitlines() == [81- 'Usage: cli a_very_long command [OPTIONS] FIRST SECOND',81+ 'Usage: cli a-very-long command [OPTIONS] FIRST SECOND',82 ' THIRD FOURTH FIFTH',83 ' SIXTH',84 '',85 ' A command.',24 unmodified lines110 def command():111 """A command.112 """113 114- result = runner.invoke(cli, ['a_very_very_very_long', 'command', '--help'],114+ result = runner.invoke(cli, ['a-very-very-very-long', 'command', '--help'],115 terminal_width=54)116 assert not result.exception117 assert result.output.splitlines() == [118- 'Usage: cli a_very_very_very_long command ',118+ 'Usage: cli a-very-very-very-long command ',119 ' [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH',120 ' SIXTH',121 '',122 ' A command.',21 unmodified lines144 '',145 'Options:',146 ' --help Show this message and exit.',147 ]148+149+150+def test_formatting_usage_error(runner):151+ @click.command()152+ @click.argument('arg')153+ def cmd(arg):154+ click.echo('arg:' + arg)155+156+ result = runner.invoke(cmd, [])157+ assert result.exit_code == 2158+ assert result.output.splitlines() == [159+ 'Usage: cmd [OPTIONS] ARG',160+ 'Try "cmd --help" for help.',161+ '',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+ pass206+207+ @cmd.command()208+ @click.argument('bar')209+ def foo(bar):210+ click.echo('foo:' + bar)211+212+ result = runner.invoke(cmd, ['foo'])213+ assert result.exit_code == 2214+ assert result.output.splitlines() == [215+ 'Usage: cmd foo [OPTIONS] BAR',216+ 'Try "cmd foo --help" for help.',217+ '',218+ 'Error: Missing argument "BAR".'219+ ]220+221+222+def test_formatting_usage_error_no_help(runner):223+ @click.command(add_help_option=False)224+ @click.argument('arg')225+ def cmd(arg):226+ click.echo('arg:' + arg)227+228+ result = runner.invoke(cmd, [])229+ assert result.exit_code == 2230+ assert result.output.splitlines() == [231+ 'Usage: cmd [OPTIONS] ARG',232+ '',233+ 'Error: Missing argument "ARG".'234+ ]235+236+237+def test_formatting_usage_custom_help(runner):238+ @click.command(context_settings=dict(help_option_names=['--man']))239+ @click.argument('arg')240+ def cmd(arg):241+ click.echo('arg:' + arg)242+243+ result = runner.invoke(cmd, [])244+ assert result.exit_code == 2245+ assert result.output.splitlines() == [246+ 'Usage: cmd [OPTIONS] ARG',247+ 'Try "cmd --man" for help.',248+ '',249+ 'Error: Missing argument "ARG".'250+ ]modified:tests/test_imports.py+1 added-2 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'35+ 'threading', 'colorama', 'errno', 'fcntl'36 ])37 38 if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',7 unmodified lines47 48 if sys.version_info[0] != 2:49 rv = rv.decode('utf-8')50 imported = json.loads(rv)51- print(imported)51 52 for module in imported:53 if module == 'click' or module.startswith('click.'):54 continue1 unmodified linemodified:tests/test_options.py+81 added-2 removed
82 unmodified lines83 assert not result.exception84 assert result.output == 'verbosity=0\n'85 86 result = runner.invoke(cli, ['--help'])87- assert re.search('-v\s+Verbosity', result.output) is not None87+ assert re.search(r'-v\s+Verbosity', result.output) is not None88 89 90 @pytest.mark.parametrize('unknown_flag', ['--foo', '-f'])91 def test_unknown_options(runner, unknown_flag):105 unmodified lines197 assert not result.exception198 assert result.output == 'x|1\ny|2\n'199 200 201+def test_show_envvar(runner):202+ @click.command()203+ @click.option('--arg1', envvar='ARG1',204+ show_envvar=True)205+ def cmd(arg):206+ pass207+208+ result = runner.invoke(cmd, ['--help'])209+ assert not result.exception210+ assert 'ARG1' in result.output211+212+213+def test_show_envvar_auto_prefix(runner):214+ @click.command()215+ @click.option('--arg1', show_envvar=True)216+ def cmd(arg):217+ pass218+219+ result = runner.invoke(cmd, ['--help'],220+ auto_envvar_prefix='TEST')221+ assert not result.exception222+ assert 'TEST_ARG1' in result.output223+224+225 def test_custom_validation(runner):202- def validate_pos_int(ctx, value):226+ def validate_pos_int(ctx, param, value):227 if value < 0:228 raise click.BadParameter('Value needs to be positive')229 return value230 103 unmodified lines334 assert 'I am a help text' in result.output335 assert 'you wont see me' not in result.output336 337 338+def test_option_custom_class_reusable(runner):339+ """Ensure we can reuse a custom class option. See Issue #926"""340+341+ class CustomOption(click.Option):342+ def get_help_record(self, ctx):343+ '''a dumb override of a help text for testing'''344+ return ('--help', 'I am a help text')345+346+ # Assign to a variable to re-use the decorator.347+ testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')348+349+ @click.command()350+ @testoption351+ def cmd1(testoption):352+ click.echo(testoption)353+354+ @click.command()355+ @testoption356+ def cmd2(testoption):357+ click.echo(testoption)358+359+ # Both of the commands should have the --help option now.360+ for cmd in (cmd1, cmd2):361+362+ result = runner.invoke(cmd, ['--help'])363+ assert 'I am a help text' in result.output364+ assert 'you wont see me' not in result.output365+366+367 def test_aliases_for_flags(runner):368 @click.command()369 @click.option('--warnings/--no-warnings', ' /-W', default=True)370 def cli(warnings):16 unmodified lines387 result = runner.invoke(cli_alt, ['--no-warnings'])388 assert result.output == 'False\n'389 result = runner.invoke(cli_alt, ['-w'])390 assert result.output == 'True\n'391+392+@pytest.mark.parametrize('option_args,expected', [393+ (['--aggressive', '--all', '-a'], 'aggressive'),394+ (['--first', '--second', '--third', '-a', '-b', '-c'], 'first'),395+ (['--apple', '--banana', '--cantaloupe', '-a', '-b', '-c'], 'apple'),396+ (['--cantaloupe', '--banana', '--apple', '-c', '-b', '-a'], 'cantaloupe'),397+ (['-a', '-b', '-c'], 'a'),398+ (['-c', '-b', '-a'], 'c'),399+ (['-a', '--apple', '-b', '--banana', '-c', '--cantaloupe'], 'apple'),400+ (['-c', '-a', '--cantaloupe', '-b', '--banana', '--apple'], 'cantaloupe'),401+ (['--from', '-f', '_from'], '_from'),402+ (['--return', '-r', '_ret'], '_ret'),403+])404+def test_option_names(runner, option_args, expected):405+406+ @click.command()407+ @click.option(*option_args, is_flag=True)408+ def cmd(**kwargs):409+ click.echo(str(kwargs[expected]))410+411+ assert cmd.params[0].name == expected412+413+ for form in option_args:414+ if form.startswith('-'):415+ result = runner.invoke(cmd, [form])416+ assert result.output == 'True\n'modified:tests/test_termui.py+83 added-2 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 19 unmodified lines50 @click.command()51 def cli():52 with click.progressbar(Hinted(10), label='test') as progress:53 for thing in progress:40- pass54+ time.sleep(.5)55 56 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)57 result = runner.invoke(cli, [])58 assert result.exception is None59+60+61+def test_progressbar_hidden(runner, monkeypatch):62+ label = 'whatever'63+64+ @click.command()65+ def cli():66+ with click.progressbar(tuple(range(10)), label=label) as progress:67+ for thing in progress:68+ pass69+70+ monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)71+ assert runner.invoke(cli, []).output == ''72+73+74+def test_choices_list_in_prompt(runner, monkeypatch):75+ @click.command()76+ @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),77+ prompt=True)78+ def cli_with_choices(g):79+ pass80+81+ @click.command()82+ @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),83+ prompt=True, show_choices=False)84+ def cli_without_choices(g):85+ pass86+87+ result = runner.invoke(cli_with_choices, [], input='none')88+ assert '(none, day, week, month)' in result.output89+90+ result = runner.invoke(cli_without_choices, [], input='none')91+ assert '(none, day, week, month)' not in result.output92+93+94+def test_secho(runner):95+ with runner.isolation() as outstreams:96+ click.secho(None, nl=False)97+ bytes = outstreams[0].getvalue()98+ assert bytes == b''99+100+101+def test_progressbar_yields_all_items(runner):102+ with click.progressbar(range(3)) as progress:103+ assert len(list(progress)) == 3104+105+106+def test_progressbar_update(runner, monkeypatch):107+ fake_clock = FakeClock()108+109+ @click.command()110+ def cli():111+ with click.progressbar(range(4)) as progress:112+ for _ in progress:113+ fake_clock.advance_time()114+ print("")115+116+ monkeypatch.setattr(time, 'time', fake_clock.time)117+ monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)118+ output = runner.invoke(cli, []).output119+120+ lines = [line for line in output.split('\n') if '[' in line]121+122+ assert ' 25% 00:00:03' in lines[0]123+ assert ' 50% 00:00:02' in lines[1]124+ assert ' 75% 00:00:01' in lines[2]125+ assert '100% ' in lines[3]modified:tests/test_testing.py+74 added
1+import os2 import sys3 4 import pytest5 import click177 unmodified lines183 184 result = runner.invoke(cli_no_error)185 assert result.exit_code == 0186 assert result.output == 'hello world\n'187+188+189+def test_env():190+ @click.command()191+ def cli_env():192+ click.echo('ENV=%s' % os.environ['TEST_CLICK_ENV'])193+194+ runner = CliRunner()195+196+ env_orig = dict(os.environ)197+ env = dict(env_orig)198+ assert 'TEST_CLICK_ENV' not in env199+ env['TEST_CLICK_ENV'] = 'some_value'200+ result = runner.invoke(cli_env, env=env)201+ assert result.exit_code == 0202+ assert result.output == 'ENV=some_value\n'203+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'),235+ (['--foo', 'one two'], 'one two\n'),236+ ('--foo "one two"', 'one two\n'),237+])238+def test_args(args, expected_output):239+240+ @click.command()241+ @click.option('--foo', default='bar')242+ def cli_args(foo):243+ click.echo(foo)244+245+ 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:CHANGES+74 added-2 removed
5 unmodified lines6 Version 7.07 -----------8 9 (upcoming release with new features, release date to be decided)10-10+- Added support for bash completions containing spaces. See #773.11+- Added support for dynamic bash completion from a user-supplied callback.12+ See #755.13+- Added support for bash completion of type=click.Choice for Options and14+ Arguments. See #535.15+- The user is now presented with the available choices if prompt=True and16+ type=click.Choice in a click.option. The choices are listed within17+ parenthesis like 'Choose fruit (apple, orange): '.18 - The exception objects now store unicode properly.19+- Added the ability to hide commands and options from help.20+- Added Float Range in Types.21+- `secho`'s first argument can now be `None`, like in `echo`.22+- Usage errors now hint at the `--help` option.23+- ``launch`` now works properly under Cygwin. See #650.24+- `CliRunner.invoke` now may receive `args` as a string representing25+ a Unix shell command. See #664.26+- Fix bug that caused bashcompletion to give improper completions on27+ chained commands. See #774.28+- Add support for bright colors.29+- 't' and 'f' are now converted to True and False.30+- Fix bug that caused bashcompletion to give improper completions on31+ chained commands when a required option/argument was being completed.32+ See #790.33+- Allow autocompletion function to determine whether or not to return34+ completions that start with the incomplete argument.35+- Subcommands that are named by the function now automatically have the36+ underscore replaced with a dash. So if you register a function named37+ `my_command` it becomes `my-command` in the command line interface.38+- Stdout is now automatically set to non blocking.39+- Use realpath to convert atomic file internally into its full canonical40+ path so that changing working directories does not harm it.41+- Force stdout/stderr writable. This works around issues with badly patched42+ standard streams like those from jupyter.43 44+Version 6.845+-----------46+47+(bugfix release; yet to be released)48+49+- Disabled sys._getframes() on Python interpreters that don't support it. See50+ #728.51+- Fix bug in test runner when calling ``sys.exit`` with ``None``. See #739.52+- Fix crash on Windows console, see #744.53+- Fix bashcompletion on chained commands. See #754.54+- Fix option naming routine to match documentation. See #79355+- Fixed the behavior of click error messages with regards to unicode on 2.x56+ and 3.x respectively. Message is now always unicode and the str and unicode57+ special methods work as you expect on that platform.58+59+Version 6.760+-----------61+62+(bugfix release; released on January 6th 2017)63+64+- Make `click.progressbar` work with `codecs.open` files. See #637.65+- Fix bug in bash completion with nested subcommands. See #639.66+- Fix test runner not saving caller env correctly. See #644.67+- Fix handling of SIGPIPE. See #62668+- Deal with broken Windows environments such as Google App Engine's. See #711.69+70+Version 6.671+-----------72+73+(bugfix release; released on April 4th 2016)74+75+- Fix bug in `click.Path` where it would crash when passed a `-`. See #551.76+77+Version 6.478+-----------79+80+(bugfix release; released on March 24th 2016)81+82+- Fix bug in bash completion where click would discard one or more trailing83+ arguments. See #471.84+85 Version 6.386 -----------87 16-(bugfix release; unreleased)88+(bugfix release; released on February 22 2016)89 90 - Fix argument checks for interpreter invoke with `-m` and `-c`91 on Windows.92 - Fixed a bug that cased locale detection to error out on Python 3.311 unmodified linesmodified:CONTRIBUTING.rst+6 added-1 removed
30 unmodified lines31 32 - Try to follow `PEP8 <http://legacy.python.org/dev/peps/pep-0008/>`_, but you33 may ignore the line-length-limit if following it would make the code uglier.34 35+- For features: Consider whether your feature would be a better fit for an36+ `external package <http://click.pocoo.org/contrib/>`_37+38+- For bugfixes: Submit against the latest maintenance branch instead of master!39+40 Running the testsuite41 ---------------------42 43 You probably want to set up a `virtualenv39-<http://virtualenv.readthedocs.org/en/latest/index.html>`_.44+<https://virtualenv.readthedocs.io/en/latest/index.html>`_.45 46 The minimal requirement for running the testsuite is ``py.test``. You can47 install it with::48 13 unmodified linesmodified:Makefile+1 added-1 removed
1 test:2- @cd tests; PYTHONPATH=.. py.test --tb=short2+ @cd tests; PYTHONPATH=.. pytest --tb=short3 4 upload-docs:5 $(MAKE) -C docs dirhtml6 rsync -a docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/click.pocoo.org/static/5 unmodified linesadded:README.rst+92 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+A Simple Example32+----------------33+34+What does it look like? Here is an example of a simple Click program:35+36+.. code-block:: python37+38+ import click39+ 40+ @click.command()41+ @click.option('--count', default=1, help='Number of greetings.')42+ @click.option('--name', prompt='Your name',43+ help='The person to greet.')44+ def hello(count, name):45+ """Simple program that greets NAME for a total of COUNT times."""46+ for x in range(count):47+ click.echo('Hello %s!' % name)48+ 49+ if __name__ == '__main__':50+ hello()51+52+And what it looks like when run:53+54+.. code-block:: text55+56+ $ python hello.py --count=357+ Your name: John58+ Hello John!59+ Hello John!60+ Hello John!61+62+Donate63+------64+65+The Pallets organization develops and supports Flask and the libraries66+it uses. In order to grow the community of contributors and users, and67+allow the maintainers to devote more time to the projects, `please68+donate today`_.69+70+.. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=2071+72+73+Links74+-----75+76+* Website: https://www.palletsprojects.com/p/click/77+* Documentation: http://click.pocoo.org/78+* License: `BSD <https://github.com/pallets/click/blob/master/LICENSE>`_79+* Releases: https://pypi.org/project/click/80+* Code: https://github.com/pallets/click81+* Issue tracker: https://github.com/pallets/click/issues82+* Test status:83+84+ * Linux, Mac: https://travis-ci.org/pallets/click85+ * Windows: https://ci.appveyor.com/project/pallets/click86+87+* Test coverage: https://codecov.io/gh/pallets/click88+89+.. _WSGI: https://wsgi.readthedocs.io90+.. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/91+.. _Jinja: https://www.palletsprojects.com/p/jinja/92+.. _pip: https://pip.pypa.io/en/stable/quickstart/modified:setup.cfg+7 added-1 removed
1-[wheel]1+[bdist_wheel]2 universal=13+4+[metadata]5+license_file = LICENSE6+7+[tool:pytest]8+addopts = -p no:warnings --tb=shortmodified:setup.py+27 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/mitsuhiko/click',23+ maintainer='Pallets team',24+ maintainer_email='contact@palletsprojects.com',25+ long_description=readme,26 packages=['click'],27+ extras_require={28+ 'docs': [29+ 'sphinx',30+ ],31+ },32 description='A simple wrapper around optparse for '33 'powerful command line utilities.',34+ license='BSD',35 classifiers=[36+ 'Development Status :: 5 - Production/Stable',37+ 'Intended Audience :: Developers',38 'License :: OSI Approved :: BSD License',39+ 'Operating System :: OS Independent'40 'Programming Language :: Python',41+ 'Programming Language :: Python :: 2',42+ 'Programming Language :: Python :: 2.7',43 'Programming Language :: Python :: 3',44+ 'Programming Language :: Python :: 3.4',45+ 'Programming Language :: Python :: 3.5',46+ 'Programming Language :: Python :: 3.6',47 ],48+ python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",49 )modified:tox.ini+7 added-4 removed
1 [tox]2-envlist = py26,py27,py33,py34,pypy2+envlist = py27,py34,py35,py36,pypy3+skip_missing_interpreters = true4 5 [testenv]6 passenv = LANG6-commands = make test7+commands = {env:TEST_RUNNER:pytest} {posargs}8 deps =8- colorama9 pytest10-whitelist_externals = make10+ colorama: colorama11+ coverage: coverage12+setenv =13+ coverage: TEST_RUNNER=coverage run -m pytest