Skip to content
Myr

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

50 files+1983 added−364 removed

modified:click/__init__.py+2 added-2 removed
26 unmodified lines
27 password_option, version_option, help_option2829# Types30from .types import ParamType, File, Path, Choice, IntRange, Tuple, \31 STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED31 STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange3233# Utilities34from .utils import echo, get_binary_stream, get_text_stream, open_file, \35 format_filename, get_app_dir, get_os_args
29 unmodified lines
65 'version_option', 'help_option',6667 # Types68 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple', 'STRING',69 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',69 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED', 'FloatRange',7071 # Utilities72 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',73 'format_filename', 'get_app_dir', 'get_os_args',
25 unmodified lines
modified:click/_bashcomplete.py+163 added-24 removed
1import collections2import copy3import os4import re56from .utils import echo7from .parser import split_arg_string5from .core import MultiCommand, Option8from .core import MultiCommand, Option, Argument9from .types import Choice1011WORDBREAK = '='1213COMPLETION_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 0
14 unmodified lines
34 }).strip() + ';'353637def 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.parent5758 return ctx596061def 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] == '-'676869def 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_str8788 return True if last_option and last_option in cmd_param.opts else False899091def 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 False109110111def 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 []127128129def 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)])134135 # 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)])143144145def 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)154155 ctx = resolve_ctx(cli, prog_name, args)156 if ctx is None:157 return []158159 # 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 = ''167168 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 break191192 add_subcommand_completions(ctx, incomplete, completions)193 return completions194195196def 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 line
201 incomplete = cwords[cword]202 except IndexError:203 incomplete = ''20451 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)20755 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))6465 for item in choices:66 if item.startswith(incomplete):67 echo(item)68208 return True209210211def bashcomplete(cli, prog_name, complete_var, complete_instr):
6 unmodified lines
modified:click/_compat.py+71 added-21 removed
6 unmodified lines
789PY2 = sys.version_info[0] == 210WIN = sys.platform.startswith('win')11CYGWIN = sys.platform.startswith('cygwin')12DEFAULT_COLUMNS = 80131414_ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')15_ansi_re = re.compile(r'\033\[((?:\d|;)*)([a-zA-Z])')161718def get_filesystem_encoding():19 return sys.getfilesystemencoding() or sys.getdefaultencoding()202121def _make_text_stream(stream, encoding, errors):22def _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)323334def is_ascii_encoding(encoding):35 """Checks if a given encoding is ascii."""
12 unmodified lines
484950class _NonClosingTextIOWrapper(io.TextIOWrapper):5148 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)5758 # The io module is a place where the Python 3 text behavior59 # was forced upon Python 2, so we need to unbreak
26 unmodified lines
86class _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.9091 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 """9586 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_writable100101 def __getattr__(self, name):102 return getattr(self._stream, name)103
8 unmodified lines
112 return self._stream.readline(size)113 return self._stream.read(size)114115 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 lines
124 return False125 return True126127 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 lines
176 # 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 f187188 try:189 import msvcrt190191 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 pass201202 try:203 import fcntl204205 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 pass216217 def isidentifier(x):218 return _identifier_re.search(x) is not None219220 def get_binary_stdin():
8 unmodified lines
229 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)235236 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)242243 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)249250 def filename_to_ui(value):251 if isinstance(value, bytes):252 value = value.decode(get_filesystem_encoding(), 'replace')
83 unmodified lines
336 return stream_encoding is not None337338 return False339297 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 the
17 unmodified lines
363 # 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)369325 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 the
17 unmodified lines
393 # 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)399400 def get_binary_stdin():401 reader = _find_binary_reader(sys.stdin)402 if reader is None:
18 unmodified lines
421 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)427428 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)434435 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)441442 def filename_to_ui(value):443 if isinstance(value, bytes):444 value = value.decode(get_filesystem_encoding(), 'replace')
20 unmodified lines
465 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 lines
505 f = io.open(fd, mode, encoding=encoding, errors=errors)506 else:507 f = os.fdopen(fd, mode)508459 return _AtomicFile(f, tmp_filename, filename), True509 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True510511512# Used in a destructor call, needs extra protection from interpreter cleanup.513if hasattr(os, 'replace'):
181 unmodified lines
modified:click/_termui_impl.py+83 added-69 removed
11 unmodified lines
12import os13import sys14import time15import math1617from ._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 CYGWIN20from .utils import echo21from .exceptions import ClickException2223
8 unmodified lines
32def _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 None
62 unmodified lines
103 def __iter__(self):104 if not self.entered:105 raise RuntimeError('You need to use progress bars in a with block.')106 self.render_progress()105 return self107 return self.generator()108109 def is_fast(self):110 return time.time() - self.start <= self.short_limit111
22 unmodified lines
134 return 0.0135136 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 lines
196 }).rstrip()197198 def render_progress(self):199 from .termui import get_terminal_size198 nl = False200201 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 return203217 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_width216221 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_width220228 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_len226227 buf.append(line)228 buf.append(' ' * (clear_width - line_len))229 line = ''.join(buf)230 # Render the line only if it changed.231232 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()236237 def make_step(self, n_steps):238 self.pos += n_steps
16 unmodified lines
255 self.eta_known = 0256 self.current_item = None257 self.finished = True258260 def next(self):259 def generator(self):260 """261 Returns a generator which yields the items added to the bar during262 construction, and updates the progress bar *after* the yielded block263 returns.264 """265 if not self.entered:266 raise RuntimeError('You need to use progress bars in a with block.')267268 if self.is_hidden: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 rv278274 if not PY2:275 __next__ = next276 del next279278279def pager(text, color=None):280def pager(generator, color=None):281 """Decide what method to use for paging through text."""282 stdout = _default_text_stdout()283 if not isatty(sys.stdin) or not isatty(stdout):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)296297 import tempfile298 fd, filename = tempfile.mkstemp()299 os.close(fd)300 try:301 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: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)306307307def _pipepager(text, cmd, color):308def _pipepager(generator, cmd, color):309 """Page through text by feeding it to another program. Invoking a310 pager through this might support colors.311 """312 import subprocess
9 unmodified lines
322 color = True323 elif 'r' in less_flags or 'R' in less_flags:324 color = True325325 if not color:326 text = strip_ansi(text)327326 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)333334 c.stdin.write(text.encode(encoding, 'replace'))335 except (IOError, KeyboardInterrupt):336 pass337 else:338 c.stdin.close()339340 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting341 # search or other commands inside less).342 #
10 unmodified lines
353 else:354 break355356354def _tempfilepager(text, cmd, color):357def _tempfilepager(generator, cmd, color):358 """Page through text by invoking a program on a temporary file."""359 import tempfile360 filename = tempfile.mktemp()361 # TODO: This never terminates if the passed generator never terminates.362 text = "".join(generator)363 if not color:364 text = strip_ansi(text)365 encoding = get_best_encoding(sys.stdout)366 with open_stream(filename, 'wb')[0] as f:
3 unmodified lines
370 finally:371 os.unlink(filename)372373369def _nullpager(stream, text, color):374def _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)380381382class Editor(object):383
104 unmodified lines
488 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)500501 try:502 if locate:503 url = os.path.dirname(_unquote_file(url)) or '.'
63 unmodified lines
modified:click/_unicodefun.py+10 added-6 removed
12 unmodified lines
131415def _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 lines
6162 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 = False7273 # Make sure we're operating on text here.
24 unmodified lines
98 )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))105106 bad_locale = None
11 unmodified lines
118 ) % bad_locale119120 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 lines
15import time16import ctypes17import msvcrt18from click._compat import _NonClosingTextIOWrapper, text_type, PY219from ctypes import byref, POINTER, pythonapi, c_int, c_char, c_char_p, \19from ctypes import byref, POINTER, c_int, c_char, c_char_p, \20 c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE21try:22 from ctypes import pythonapi23 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer24 PyBuffer_Release = pythonapi.PyBuffer_Release25except ImportError:26 pythonapi = None27from ctypes.wintypes import LPWSTR, LPCWSTR282930c_ssize_p = POINTER(c_ssize_t)3126PyObject_GetBuffer = pythonapi.PyObject_GetBuffer27PyBuffer_Release = pythonapi.PyBuffer_Release2832kernel32 = windll.kernel3233GetStdHandle = kernel32.GetStdHandle34ReadConsoleW = kernel32.ReadConsoleW35WriteConsoleW = kernel32.WriteConsoleW
43 unmodified lines
79 if PY2:80 _fields_.insert(-1, ('smalltable', c_ssize_t * 2))818283# On PyPy we cannot get buffers so our ability to operate here is84# serverly limited.85if pythonapi is None:86 get_buffer = None87else:80def 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))979899class _WindowsConsoleRawIOBase(io.RawIOBase):100
152 unmodified lines
253}254255256def _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 we
5 unmodified lines
modified:click/core.py+72 added-22 removed
1import errno2import os3import sys4from contextlib import contextmanager5from itertools import repeat
18 unmodified lines
24SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'25SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'262728def 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)353637def _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 lines
43 return4445 from ._bashcomplete import bashcomplete46 if bashcomplete(cmd, prog_name, complete_var, complete_instr):37 sys.exit(1)47 fast_exit(1)484950def _check_multicommand(base_command, cmd_name, cmd, register=False):51 if not base_command.chain or not isinstance(cmd, MultiCommand):
6 unmodified lines
58 '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 lines
378379 @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.385386 The keys are supposed to be unique dotted strings. For instance
274 unmodified lines
661 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 into
6 unmodified lines
676 :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 lines
712 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 lines
749 :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 """755756 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 = callback
7 unmodified lines
771 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 = hidden776777 def get_usage(self, ctx):778 formatter = ctx.make_formatter()779 self.format_usage(ctx, formatter)
45 unmodified lines
825826 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 lines
1009 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 continue10151016 help = cmd.short_help or ''1017 rows.append((subcommand, help))1018
206 unmodified lines
1225 return sorted(rv)122612271228class 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 lines
1270 param_type_name = 'parameter'12711272 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)12781279 self.type = convert_type(type, default)
14 unmodified lines
1294 self.default = default1295 self.is_eager = is_eager1296 self.metavar = metavar1297 self.envvar = envvar1298 self.autocompletion = autocompletion12991300 @property1301 def human_readable_name(self):1302 """Returns the human readable name of this parameter. This is the
22 unmodified lines
13251326 def add_to_parser(self, parser, ctx):1327 pass132813291330 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 value13371338 def type_cast_value(self, ctx, value):1339 """Given a value this runs it properly through the type system.
88 unmodified lines
14281429 def get_usage_pieces(self, ctx):1430 return []14311432 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)143814391440class Option(Parameter):1441 """Options are usually optional values on the command line and1442 have some extra features that arguments don't have.14431444 All other parameters are passed onwards to the parameter constructor.14451446 :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 password
12 unmodified lines
1470 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'14771478 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)14861487 if prompt is True:
4 unmodified lines
1492 prompt_text = prompt1493 self.prompt = prompt_text1494 self.confirmation_prompt = confirmation_prompt1495 self.hide_input = hide_input1496 self.hidden = hidden14971498 # Flags1499 if is_flag is None:1500 if flag_value is not None:
24 unmodified lines
1525 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_envvar15311532 # Sanity check for stuff we don't support1533 if __debug__:1534 if self.nargs < 0:
40 unmodified lines
1575 possible_names.append(split_opt(decl))1576 opts.append(decl)15771578 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 = None15831584 if name is None:
37 unmodified lines
1622 kwargs['action'] = action1623 parser.add_option(self.opts, **kwargs)16241625 def get_help_record(self, ctx):1626 if self.hidden:1627 return1628 any_prefix_is_slash = []16291630 def _write_opts(opts):1631 rv, any_slashes = join_options(opts)
8 unmodified lines
1640 rv.append(_write_opts(self.secondary_opts))16411642 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 lines
1689 # differently.1690 if self.is_bool_flag:1691 return confirm(self.prompt, default)16921646 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))16971698 def resolve_envvar_value(self, ctx):
76 unmodified lines
17751776 def get_usage_pieces(self, ctx):1777 return [self.make_metavar()]17781779 def get_error_hint(self, ctx):1780 return '"%s"' % self.make_metavar()17811782 def add_to_parser(self, parser, ctx):1783 parser.add_argument(dest=self.name, nargs=self.nargs,1784 obj=self)1785
3 unmodified lines
modified:click/decorators.py+15 added-8 removed
83 unmodified lines
84 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)909192def 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.9697 The name of the command defaults to the name of the function. If you
6 unmodified lines
104 that can be invoked as a command line utility or be attached to a105 command :class:`Group`.106107 :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 lines
163 :param cls: the option class to instantiate. This defaults to164 :class:`Option`.165 """166 def decorator(f):167 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=168 option_attrs = attrs.copy()169167 if 'help' in attrs:168 attrs['help'] = inspect.cleandoc(attrs['help'])169 OptionClass = attrs.pop('cls', Option)170 _param_memo(f, OptionClass(param_decls, **attrs))170 if 'help' in option_attrs:171 option_attrs['help'] = inspect.cleandoc(option_attrs['help'])172 OptionClass = option_attrs.pop('cls', Option)173 _param_memo(f, OptionClass(param_decls, **option_attrs))174 return f175 return decorator176177
59 unmodified lines
237 (``'%(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 = ''245246 def decorator(f):247 prog_name = attrs.pop('prog_name', None)248 message = attrs.pop('message', '%(prog)s, version %(version)s')249
62 unmodified lines
modified:click/exceptions.py+24 added-10 removed
1from ._compat import PY2, filename_to_ui, get_text_stderr2from .utils import echo345def _join_param_hints(param_hint):6 if isinstance(param_hint, (tuple, list)):7 return ' / '.join('"%s"' % x for x in param_hint)8 return param_hint91011class ClickException(Exception):12 """An exception that Click can handle and show to the user."""1314 #: The exit code for this exception
9 unmodified lines
2425 def format_message(self):26 return self.message2722 def __unicode__(self):28 def __str__(self):29 return self.message3025 def __str__(self):26 return self.message.encode('utf-8')31 if PY2:32 __unicode__ = __str__3334 def __str__(self):35 return self.message.encode('utf-8')3637 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 lines
5253 def __init__(self, message, ctx=None):54 ClickException.__init__(self, message)55 self.ctx = ctx56 self.cmd = self.ctx and self.ctx.command or None5758 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)717273class BadParameter(UsageError):
23 unmodified lines
97 def format_message(self):98 if self.param_hint is not None:99 param_hint = self.param_hint100 elif self.param is not None: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)105106 return 'Invalid value for %s: %s' % (param_hint, self.message)107108109class MissingParameter(BadParameter):
16 unmodified lines
126 def format_message(self):127 if self.param_hint is not None:128 param_hint = self.param_hint129 elif self.param is not None: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)134135 param_type = self.param_type136 if param_type is None and self.param is not None:137 param_type = self.param.param_type_name
88 unmodified lines
modified:click/globals.py+1 added-1 removed
7 unmodified lines
8 """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.1314 To push the current context, :meth:`Context.scope` can be used.1516 .. versionadded:: 5.0
32 unmodified lines
modified:click/termui.py+78 added-21 removed
1import os2import sys3import struct4import inspect5import itertools67from ._compat import raw_input, text_type, string_types, \8 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN9from .utils import echo10from .exceptions import Abort, UsageError9from .types import convert_type11from .types import convert_type, Choice12from .globals import resolve_color_default131415# The prompt functions to use. The doc tools currently override these16# functions to customize how they work.17visible_prompt_func = raw_input1817_ansi_colors = ('black', 'red', 'green', 'yellow', 'blue', 'magenta',18 'cyan', 'white', 'reset')19_ansi_colors = {20 'black': 30,21 'red': 31,22 'green': 32,23 'yellow': 33,24 'blue': 34,25 'magenta': 35,26 'cyan': 36,27 'white': 37,28 'reset': 39,29 'bright_black': 90,30 'bright_red': 91,31 'bright_green': 92,32 'bright_yellow': 93,33 'bright_blue': 94,34 'bright_magenta': 95,35 'bright_cyan': 96,36 'bright_white': 97,37}38_ansi_reset_all = '\033[0m'394041def hidden_prompt_func(prompt):42 import getpass43 return getpass.getpass(prompt)444527def _build_prompt(text, suffix, show_default=False, default=None):46def _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 + suffix535434def 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):55def 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.6061 If the user aborts the input by sending a interrupt signal, this62 function will catch it and raise a :exc:`Abort` exception.6364 .. versionadded:: 7.065 Added the show_choices parameter.6667 .. versionadded:: 6.068 Added unicode support for cmd.exe on Windows.6970 .. versionadded:: 4.0
12 unmodified lines
83 :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 = None9394 def prompt_func(text):
13 unmodified lines
108109 if value_proc is None:110 value_proc = convert_type(type, default)11185 prompt = _build_prompt(text, prompt_suffix, show_default, default)112 prompt = _build_prompt(text, prompt_suffix, show_default, default, show_choices, type)113114 while 1:115 while 1:116 value = prompt_func(prompt)
75 unmodified lines
192 if shutil_get_terminal_size:193 sz = shutil_get_terminal_size()194 return sz.columns, sz.lines195196 # We provide a sensible default for get_winterm_size() when being invoked197 # inside a subprocess. Without this, it would not provide a useful input.198 if get_winterm_size is not None:170 return get_winterm_size()199 size = get_winterm_size()200 if size == (0, 0):201 return (79, 24)202 else:203 return size204205 def ioctl_gwinsz(fd):206 try:207 import fcntl
19 unmodified lines
227 os.environ.get('COLUMNS', DEFAULT_COLUMNS))228 return int(cr[1]), int(cr[0])229230198def echo_via_pager(text, color=None):231def echo_via_pager(text_or_generator, color=None):232 """This function takes a text and shows it via an environment specific233 pager on stdout.234235 .. versionchanged:: 3.0236 Added the `color` flag.237205 :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)244245 if inspect.isgeneratorfunction(text_or_generator):246 i = text_or_generator()247 elif isinstance(text_or_generator, string_types):248 i = [text_or_generator]249 else:250 i = iter(text_or_generator)251252 # convert every element of i to a text type if necessary253 text_generator = (el if isinstance(el, string_types) else text_type(el)254 for el in i)255256 from ._termui_impl import pager213 return pager(text + '\n', color)257 return pager(itertools.chain(text_generator, "\n"), color)258259260def progressbar(iterable=None, length=None, label=None, show_eta=True,261 show_percent=None, show_pos=False,
128 unmodified lines
390 * ``blue``391 * ``magenta``392 * ``cyan``393 * ``white`` (might be light gray)394 * ``bright_black``395 * ``bright_red``396 * ``bright_green``397 * ``bright_yellow``398 * ``bright_blue``399 * ``bright_magenta``400 * ``bright_cyan``401 * ``bright_white``402 * ``reset`` (reset the color code only)403404 .. versionadded:: 2.0405406 .. versionadded:: 7.0407 Added support for bright colors.408409 :param text: the string to style with ansi codes.410 :param fg: if provided this will become the foreground color.411 :param bg: if provided this will become the background color.412 :param bold: if provided this will enable or disable bold mode.
10 unmodified lines
423 """424 bits = []425 if fg:426 try: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 lines
459 """460 return strip_ansi(text)461462408def secho(text, file=None, nl=True, err=False, color=None, **styles):463def 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::466467 click.secho('Hello World!', fg='green')
3 unmodified lines
471 depending on which one they go with.472473 .. 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)478479480def edit(text=None, editor=None, env=None, require_save=True,481 extension='.txt', filename=None):
115 unmodified lines
modified:click/testing.py+77 added-25 removed
1 unmodified line
2import sys3import shutil4import tempfile5import contextlib6import shlex77from ._compat import iteritems, PY28from ._compat import iteritems, PY2, string_types91011# If someone wants to vendor click, we want to ensure the12# correct package is discovered. Ideally we could use a
59 unmodified lines
7273class Result(object):74 """Holds the captured result of an invoked CLI script."""7575 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 = exception
1 unmodified line
89 self.exc_info = exc_info9091 @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.stdout9596 @property97 def stdout(self):98 """The standard output as unicode string."""99 return self.stdout_bytes.decode(self.runner.charset, 'replace') \100 .replace('\r\n', '\n')101102 @property103 def stderr(self):104 """The standard error as unicode string."""105 if not self.stderr_bytes:106 raise ValueError("stderr not separately captured")107 return self.stderr_bytes.decode(self.runner.charset, 'replace') \108 .replace('\r\n', '\n')109110111 def __repr__(self):95 return '<Result %s>' % (112 return '<%s %s>' % (113 type(self).__name__,114 self.exception and repr(self.exception) or 'okay',115 )116117
10 unmodified lines
128 :param echo_stdin: if this is set to `True`, then reading from stdin writes129 to stdout. This is useful for showing examples in130 some circumstances. Note that regular prompts131 will automatically echo the input.132 :param mix_stderr: if this is set to `False`, then stdout and stderr are133 preserved as independent streams. This is useful for134 Unix-philosophy apps that have predictable stdout and135 noisy stderr, such that each may be measured136 independently137 """138116 def __init__(self, charset=None, env=None, echo_stdin=False):139 def __init__(self, charset=None, env=None, echo_stdin=False,140 mix_stderr=True):141 if charset is None:142 charset = 'utf-8'143 self.charset = charset144 self.env = env or {}145 self.echo_stdin = echo_stdin146 self.mix_stderr = mix_stderr147148 def get_default_prog_name(self, cli):149 """Given a command object it will return the default program name150 for it. The default is the `name` attribute or ``"root"`` if not
36 unmodified lines
187188 env = self.make_env(env)189190 if PY2: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)209210 if self.mix_stderr:211 sys.stderr = sys.stdout212213 sys.stdin = input214215 def visible_input(prompt=None):216 sys.stdout.write(prompt or '')
14 unmodified lines
231 sys.stdout.flush()232 return char233234 default_color = color235236 def should_strip_ansi(stream=None, color=None):237 if color is None:238 return not default_color239 return not color
9 unmodified lines
249250 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 lines
277 clickpkg.utils.should_strip_ansi = old_should_strip_ansi278 clickpkg.formatting.FORCED_WIDTH = old_forced_width279280 def invoke(self, cli, args=None, input=None, env=None,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 lines
296 .. versionadded:: 4.0297 The ``color`` parameter was added.298299 :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 line
309 :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 = 0316317 if isinstance(args, string_types):318 args = shlex.split(args)319320 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)324325 try:326 cli.main(args=args or (), prog_name=prog_name, **extra)327 except SystemExit as e:328 exc_info = sys.exc_info()285329 exit_code = e.code330 if exit_code is None:331 exit_code = 0332333 if exit_code != 0:334 exception = e335336 if not isinstance(exit_code, int):337 sys.stdout.write(str(exit_code))338 sys.stdout.write('\n')339 exit_code = 1340341 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()351352 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 lines
modified:click/types.py+87 added-43 removed
127 unmodified lines
128class 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.131132 You should only pass *choices* as list or tuple. Other iterables (like133 generators) may lead to surprising results.134135 See :ref:`choice-opts` for an example.136 """137 name = 'choice'138
77 unmodified lines
216 def __repr__(self):217 return 'IntRange(%r, %r)' % (self.min, self.max)218219220class FloatParamType(ParamType):221 name = 'float'222223 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)229230 def __repr__(self):231 return 'FLOAT'232233234class 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.239240 See :ref:`ranges` for an example.241 """242 name = 'float range'243244 def __init__(self, min=None, max=None, clamp=False):245 self.min = min246 self.max = max247 self.clamp = clamp248249 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 rv268269 def __repr__(self):270 return 'FloatRange(%r, %r)' % (self.min, self.max)271272273class BoolParamType(ParamType):274 name = 'boolean'275276 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)285286 def __repr__(self):287 return 'BOOL'288289234class FloatParamType(ParamType):235 name = 'float'236237 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)243244 def __repr__(self):245 return 'FLOAT'246247290class UUIDParameterType(ParamType):291 name = 'uuid'292293 def convert(self, value, param, ctx):
105 unmodified lines
399 :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.pathsep415416 def __init__(self, exists=False, file_okay=True, dir_okay=True,
10 unmodified lines
427428 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 lines
461 self.path_type,462 filename_to_ui(value)463 ), param, ctx)464421 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)485486 return self.coerce_path_result(rv)487488
106 unmodified lines
modified:click/utils.py+3 added-2 removed
41 unmodified lines
42 return text_type(value)434445def 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 = False
120 unmodified lines
171 matter how badly configured the system is.172173 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.178179 In addition to that, if `colorama`_ is installed, the echo function will
3 unmodified lines
183 - add transparent handling of ANSI color codes on Windows.184 - hide ANSI codes automatically if the destination file is not a185 terminal.186186 .. _colorama: http://pypi.python.org/pypi/colorama187 .. _colorama: https://pypi.org/project/colorama/188189 .. versionchanged:: 6.0190 As of Click 6.0 the echo function will properly support unicode191 output on the windows console. Not that click does not modify
225 unmodified lines
modified:docs/_templates/sidebarintro.html+3 added-3 removed
5 unmodified lines
6</p>7<h3>Useful Links</h3>8<ul>9 <li><a href="http://click.pocoo.org/">The Click Website</a></li>10 <li><a href="http://pypi.python.org/pypi/click">click @ PyPI</a></li>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 lines
276 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`.2792. 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 lines
294 ))295 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')296 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)297 def cli(verbose, timeit_args):298 """A wrapper around Python's timeit."""299 cmdline = ['python', '-mtimeit'] + list(timeit_args)298 """A fake wrapper around Python's timeit."""299 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)300 if verbose:301 click.echo('Invoking: %s' % ' '.join(cmdline))302 call(cmdline)303
16 unmodified lines
320 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 parameters
16 unmodified lines
345346.. versionadded:: 5.0347348Starting with Click 5.0 it is possible to access the current context from349anywhere within the same through through the use of the349anywhere within the same thread through the use of the350:func:`get_current_context` function which returns it. This is primarily351useful for accessing the context bound object as well as some flags that352are 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 lines
modified:docs/arguments.rst+18 added
241 unmodified lines
242243.. click:run::244245 invoke(touch, ['--', '-foo.txt', 'bar.txt'])246247If you don't like the ``--`` marker, you can set ignore_unknown_options to248True to avoid checking unknown options:249250.. click:example::251252 @click.command(context_settings={"ignore_unknown_options": True})253 @click.argument('files', nargs=-1, type=click.Path())254 def touch(files):255 for filename in files:256 click.echo(filename)257258And from the command line:259260.. click:run::261262 invoke(touch, ['-foo.txt', 'bar.txt'])263
modified:docs/bashcomplete.rst+44 added-7 removed
11 unmodified lines
1213Bash completion is only available if a script has been installed properly,14and not executed through the ``python`` command. For information about15how to do that, see :ref:`setuptools-integration`. Also, Click currently16only supports completion for Bash.16only supports completion for Bash. Zsh support is available through Zsh's17bash completion compatibility mode.1818Currently, Bash completion is an internal feature that is not customizable.19This might be relaxed in future versions.2019What it Completes20-----------------2124Generally, the Bash completion support will complete subcommands and25parameters. Subcommands are always listed whereas parameters only if at22Generally, the Bash completion support will complete subcommands, options23and any option or argument values where the type is click.Choice.24Subcommands and choices are always listed whereas options only if at25least a dash has been provided. Example::2627 $ repo <TAB><TAB>28 clone commit copy delete setuser29 $ repo clone -<TAB><TAB>30 --deep --help --rev --shallow -r3132Additionally, custom suggestions can be provided for arguments and options with33the ``autocompletion`` parameter. ``autocompletion`` should a callback function34that returns a list of strings. This is useful when the suggestions need to be35dynamically generated at bash completion time. The callback function will be36passed 3 keyword arguments:3738- ``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.4243Here is an example of using a callback function to generate dynamic suggestions:4445.. click:example::4647 import os4849 def get_env_vars(ctx, args, incomplete):50 return os.environ.keys()5152 @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])575859Activation60----------6162In order to activate Bash completion, you need to inform Bash that
4 unmodified lines
67with dashes replaced by underscores.6869If your tool is called ``foo-bar``, then the magic variable is called70``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will45spit out the activation script which can be trivally activated.71spit out the activation script which can be trivially activated.7273For instance, to enable Bash completion for your ``foo-bar`` script, this74is what you would need to put into your ``.bashrc``::75
16 unmodified lines
9293And then you would put this into your bashrc instead::9495 . /path/to/foo-bar-complete.sh9697Zsh Compatibility98----------------99100To enable Bash completion in Zsh, add the following lines to your .zshrc:101102 autoload bashcompinit103 bashcompinit104105See https://github.com/pallets/click/issues/323 for more information on106this issue.
modified:docs/clickdoctools.py+9 added-2 removed
13 unmodified lines
14from docutils import nodes15from docutils.statemachine import ViewList1617from sphinx.domains import Domain18from sphinx.util.compat import Directive18from docutils.parsers.rst import Directive1920PY2 = sys.version_info[0] == 22122if PY2:23 text_type = unicode24else:25 text_type = str26 2728class EchoingStdin(object):2930 def __init__(self, input, output):31 self._input = input
44 unmodified lines
767778@contextlib.contextmanager79def isolation(input=None, env=None):73 if isinstance(input, unicode):80 if isinstance(input, text_type):81 input = input.encode('utf-8')82 input = StringIO(input or '')83 output = StringIO()84 sys.stdin = EchoingStdin(input, output)
198 unmodified lines
modified:docs/commands.rst+3 added-3 removed
27 unmodified lines
28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))2930 @cli.command()31 def sync():32 click.echo('Synching')32 click.echo('Syncing')3334Here is what this looks like:3536.. click:run::
379 unmodified lines
416:func:`open_file`.417418For a more complex example that also improves upon handling of the419pipelines 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>`__ in421the Click repository. It implements a pipeline based image editing tool422that has a nice internal structure for the pipelines.423424
11 unmodified lines
436you're not satisfied with the defaults.437438The default map can be nested arbitrarily for each subcommand and439provided when the script is invoked. Alternatively, it can also be440overriden at any point by commands. For instance, a top-level command could440overridden at any point by commands. For instance, a top-level command could441load the defaults from a configuration file.442443Example usage:444
114 unmodified lines
modified:docs/complex.rst+5 added-5 removed
151 unmodified lines
152One obvious way to remedy this is to store a reference to the repo in the153plugin, but then a command needs to be aware that it's attached below such a154plugin.155156There is a much better system that can built by taking advantage of the linked157nature of contexts. We know that the plugin context is linked to the context158that created our repo. Because of that, we can start a search for the last159level where the object stored by the context was a repo.156There is a much better system that can be built by taking advantage of the157linked nature of contexts. We know that the plugin context is linked to the158context that created our repo. Because of that, we can start a search for159the last level where the object stored by the context was a repo.160161Built-in support for this is provided by the :func:`make_pass_decorator`162factory, which will create decorators for us that find objects (it163internally calls into :meth:`Context.find_object`). In our case, we
45 unmodified lines
209210 @click.command()211 @pass_repo212 def cp(repo):213 click.echo(repo)213 click.echo(isinstance(repo, Repo))214215As you can see:216217.. click:run::
2 unmodified lines
modified:docs/options.rst+17 added-2 removed
14 unmodified lines
1516The most basic option is a value option. These options accept one17argument which is a value. If no type is provided, the type of the default18value 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 long20option defined; otherwise the first short one is used.19:data:`STRING`. Unless a name is explicitly specified, the name of the20parameter is the first long option defined; otherwise the first short one is21used.2223.. click:example::2425 @click.command()26 @click.option('--n', default=1)27 def dots(n):28 click.echo('.' * n)2930.. click:example::3132 # 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))3839And on the command line:4041.. click:run::42
248 unmodified lines
291 invoke(digest, args=['--hash-type=foo'])292 println()293 invoke(digest, args=['--help'])294295.. note::296297 You should only pass the choices as list or tuple. Other iterables (like298 generators) may lead to surprising results.299300.. _option-prompting:301302Prompting303---------
407 unmodified lines
modified:docs/parameters.rst+5 added-2 removed
45 unmodified lines
46 A parameter that only accepts floating point values.4748``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`.5354:data:`click.UUID`:55 A parameter that accepts UUID values. This is not automatically
10 unmodified lines
6667.. autoclass:: IntRange68 :noindex:6970.. autoclass:: FloatRange71 :noindex:7273Custom parameter types can be implemented by subclassing74:class:`click.ParamType`. For simple cases, passing a Python function that75fails with a `ValueError` is also supported, though discouraged.76
47 unmodified lines
modified:docs/python3.rst+2 added-2 removed
4 unmodified lines
56Click supports Python 3, but like all other command line utility libraries,7it suffers from the Unicode text model in Python 3. All examples in the8documentation were written so that they could run on both Python 2.x and9Python 3.3 or higher.9Python 3.4 or higher.1011At the moment, it is strongly recommended is to use Python 2 for Click11At the moment, it is strongly recommended to use Python 2 for Click12utilities unless Python 3 is a hard requirement.1314.. _python3-limitations:15
168 unmodified lines
modified:docs/quickstart.rst+11 added-11 removed
49 unmodified lines
50``pip`` first. For more information about this, see `installing pip`_.51Once you have it installed, run the ``pip`` command from above, but without52the `sudo` prefix.5354.. _installing pip: http://pip.readthedocs.org/en/latest/installing.html54.. _installing pip: https://pip.readthedocs.io/en/latest/installing.html5556Once you have virtualenv installed, just fire up a shell and create57your own environment. I usually create a project folder and a `venv`58folder within::
19 unmodified lines
78And if you want to go back to the real world, use the following command::7980 $ deactivate8182After doing this, the prompt of your shell should be as familar as before.82After doing this, the prompt of your shell should be as familiar as before.8384Now, let's move on. Enter the following command to get Click activated in your85virtualenv::86
14 unmodified lines
101Examples of Click applications can be found in the documentation as well102as in the GitHub repository together with readme files:103104* ``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>`_122123Basic Concepts124--------------125
149 unmodified lines
modified:docs/upgrading.rst+1 added-1 removed
42 unmodified lines
4344Multicommand Chaining API45`````````````````````````4647Click 3 introduced multicommand chaning. This required a change in how47Click 3 introduced multicommand chaining. This required a change in how48Click internally dispatches. Unfortunately this change was not correctly49implemented and it appeared that it was possible to provide an API that50can inform the super command about all the subcommands that will be51invoked.
49 unmodified lines
modified:docs/utils.rst+13 added-2 removed
93 unmodified lines
94 click.secho('Some more text', bg='blue', fg='white')95 click.secho('ATTENTION', blink=True, bold=True)969798.. _colorama: https://pypi.python.org/pypi/colorama98.. _colorama: https://pypi.org/project/colorama/99100Pager Support101-------------102
10 unmodified lines
113 def less():114 click.echo_via_pager('\n'.join('Line %d' % idx115 for idx in range(200)))116117If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:118119.. click:example::120 def _generate_output():121 for idx in range(50000):122 yield "Line %d\n" % idx123124 @click.command()125 def less():126 click.echo_via_pager(_generate_output())127128129Screen Clearing130---------------131132.. versionadded:: 2.0
103 unmodified lines
236237.. versionadded:: 2.0238239Click supports launching applications through :func:`launch`. This can be229used to open the default application assocated with a URL or filetype.240used to open the default application associated with a URL or filetype.241This can be used to launch web browsers or picture viewers, for instance.242In addition to this, it can also launch the file manager and automatically243select the provided file.244
165 unmodified lines
added:examples/bashcompletion/bashcompletion.py+41 added
1import click2import os345@click.group()6def cli():7 pass8910def get_env_vars(ctx, args, incomplete):11 for key in os.environ.keys():12 if incomplete in key:13 yield key141516@cli.command()17@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)18def cmd1(envvar):19 click.echo('Environment variable: %s' % envvar)20 click.echo('Value: %s' % os.environ[envvar])212223@click.group()24def group():25 pass262728def 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 user343536@group.command()37@click.argument("user", type=click.STRING, autocompletion=list_users)38def subcmd(user):39 click.echo('Chosen user is %s' % user)4041cli.add_command(group)
added:examples/bashcompletion/README+12 added
1$ bashcompletion23 bashcompletion is a simple example of an application that4 tries to autocomplete commands, arguments and options.56 This example requires Click 2.0 or higher.78Usage:910 $ pip install --editable .11 $ eval "$(_BASHCOMPLETION_COMPLETE=source bashcompletion)"12 $ bashcompletion --help
added:examples/bashcompletion/setup.py+15 added
1from setuptools import setup23setup(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
1import click234all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \5 'cyan', 'white'5 'cyan', 'white', 'bright_black', 'bright_red', \6 'bright_green', 'bright_yellow', 'bright_blue', \7 'bright_magenta', 'bright_cyan', 'bright_white'8910@click.command()11def cli():
17 unmodified lines
modified:examples/validation/validation.py+1 added-1 removed
1import click2try:3 from urllib import parser as urlparse3 from urllib import parse as urlparse4except ImportError:5 import urlparse67
37 unmodified lines
modified:tests/test_arguments.py+13 added-2 removed
104 unmodified lines
105 assert result.output == 'Hey!'106 assert result.exit_code == 0107108109def 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)114115 result = runner.invoke(foo, ['-'])116 assert result.output == '-\n'117 assert result.exit_code == 0118119120def test_file_atomics(runner):121 @click.command()122 @click.argument('output', type=click.File('wb', atomic=True))123 def inout(output):
63 unmodified lines
187 click.echo('arg:' + '|'.join(arg))188189 result = runner.invoke(cmd2, [])190 assert result.exit_code == 2180 assert 'Missing argument "arg"' in result.output191 assert 'Missing argument "ARG..."' in result.output192193194def test_missing_arg(runner):195 @click.command()
2 unmodified lines
198 click.echo('arg:' + arg)199200 result = runner.invoke(cmd, [])201 assert result.exit_code == 2191 assert 'Missing argument "arg".' in result.output202 assert 'Missing argument "ARG".' in result.output203204205def test_implicit_non_required(runner):206 @click.command()
83 unmodified lines
added:tests/test_bashcomplete.py+286 added
1# -*- coding: utf-8 -*-23import click4from click._bashcomplete import get_choices567def test_single_command():8 @click.command()9 @click.option('--local-opt')10 def cli(local_opt):11 pass1213 assert list(get_choices(cli, 'lol', [], '-')) == ['--local-opt']14 assert list(get_choices(cli, 'lol', [], '')) == []151617def test_boolean_flag():18 @click.command()19 @click.option('--shout/--no-shout', default=False)20 def cli(local_opt):21 pass2223 assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']242526def test_multi_value_option():27 @click.group()28 @click.option('--pos', nargs=2, type=float)29 def cli(local_opt):30 pass3132 @cli.command()33 @click.option('--local-opt')34 def sub(local_opt):35 pass3637 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']414243def test_multi_option():44 @click.command()45 @click.option('--message', '-m', multiple=True)46 def cli(local_opt):47 pass4849 assert list(get_choices(cli, 'lol', [], '-')) == ['--message', '-m']50 assert list(get_choices(cli, 'lol', ['-m'], '')) == []515253def test_small_chain():54 @click.group()55 @click.option('--global-opt')56 def cli(global_opt):57 pass5859 @cli.command()60 @click.option('--local-opt')61 def sub(local_opt):62 pass6364 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']686970def test_long_chain():71 @click.group('cli')72 @click.option('--cli-opt')73 def cli(cli_opt):74 pass7576 @cli.group('asub')77 @click.option('--asub-opt')78 def asub(asub_opt):79 pass8081 @asub.group('bsub')82 @click.option('--bsub-opt')83 def bsub(bsub_opt):84 pass8586 COLORS = ['red', 'green', 'blue']87 def get_colors(ctx, args, incomplete):88 for c in COLORS:89 if c.startswith(incomplete):90 yield c9192 def search_colors(ctx, args, incomplete):93 for c in COLORS:94 if incomplete in c:95 yield c9697 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 pass106107 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']121122123def test_chaining():124 @click.group('cli', chain=True)125 @click.option('--cli-opt')126 def cli(cli_opt):127 pass128129 @cli.command('asub')130 @click.option('--asub-opt')131 def asub(asub_opt):132 pass133134 @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 pass139140 @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 pass145146 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']156157158def 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 pass165166 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']171172173def 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 pass180181 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']194195 assert list(get_choices(cli, 'lol', ['--opt1', 'invalid_opt'], '-')) == ['--opt2', '--opt3']196197198def 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 pass205206 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']210211212def 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 pass218219 assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']220 assert list(get_choices(cli, 'lol', ['--shout'], '')) == ['arg1', 'arg2']221222223def 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 pass229230 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'], '')) == []234235236def 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 pass242243 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']246247248def test_variadic_argument_choice():249 @click.command()250 @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))251 def cli(local_opt):252 pass253254 assert list(get_choices(cli, 'lol', ['src1', 'src2'], '')) == ['src1', 'src2']255256257def test_long_chain_choice():258 @click.group()259 def cli():260 pass261262 @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 pass267268 @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 pass274275 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 lines
179 assert not result.exception180 assert result.output == '%s\n' % (default)181182183def 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)189190 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'194195 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'199200 result = runner.invoke(cli, [])201 assert not result.exception202 assert result.output == '%s\n' % default203204205def test_file_option(runner):206 @click.command()207 @click.option('--file', type=click.File('w'))208 def input(file):
155 unmodified lines
364 assert not result.exception365 assert result.output == '0\n'366367368def 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)373374 result = runner.invoke(cli, ['--x=5.0'])375 assert not result.exception376 assert result.output == '5.0\n'377378 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.output382383 @click.command()384 @click.option('--x', type=click.FloatRange(0, 5, clamp=True))385 def clamp(x):386 click.echo(x)387388 result = runner.invoke(clamp, ['--x=5.0'])389 assert not result.exception390 assert result.output == '5.0\n'391392 result = runner.invoke(clamp, ['--x=6.0'])393 assert not result.exception394 assert result.output == '5\n'395396 result = runner.invoke(clamp, ['--x=-1.0'])397 assert not result.exception398 assert result.output == '0\n'399400401def test_required_option(runner):402 @click.command()403 @click.option('--foo', required=True)404 def cli(foo):
6 unmodified lines
411412def test_evaluation_order(runner):413 called = []414360 def memo(ctx, value):415 def memo(ctx, param, value):416 called.append(value)417 return value418419 @click.command()
31 unmodified lines
451 'normal3',452 'normal1',453 'missing',454 ]455456457def test_hidden_option(runner):458 @click.command()459 @click.option('--nope', hidden=True)460 def cli(nope):461 click.echo(nope)462463 result = runner.invoke(cli, ['--help'])464 assert result.exit_code == 0465 assert '--nope' not in result.output466467468def test_hidden_command(runner):469 @click.group()470 def cli():471 pass472473 @cli.command(hidden=True)474 def nope():475 pass476477 result = runner.invoke(cli, ['--help'])478 assert result.exit_code == 0479 assert 'nope' not in result.output480481482def test_hidden_group(runner):483 @click.group()484 def cli():485 pass486487 @cli.group(hidden=True)488 def subgroup():489 pass490491 @subgroup.command()492 def nope():493 pass494495 result = runner.invoke(cli, ['--help'])496 assert result.exit_code == 0497 assert 'subgroup' not in result.output498 assert 'nope' not in result.output
modified:tests/test_commands.py+64 added-2 removed
1# -*- coding: utf-8 -*-2import re34import click5import pytest678def test_other_command_invoke(runner):9 @click.command()
53 unmodified lines
63 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 None697071def test_default_maps(runner):
135 unmodified lines
207 @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)213214 result = runner.invoke(cli, [])215 assert not result.exception
38 unmodified lines
254 assert result.output.splitlines() == [255 'Verbosity: 4',256 'Args: -foo|-x|--muhaha|x|y|-x',257 ]258259260def test_subcommand_naming(runner):261 @click.group()262 def cli():263 pass264265 @cli.command()266 def foo_bar():267 click.echo('foo-bar')268269 result = runner.invoke(cli, ['foo-bar'])270 assert not result.exception271 assert result.output.splitlines() == ['foo-bar']272273274def test_environment_variables(runner):275 @click.group()276 def cli():277 pass278279 @cli.command()280 @click.option('--name', envvar='CLICK_NAME')281 def foo(name):282 click.echo(name)283284 result = runner.invoke(cli, ['foo'], env={'CLICK_NAME': 'environment'})285286 assert not result.exception287 assert result.output == 'environment\n'288289290# Ensures the variables are read in the following order:291# 1. CLI292# 2. Environment293# 3. Defaults294variable_precedence_testdata = [295 (['foo', '--name=cli'], {'CLICK_NAME': 'environment'}, 'cli\n'),296 (['foo'], {'CLICK_NAME': 'environment'}, 'environment\n'),297 (['foo'], None, 'defaults\n'),298]299300301@pytest.mark.parametrize("command,environment,expected",302 variable_precedence_testdata)303def test_variable_precendence_00(runner, command, environment, expected):304 @click.group()305 def cli():306 pass307308 @cli.command()309 @click.option('--name', envvar='CLICK_NAME')310 def foo(name):311 click.echo(name)312313 defaults = {'foo': {'name': 'defaults'}}314 result = runner.invoke(cli, command, default_map=defaults, env=environment)315316 assert not result.exception317 assert result.output == expected
modified:tests/test_compat.py+5 added-4 removed
1import click2import pytest345if click.__version__ >= '3.0':6 def test_legacy_callbacks(runner):
4 unmodified lines
11 @click.option('--foo', callback=legacy_callback)12 def cli(foo):13 click.echo(foo)1414 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.output192021def test_bash_func_name():22 from click._bashcomplete import get_completion_script
3 unmodified lines
modified:tests/test_formatting.py+107 added-4 removed
72 unmodified lines
73 """7475 # 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 lines
110 def command():111 """A command.112 """113114 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 lines
144 '',145 'Options:',146 ' --help Show this message and exit.',147 ]148149150def test_formatting_usage_error(runner):151 @click.command()152 @click.argument('arg')153 def cmd(arg):154 click.echo('arg:' + arg)155156 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 ]164165166def test_formatting_usage_error_metavar_missing_arg(runner):167 """168 :author: @r-m-n169 Including attribution to #612170 """171 @click.command()172 @click.argument('arg', metavar='metavar')173 def cmd(arg):174 pass175176 result = runner.invoke(cmd, [])177 assert result.exit_code == 2178 assert result.output.splitlines() == [179 'Usage: cmd [OPTIONS] metavar',180 'Try "cmd --help" for help.',181 '',182 'Error: Missing argument "metavar".'183 ]184185186def test_formatting_usage_error_metavar_bad_arg(runner):187 @click.command()188 @click.argument('arg', type=click.INT, metavar='metavar')189 def cmd(arg):190 pass191192 result = runner.invoke(cmd, ['3.14'])193 assert result.exit_code == 2194 assert result.output.splitlines() == [195 'Usage: cmd [OPTIONS] metavar',196 'Try "cmd --help" for help.',197 '',198 'Error: Invalid value for "metavar": 3.14 is not a valid integer'199 ]200201202def test_formatting_usage_error_nested(runner):203 @click.group()204 def cmd():205 pass206207 @cmd.command()208 @click.argument('bar')209 def foo(bar):210 click.echo('foo:' + bar)211212 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 ]220221222def 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)227228 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 ]235236237def 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)242243 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 lines
3132ALLOWED_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])3738if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',
7 unmodified lines
4748 if sys.version_info[0] != 2:49 rv = rv.decode('utf-8')50 imported = json.loads(rv)51 print(imported)5152 for module in imported:53 if module == 'click' or module.startswith('click.'):54 continue
1 unmodified line
modified:tests/test_options.py+81 added-2 removed
82 unmodified lines
83 assert not result.exception84 assert result.output == 'verbosity=0\n'8586 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 None888990@pytest.mark.parametrize('unknown_flag', ['--foo', '-f'])91def test_unknown_options(runner, unknown_flag):
105 unmodified lines
197 assert not result.exception198 assert result.output == 'x|1\ny|2\n'199200201def test_show_envvar(runner):202 @click.command()203 @click.option('--arg1', envvar='ARG1',204 show_envvar=True)205 def cmd(arg):206 pass207208 result = runner.invoke(cmd, ['--help'])209 assert not result.exception210 assert 'ARG1' in result.output211212213def test_show_envvar_auto_prefix(runner):214 @click.command()215 @click.option('--arg1', show_envvar=True)216 def cmd(arg):217 pass218219 result = runner.invoke(cmd, ['--help'],220 auto_envvar_prefix='TEST')221 assert not result.exception222 assert 'TEST_ARG1' in result.output223224225def 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 lines
334 assert 'I am a help text' in result.output335 assert 'you wont see me' not in result.output336337338def test_option_custom_class_reusable(runner):339 """Ensure we can reuse a custom class option. See Issue #926"""340341 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')345346 # Assign to a variable to re-use the decorator.347 testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')348349 @click.command()350 @testoption351 def cmd1(testoption):352 click.echo(testoption)353354 @click.command()355 @testoption356 def cmd2(testoption):357 click.echo(testoption)358359 # Both of the commands should have the --help option now.360 for cmd in (cmd1, cmd2):361362 result = runner.invoke(cmd, ['--help'])363 assert 'I am a help text' in result.output364 assert 'you wont see me' not in result.output365366367def test_aliases_for_flags(runner):368 @click.command()369 @click.option('--warnings/--no-warnings', ' /-W', default=True)370 def cli(warnings):
16 unmodified lines
387 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'391392@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])404def test_option_names(runner, option_args, expected):405406 @click.command()407 @click.option(*option_args, is_flag=True)408 def cmd(**kwargs):409 click.echo(str(kwargs[expected]))410411 assert cmd.params[0].name == expected412413 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
1import click2import time345class FakeClock(object):6 def __init__(self):7 self.now = time.time()89 def advance_time(self, seconds=1):10 self.now += seconds1112 def time(self):13 return self.now141516def test_progressbar_strip_regression(runner, monkeypatch):17 fake_clock = FakeClock()18 label = ' padded line'1920 @click.command()21 def cli():22 with click.progressbar(tuple(range(10)), label=label) as progress:23 for thing in progress:11 pass24 fake_clock.advance_time()2526 monkeypatch.setattr(time, 'time', fake_clock.time)27 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)28 assert label in runner.invoke(cli, []).output2930
19 unmodified lines
50 @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)5556 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)57 result = runner.invoke(cli, [])58 assert result.exception is None596061def test_progressbar_hidden(runner, monkeypatch):62 label = 'whatever'6364 @click.command()65 def cli():66 with click.progressbar(tuple(range(10)), label=label) as progress:67 for thing in progress:68 pass6970 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)71 assert runner.invoke(cli, []).output == ''727374def 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 pass8081 @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 pass8687 result = runner.invoke(cli_with_choices, [], input='none')88 assert '(none, day, week, month)' in result.output8990 result = runner.invoke(cli_without_choices, [], input='none')91 assert '(none, day, week, month)' not in result.output929394def test_secho(runner):95 with runner.isolation() as outstreams:96 click.secho(None, nl=False)97 bytes = outstreams[0].getvalue()98 assert bytes == b''99100101def test_progressbar_yields_all_items(runner):102 with click.progressbar(range(3)) as progress:103 assert len(list(progress)) == 3104105106def test_progressbar_update(runner, monkeypatch):107 fake_clock = FakeClock()108109 @click.command()110 def cli():111 with click.progressbar(range(4)) as progress:112 for _ in progress:113 fake_clock.advance_time()114 print("")115116 monkeypatch.setattr(time, 'time', fake_clock.time)117 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)118 output = runner.invoke(cli, []).output119120 lines = [line for line in output.split('\n') if '[' in line]121122 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
1import os2import sys34import pytest5import click
177 unmodified lines
183184 result = runner.invoke(cli_no_error)185 assert result.exit_code == 0186 assert result.output == 'hello world\n'187188189def test_env():190 @click.command()191 def cli_env():192 click.echo('ENV=%s' % os.environ['TEST_CLICK_ENV'])193194 runner = CliRunner()195196 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'203204 assert os.environ == env_orig205206207def test_stderr():208 @click.command()209 def cli_stderr():210 click.echo("stdout")211 click.echo("stderr", err=True)212213 runner = CliRunner(mix_stderr=False)214215 result = runner.invoke(cli_stderr)216217 assert result.output == 'stdout\n'218 assert result.stdout == 'stdout\n'219 assert result.stderr == 'stderr\n'220221 runner_mix = CliRunner(mix_stderr=True)222 result_mix = runner_mix.invoke(cli_stderr)223224 assert result_mix.output == 'stdout\nstderr\n'225 assert result_mix.stdout == 'stdout\nstderr\n'226227 with pytest.raises(ValueError):228 result_mix.stderr229230231@pytest.mark.parametrize('args, expected_output', [232 (None, 'bar\n'),233 ([], 'bar\n'),234 ('', 'bar\n'),235 (['--foo', 'one two'], 'one two\n'),236 ('--foo "one two"', 'one two\n'),237])238def test_args(args, expected_output):239240 @click.command()241 @click.option('--foo', default='bar')242 def cli_args(foo):243 click.echo(foo)244245 runner = CliRunner()246 result = runner.invoke(cli_args, args=args)247 assert result.exit_code == 0248 assert result.output == expected_output249250251def test_setting_prog_name_in_extra():252 @click.command()253 def cli():254 click.echo("ok")255256 runner = CliRunner()257 result = runner.invoke(cli, prog_name="foobar")258 assert not result.exception259 assert result.output == 'ok\n'
modified:tests/test_utils.py+37 added-14 removed
8 unmodified lines
9from click._compat import WIN, PY2101112def test_echo(runner):13 with runner.isolation() as out:13 with runner.isolation() as outstreams:14 click.echo(u'\N{SNOWMAN}')15 click.echo(b'\x44\x44')16 click.echo(42, nl=False)17 click.echo(b'a', nl=False)18 click.echo('\x1b[31mx\x1b[39m', nl=False)19 bytes = out.getvalue().replace(b'\r\n', b'\n')19 bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')20 assert bytes == b'\xe2\x98\x83\nDD\n42ax'2122 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 3
10 unmodified lines
34 @click.command()35 def cli():36 click.echo(b'\xf6')37 result = runner.invoke(cli, [])38 assert result.output_bytes == b'\xf6\n'38 assert result.stdout_bytes == b'\xf6\n'3940 # Ensure we do not strip for bytes.41 with runner.isolation() as out:41 with runner.isolation() as outstreams:42 click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)43 assert out.getvalue() == b'\x1b[31mx\x1b[39m'43 assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'444546def test_echo_custom_file():47 import io
97 unmodified lines
145 out, err = capsys.readouterr()146 assert out == 'Password: \nScrew you.\n'147148149def _test_gen_func():150 yield 'a'151 yield 'b'152 yield 'c'153 yield 'abc'154155156@pytest.mark.skipif(WIN, reason='Different behavior on windows.')157@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])158@pytest.mark.parametrize('test', [159 # We need lambda here, because pytest will160 # reuse the parameters, and then the generators161 # are already used and will not yield anymore162 ('just text\n', lambda: 'just text'),163 ('iterable\n', lambda: ["itera", "ble"]),164 ('abcabc\n', lambda: _test_gen_func),165 ('abcabc\n', lambda: _test_gen_func()),166 ('012345\n', lambda: (c for c in range(6))),167])151def test_echo_via_pager(monkeypatch, capfd, cat):168def test_echo_via_pager(monkeypatch, capfd, cat, test):169 monkeypatch.setitem(os.environ, 'PAGER', cat)170 monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)171172 expected_output = test[0]173 test_input = test[1]()174154 click.echo_via_pager('haha')175 click.echo_via_pager(test_input)176177 out, err = capfd.readouterr()156 assert out == 'haha\n'178 assert out == expected_output179180181@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')182def test_echo_color_flag(monkeypatch, capfd):
106 unmodified lines
289def test_iter_keepopenfile(tmpdir):290 expected = list(map(str, range(10)))291 p = tmpdir.mkdir('testdir').join('testfile')292 p.write(os.linesep.join(expected))271 f = p.open()272 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):273 assert e_line == a_line.strip()293 with p.open() as f:294 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):295 assert e_line == a_line.strip()296297298@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')299def test_iter_lazyfile(tmpdir):300 expected = list(map(str, range(10)))301 p = tmpdir.mkdir('testdir').join('testfile')302 p.write(os.linesep.join(expected))303 with p.open() as f:281 f = p.open()282 for e_line, a_line in zip(expected, click.utils.LazyFile(f.name)):283 assert e_line == a_line.strip()304 with click.utils.LazyFile(f.name) as lf:305 for e_line, a_line in zip(expected, lf):306 assert e_line == a_line.strip()
modified:CHANGES+74 added-2 removed
5 unmodified lines
6Version 7.07-----------89(upcoming release with new features, release date to be decided)1010- 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.4344Version 6.845-----------4647(bugfix release; yet to be released)4849- 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.5859Version 6.760-----------6162(bugfix release; released on January 6th 2017)6364- 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.6970Version 6.671-----------7273(bugfix release; released on April 4th 2016)7475- Fix bug in `click.Path` where it would crash when passed a `-`. See #551.7677Version 6.478-----------7980(bugfix release; released on March 24th 2016)8182- Fix bug in bash completion where click would discard one or more trailing83 arguments. See #471.8485Version 6.386-----------8716(bugfix release; unreleased)88(bugfix release; released on February 22 2016)8990- 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 lines
modified:CONTRIBUTING.rst+6 added-1 removed
30 unmodified lines
3132- 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.3435- For features: Consider whether your feature would be a better fit for an36 `external package <http://click.pocoo.org/contrib/>`_3738- For bugfixes: Submit against the latest maintenance branch instead of master!3940Running the testsuite41---------------------4243You probably want to set up a `virtualenv39<http://virtualenv.readthedocs.org/en/latest/index.html>`_.44<https://virtualenv.readthedocs.io/en/latest/index.html>`_.4546The minimal requirement for running the testsuite is ``py.test``. You can47install it with::48
13 unmodified lines
modified:Makefile+1 added-1 removed
1test:2 @cd tests; PYTHONPATH=.. py.test --tb=short2 @cd tests; PYTHONPATH=.. pytest --tb=short34upload-docs:5 $(MAKE) -C docs dirhtml6 rsync -a docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/click.pocoo.org/static/
5 unmodified lines
added:README.rst+92 added
1\$ click\_2==========34What's Click?5-------------67Click is a Python package for creating beautiful command line interfaces8in a composable way with as little code as necessary. It's the "Command9Line Interface Creation Kit". It's highly configurable but comes with10sensible defaults out of the box.1112It aims to make the process of writing command line tools quick and fun13while also preventing any frustration caused by the inability to implement14an intended CLI API.1516Click in three points:17 - arbitrary nesting of commands18 - automatic help page generation19 - supports lazy loading of subcommands at runtime202122Installing23----------2425Install and update using `pip`_:2627.. code-block:: text2829 $ pip install click3031A Simple Example32----------------3334What does it look like? Here is an example of a simple Click program:3536.. code-block:: python3738 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()5152And what it looks like when run:5354.. code-block:: text5556 $ python hello.py --count=357 Your name: John58 Hello John!59 Hello John!60 Hello John!6162Donate63------6465The Pallets organization develops and supports Flask and the libraries66it uses. In order to grow the community of contributors and users, and67allow the maintainers to devote more time to the projects, `please68donate today`_.6970.. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=20717273Links74-----7576* 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:8384 * Linux, Mac: https://travis-ci.org/pallets/click85 * Windows: https://ci.appveyor.com/project/pallets/click8687* Test coverage: https://codecov.io/gh/pallets/click8889.. _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]2universal=134[metadata]5license_file = LICENSE67[tool:pytest]8addopts = -p no:warnings --tb=short
modified:setup.py+27 added-6 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import io4import re2import ast5from setuptools import setup678_version_re = re.compile(r'__version__\s+=\s+(.*)')9109with open('click/__init__.py', 'rb') as f:10 version = str(ast.literal_eval(_version_re.search(11 f.read().decode('utf-8')).group(1)))11with io.open('README.rst', 'rt', encoding='utf8') as f:12 readme = f.read()1314with io.open('click/__init__.py', 'rt', encoding='utf8') as f:15 version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)1617setup(18 name='click',19 version=version,20 url='https://www.palletsprojects.com/p/click/',21 author='Armin Ronacher',22 author_email='armin.ronacher@active-4.com',18 version=version,19 url='http://github.com/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]2envlist = py26,py27,py33,py34,pypy2envlist = py27,py34,py35,py36,pypy3skip_missing_interpreters = true45[testenv]6passenv = LANG6commands = make test7commands = {env:TEST_RUNNER:pytest} {posargs}8deps =8 colorama9 pytest10whitelist_externals = make10 colorama: colorama11 coverage: coverage12setenv =13 coverage: TEST_RUNNER=coverage run -m pytest