Merge branch 'master' into bright-colors
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Dan Sully · committed by GitHub · parents eb4598f, 789ba88 · Browse files · 51 files·+831 added−274 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
51 files+831 added−274 removed
- tests:+271 added−45 removed
- other:+560 added−229 removed
Provenance
- Commit
c0ccf30- Tree
ea94284- Author
Dan Sully <daniel-github@electricrain.com>- Committer
GitHub <noreply@github.com>- Parent 1
eb4598f- Parent 2
789ba88
51 files changed+831 added−274 removed
modified:.ci/appveyor.yml+16 added
30 unmodified lines31323334353637383940414243444546474849505152535412 unmodified lines30 unmodified lines - PYTHON: "C:\\Python34-x64" PYTHON_VERSION: "3.4.x" PYTHON_ARCH: "64"
- PYTHON: "C:\\Python35" PYTHON_VERSION: "3.5.x" PYTHON_ARCH: "32"
- PYTHON: "C:\\Python35-x64" PYTHON_VERSION: "3.5.x" PYTHON_ARCH: "64"
- PYTHON: "C:\\Python36" PYTHON_VERSION: "3.6.x" PYTHON_ARCH: "32"
- PYTHON: "C:\\Python36-x64" PYTHON_VERSION: "3.6.x" PYTHON_ARCH: "64"
branches: only: - master
12 unmodified linesmodified:click/__init__.py+1 added-1 removed
64 unmodified lines65 'version_option', 'help_option',66 67 # Types68 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple', 'STRING',69- 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED', 'FloatRange'69+ 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED', 'FloatRange',70 71 # Utilities72 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',73 'format_filename', 'get_app_dir', 'get_os_args',25 unmodified linesmodified:click/_bashcomplete.py+56 added-42 removed
43 unmodified lines44 """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: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(args_remaining[0], args_remaining[1:], parent=ctx, resilient_parsing=True)53- args_remaining = ctx.protected_args + ctx.args54- else:55- ctx = ctx.parent48+ if isinstance(ctx.command, MultiCommand):49+ cmd = ctx.command.get_command(ctx, args_remaining[0])50+ if cmd is None:51+ return None52+ ctx = cmd.make_context(53+ args_remaining[0], args_remaining[1:], parent=ctx, resilient_parsing=True)54+ args_remaining = ctx.protected_args + ctx.args55+ else:56+ ctx = ctx.parent57 58 return ctx59 60+61 def start_of_option(param_str):62 """63 :param param_str: param_str to check64 :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")8 unmodified lines73 :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])):11 unmodified lines94 :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:2 unmodified lines106 and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:107 return True108 return False109 110+111 def get_user_autocompletions(ctx, args, incomplete, cmd_param):112 """113 :param ctx: context associated with the parsed command114 :param args: full list of args1 unmodified line116 :param cmd_param: command definition117 :return: all the possible user-specified completions for the param118 """119 if isinstance(cmd_param.type, Choice):113- return cmd_param.type.choices120+ return [c for c in cmd_param.type.choices if c.startswith(incomplete)]121 elif cmd_param.autocompletion is not None:122 return cmd_param.autocompletion(ctx=ctx,123 args=args,124 incomplete=incomplete)125 else:126 return []127 128+129+def add_subcommand_completions(ctx, incomplete, completions_out):130+ # Add subcommand completions.131+ if isinstance(ctx.command, MultiCommand):132+ completions_out.extend(133+ [c for c in ctx.command.list_commands(ctx) if c.startswith(incomplete)])134+135+ # Walk up the context list and add any other completion possibilities from chained commands136+ while ctx.parent is not None:137+ ctx = ctx.parent138+ if isinstance(ctx.command, MultiCommand) and ctx.command.chain:139+ remaining_commands = sorted(140+ set(ctx.command.list_commands(ctx)) - set(ctx.protected_args))141+ completions_out.extend(142+ [c for c in remaining_commands if c.startswith(incomplete)])143+144+145 def get_choices(cli, prog_name, args, incomplete):146 """147 :param cli: command definition148 :param prog_name: the program that is running4 unmodified lines153 all_args = copy.deepcopy(args)154 155 ctx = resolve_ctx(cli, prog_name, args)156 if ctx is None:133- return157+ return []158 159 # In newer versions of bash long opts with '='s are partitioned, but it's easier to parse160 # without the '='161 if start_of_option(incomplete) and WORDBREAK in incomplete:2 unmodified lines164 incomplete = partition_incomplete[2]165 elif incomplete == WORDBREAK:166 incomplete = ''167 144- choices = []145- found_param = False168+ completions = []169 if start_of_option(incomplete):147- # completions for options170+ # completions for partial options171 for param in ctx.command.params:172 if isinstance(param, Option):150- choices.extend([param_opt for param_opt in param.opts + param.secondary_opts151- if param_opt not in all_args or param.multiple])152- found_param = True153- if not found_param:154- # completion for option values by choices155- for cmd_param in ctx.command.params:156- if isinstance(cmd_param, Option) and is_incomplete_option(all_args, cmd_param):157- choices.extend(get_user_autocompletions(ctx, all_args, incomplete, cmd_param))158- found_param = True159- break160- if not found_param:161- # completion for argument values by choices162- for cmd_param in ctx.command.params:163- if isinstance(cmd_param, Argument) and is_incomplete_argument(ctx.params, cmd_param):164- choices.extend(get_user_autocompletions(ctx, all_args, incomplete, cmd_param))165- found_param = True166- break173+ param_opts = [param_opt for param_opt in param.opts +174+ param.secondary_opts if param_opt not in all_args or param.multiple]175+ completions.extend(176+ [c for c in param_opts if c.startswith(incomplete)])177+ return completions178+ # completion for option values from user supplied values179+ for param in ctx.command.params:180+ if is_incomplete_option(all_args, param):181+ return get_user_autocompletions(ctx, all_args, incomplete, param)182+ # completion for argument values from user supplied values183+ for param in ctx.command.params:184+ if is_incomplete_argument(ctx.params, param):185+ completions.extend(get_user_autocompletions(186+ ctx, all_args, incomplete, param))187+ # Stop looking for other completions only if this argument is required.188+ if param.required:189+ return completions190+ break191 168- if not found_param and isinstance(ctx.command, MultiCommand):169- # completion for any subcommands170- choices.extend(ctx.command.list_commands(ctx))192+ add_subcommand_completions(ctx, incomplete, completions)193+ return completions194 172- if not start_of_option(incomplete) and ctx.parent is not None and isinstance(ctx.parent.command, MultiCommand) and ctx.parent.command.chain:173- # completion for chained commands174- remaining_comands = set(ctx.parent.command.list_commands(ctx.parent))-set(ctx.parent.protected_args)175- choices.extend(remaining_comands)195 177- for item in choices:178- if item.startswith(incomplete):179- yield item180-181-196 def do_complete(cli, prog_name):197 cwords = split_arg_string(os.environ['COMP_WORDS'])198 cword = int(os.environ['COMP_CWORD'])199 args = cwords[1:cword]18 unmodified linesmodified:click/_compat.py+64 added-21 removed
10 unmodified lines11 CYGWIN = sys.platform.startswith('cygwin')12 DEFAULT_COLUMNS = 8013 14 15-_ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')15+_ansi_re = re.compile(r'\033\[((?:\d|;)*)([a-zA-Z])')16 17 18 def get_filesystem_encoding():19 return sys.getfilesystemencoding() or sys.getdefaultencoding()20 21 22-def _make_text_stream(stream, encoding, errors):22+def _make_text_stream(stream, encoding, errors,23+ force_readable=False, force_writable=False):24 if encoding is None:25 encoding = get_best_encoding(stream)26 if errors is None:27 errors = 'replace'28 return _NonClosingTextIOWrapper(stream, encoding, errors,28- line_buffering=True)29+ line_buffering=True,30+ force_readable=force_readable,31+ force_writable=force_writable)32 33 34 def is_ascii_encoding(encoding):35 """Checks if a given encoding is ascii."""12 unmodified lines48 49 50 class _NonClosingTextIOWrapper(io.TextIOWrapper):51 49- def __init__(self, stream, encoding, errors, **extra):50- self._stream = stream = _FixupStream(stream)52+ def __init__(self, stream, encoding, errors,53+ force_readable=False, force_writable=False, **extra):54+ self._stream = stream = _FixupStream(stream, force_readable,55+ force_writable)56 io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)57 58 # The io module is a place where the Python 3 text behavior59 # was forced upon Python 2, so we need to unbreak26 unmodified lines86 class _FixupStream(object):87 """The new io interface needs more from streams than streams88 traditionally implement. As such, this fix-up code is necessary in89 some circumstances.90+91+ The forcing of readable and writable flags are there because some tools92+ put badly patched objects on sys (one such offender are certain version93+ of jupyter notebook).94 """95 87- def __init__(self, stream):96+ def __init__(self, stream, force_readable=False, force_writable=False):97 self._stream = stream98+ self._force_readable = force_readable99+ self._force_writable = force_writable100 101 def __getattr__(self, name):102 return getattr(self._stream, name)103 8 unmodified lines112 return self._stream.readline(size)113 return self._stream.read(size)114 115 def readable(self):116+ if self._force_readable:117+ return True118 x = getattr(self._stream, 'readable', None)119 if x is not None:120 return x()121 try:2 unmodified lines124 return False125 return True126 127 def writable(self):128+ if self._force_writable:129+ return True130 x = getattr(self._stream, 'writable', None)131 if x is not None:132 return x()133 try:47 unmodified lines181 # There are also Windows environments where the `msvcrt` module is not182 # available (which is why we use try-catch instead of the WIN variable183 # here), such as the Google App Engine development server on Windows. In184 # those cases there is just nothing we can do.185+ def set_binary_mode(f):186+ return f187+188 try:189 import msvcrt172- except ImportError:173- set_binary_mode = lambda x: x174- else:190+191 def set_binary_mode(f):192 try:193 fileno = f.fileno()194 except Exception:195 pass196 else:197 msvcrt.setmode(fileno, os.O_BINARY)198 return f199+ except ImportError:200+ pass201 202+ try:203+ import fcntl204+205+ def set_binary_mode(f):206+ try:207+ fileno = f.fileno()208+ except Exception:209+ pass210+ else:211+ flags = fcntl.fcntl(fileno, fcntl.F_GETFL)212+ fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)213+ return f214+ except ImportError:215+ pass216+217 def isidentifier(x):218 return _identifier_re.search(x) is not None219 220 def get_binary_stdin():8 unmodified lines229 def get_text_stdin(encoding=None, errors=None):230 rv = _get_windows_console_stream(sys.stdin, encoding, errors)231 if rv is not None:232 return rv200- return _make_text_stream(sys.stdin, encoding, errors)233+ return _make_text_stream(sys.stdin, encoding, errors,234+ force_readable=True)235 236 def get_text_stdout(encoding=None, errors=None):237 rv = _get_windows_console_stream(sys.stdout, encoding, errors)238 if rv is not None:239 return rv206- return _make_text_stream(sys.stdout, encoding, errors)240+ return _make_text_stream(sys.stdout, encoding, errors,241+ force_writable=True)242 243 def get_text_stderr(encoding=None, errors=None):244 rv = _get_windows_console_stream(sys.stderr, encoding, errors)245 if rv is not None:246 return rv212- return _make_text_stream(sys.stderr, encoding, errors)247+ return _make_text_stream(sys.stderr, encoding, errors,248+ force_writable=True)249 250 def filename_to_ui(value):251 if isinstance(value, bytes):252 value = value.decode(get_filesystem_encoding(), 'replace')83 unmodified lines336 return stream_encoding is not None337 338 return False339 304- def _force_correct_text_reader(text_reader, encoding, errors):340+ def _force_correct_text_reader(text_reader, encoding, errors,341+ force_readable=False):342 if _is_binary_reader(text_reader, False):343 binary_reader = text_reader344 else:345 # If there is no target encoding set, we need to verify that the17 unmodified lines363 # because nobody handles those errors anyways and at this point364 # we're so fundamentally fucked that nothing can repair it.365 if errors is None:366 errors = 'replace'330- return _make_text_stream(binary_reader, encoding, errors)367+ return _make_text_stream(binary_reader, encoding, errors,368+ force_readable=force_readable)369 332- def _force_correct_text_writer(text_writer, encoding, errors):370+ def _force_correct_text_writer(text_writer, encoding, errors,371+ force_writable=False):372 if _is_binary_writer(text_writer, False):373 binary_writer = text_writer374 else:375 # If there is no target encoding set, we need to verify that the17 unmodified lines393 # because nobody handles those errors anyways and at this point394 # we're so fundamentally fucked that nothing can repair it.395 if errors is None:396 errors = 'replace'358- return _make_text_stream(binary_writer, encoding, errors)397+ return _make_text_stream(binary_writer, encoding, errors,398+ force_writable=force_writable)399 400 def get_binary_stdin():401 reader = _find_binary_reader(sys.stdin)402 if reader is None:18 unmodified lines421 def get_text_stdin(encoding=None, errors=None):422 rv = _get_windows_console_stream(sys.stdin, encoding, errors)423 if rv is not None:424 return rv385- return _force_correct_text_reader(sys.stdin, encoding, errors)425+ return _force_correct_text_reader(sys.stdin, encoding, errors,426+ force_readable=True)427 428 def get_text_stdout(encoding=None, errors=None):429 rv = _get_windows_console_stream(sys.stdout, encoding, errors)430 if rv is not None:431 return rv391- return _force_correct_text_writer(sys.stdout, encoding, errors)432+ return _force_correct_text_writer(sys.stdout, encoding, errors,433+ force_writable=True)434 435 def get_text_stderr(encoding=None, errors=None):436 rv = _get_windows_console_stream(sys.stderr, encoding, errors)437 if rv is not None:438 return rv397- return _force_correct_text_writer(sys.stderr, encoding, errors)439+ return _force_correct_text_writer(sys.stderr, encoding, errors,440+ force_writable=True)441 442 def filename_to_ui(value):443 if isinstance(value, bytes):444 value = value.decode(get_filesystem_encoding(), 'replace')20 unmodified lines465 atomic=False):466 # Standard streams first. These are simple because they don't need467 # special handling for the atomic flag. It's entirely ignored.468 if filename == '-':426- if 'w' in mode:469+ if any(m in mode for m in ['w', 'a', 'x']):470 if 'b' in mode:471 return get_binary_stdout(), False472 return get_text_stdout(encoding=encoding, errors=errors), False473 if 'b' in mode:31 unmodified lines505 f = io.open(fd, mode, encoding=encoding, errors=errors)506 else:507 f = os.fdopen(fd, mode)508 466- return _AtomicFile(f, tmp_filename, filename), True509+ return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True510 511 512 # Used in a destructor call, needs extra protection from interpreter cleanup.513 if hasattr(os, 'replace'):181 unmodified linesmodified:click/_termui_impl.py+51 added-48 removed
11 unmodified lines12 import os13 import sys14 import time15 import math16+17 from ._compat import _default_text_stdout, range_type, PY2, isatty, \18 open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \19 CYGWIN20 from .utils import echo171 unmodified lines192 }).rstrip()193 194 def render_progress(self):195 from .termui import get_terminal_size195- nl = False196 197 if self.is_hidden:198- buf = [self.label]199- nl = True200- else:201- buf = []202- # Update width in case the terminal has been resized203- if self.autowidth:204- old_width = self.width205- self.width = 0206- clutter_length = term_len(self.format_progress_line())207- new_width = max(0, get_terminal_size()[0] - clutter_length)208- if new_width < old_width:209- buf.append(BEFORE_BAR)210- buf.append(' ' * self.max_width)211- self.max_width = new_width212- self.width = new_width198+ return199 214- clear_width = self.width215- if self.max_width is not None:216- clear_width = self.max_width200+ buf = []201+ # Update width in case the terminal has been resized202+ if self.autowidth:203+ old_width = self.width204+ self.width = 0205+ clutter_length = term_len(self.format_progress_line())206+ new_width = max(0, get_terminal_size()[0] - clutter_length)207+ if new_width < old_width:208+ buf.append(BEFORE_BAR)209+ buf.append(' ' * self.max_width)210+ self.max_width = new_width211+ self.width = new_width212 218- buf.append(BEFORE_BAR)219- line = self.format_progress_line()220- line_len = term_len(line)221- if self.max_width is None or self.max_width < line_len:222- self.max_width = line_len223- buf.append(line)213+ clear_width = self.width214+ if self.max_width is not None:215+ clear_width = self.max_width216 225- buf.append(' ' * (clear_width - line_len))226- line = ''.join(buf)217+ buf.append(BEFORE_BAR)218+ line = self.format_progress_line()219+ line_len = term_len(line)220+ if self.max_width is None or self.max_width < line_len:221+ self.max_width = line_len222 223+ buf.append(line)224+ buf.append(' ' * (clear_width - line_len))225+ line = ''.join(buf)226 # Render the line only if it changed.227 if line != self._last_line:228 self._last_line = line231- echo(line, file=self.file, color=self.color, nl=nl)229+ echo(line, file=self.file, color=self.color, nl=True)230 self.file.flush()231 232 def make_step(self, n_steps):233 self.pos += n_steps35 unmodified lines269 __next__ = next270 del next271 272 275-def pager(text, color=None):273+def pager(generator, color=None):274 """Decide what method to use for paging through text."""275 stdout = _default_text_stdout()276 if not isatty(sys.stdin) or not isatty(stdout):279- return _nullpager(stdout, text, color)277+ return _nullpager(stdout, generator, color)278 pager_cmd = (os.environ.get('PAGER', None) or '').strip()279 if pager_cmd:280 if WIN:283- return _tempfilepager(text, pager_cmd, color)284- return _pipepager(text, pager_cmd, color)281+ return _tempfilepager(generator, pager_cmd, color)282+ return _pipepager(generator, pager_cmd, color)283 if os.environ.get('TERM') in ('dumb', 'emacs'):286- return _nullpager(stdout, text, color)284+ return _nullpager(stdout, generator, color)285 if WIN or sys.platform.startswith('os2'):288- return _tempfilepager(text, 'more <', color)286+ return _tempfilepager(generator, 'more <', color)287 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:290- return _pipepager(text, 'less', color)288+ return _pipepager(generator, 'less', color)289 290 import tempfile291 fd, filename = tempfile.mkstemp()292 os.close(fd)293 try:294 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:297- return _pipepager(text, 'more', color)298- return _nullpager(stdout, text, color)295+ return _pipepager(generator, 'more', color)296+ return _nullpager(stdout, generator, color)297 finally:298 os.unlink(filename)299 300 303-def _pipepager(text, cmd, color):301+def _pipepager(generator, cmd, color):302 """Page through text by feeding it to another program. Invoking a303 pager through this might support colors.304 """305 import subprocess9 unmodified lines315 color = True316 elif 'r' in less_flags or 'R' in less_flags:317 color = True318 321- if not color:322- text = strip_ansi(text)323-319 c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,320 env=env)321 encoding = get_best_encoding(c.stdin)322 try:328- c.stdin.write(text.encode(encoding, 'replace'))329- c.stdin.close()323+ for text in generator:324+ if not color:325+ text = strip_ansi(text)326+327+ c.stdin.write(text.encode(encoding, 'replace'))328 except (IOError, KeyboardInterrupt):329 pass330+ else:331+ c.stdin.close()332 333 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting334 # search or other commands inside less).335 #10 unmodified lines346 else:347 break348 349 350-def _tempfilepager(text, cmd, color):350+def _tempfilepager(generator, cmd, color):351 """Page through text by invoking a program on a temporary file."""352 import tempfile353 filename = tempfile.mktemp()354+ # TODO: This never terminates if the passed generator never terminates.355+ text = "".join(generator)356 if not color:357 text = strip_ansi(text)358 encoding = get_best_encoding(sys.stdout)359 with open_stream(filename, 'wb')[0] as f:3 unmodified lines363 finally:364 os.unlink(filename)365 366 365-def _nullpager(stream, text, color):367+def _nullpager(stream, generator, color):368 """Simply print unformatted text. This is the ultimate fallback."""369+ for text in generator:367- if not color:368- text = strip_ansi(text)369- stream.write(text)370+ if not color:371+ text = strip_ansi(text)372+ stream.write(text)373 374 375 class Editor(object):376 183 unmodified linesmodified:click/_unicodefun.py+6 added-3 removed
60 unmodified lines61 62 extra = ''63 if os.name == 'posix':64 import subprocess65+ try:65- rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,66- stderr=subprocess.PIPE).communicate()[0]66+ rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,67+ stderr=subprocess.PIPE).communicate()[0]68+ except OSError:69+ rv = b''70 good_locales = set()71 has_c_utf8 = False72 73 # Make sure we're operating on text here.44 unmodified lines118 ) % bad_locale119 120 raise RuntimeError('Click will abort further execution because Python 3 '121 'was configured to use ASCII as encoding for the '119- 'environment. Consult http://click.pocoo.org/python3/'122+ 'environment. Consult http://click.pocoo.org/python3/ '123 'for mitigation steps.' + extra)modified:click/core.py+16 added-9 removed
57 unmodified lines58 'that is in chain mode. This is not supported'59 raise RuntimeError('%s. Command "%s" is set to chain and "%s" was '60 'added as subcommand but it in itself is a '61 'multi command. ("%s" is a %s within a chained '62- '%s named "%s"). This restriction was supposed to '63- 'be lifted in 6.0 but the fix was flawed. This '64- 'will be fixed in Click 7.0' % (62+ '%s named "%s").' % (63 hint, base_command.name, cmd_name,64 cmd_name, cmd.__class__.__name__,65 base_command.__class__.__name__,66 base_command.name))311 unmodified lines378 379 @property380 def meta(self):381 """This is a dictionary which is shared with all the contexts384- that are nested. It exists so that click utiltiies can store some382+ that are nested. It exists so that click utilities can store some383 state here if they need to. It is however the responsibility of384 that code to manage this dictionary well.385 386 The keys are supposed to be unique dotted strings. For instance438 unmodified lines825 826 def make_parser(self, ctx):827 """Creates the underlying option parser for this command."""828 parser = OptionParser(ctx)831- parser.allow_interspersed_args = ctx.allow_interspersed_args832- 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 392 unmodified lines1225 return sorted(rv)1226 1227 1228 class Parameter(object):1233- """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 91 unmodified lines1325 1326 def add_to_parser(self, parser, ctx):1327 pass1328 1329+1330 def consume_value(self, ctx, opts):1331 value = opts.get(self.name)1332 if value is None:1336- value = ctx.lookup_default(self.name)1337- if value is None:1333 value = self.value_from_envvar(ctx)1334+ if value is None:1335+ value = ctx.lookup_default(self.name)1336 return value1337 1338 def type_cast_value(self, ctx, value):1339 """Given a value this runs it properly through the type system.88 unmodified lines1428 1429 def get_usage_pieces(self, ctx):1430 return []1431 1432+ def get_error_hint(self, ctx):1433+ """Get a stringified version of the param for use in error messages to1434+ indicate which param caused the error.1435+ """1436+ hint_list = self.opts or [self.human_readable_name]1437+ return ' / '.join('"%s"' % x for x in hint_list)1438 1439+1440 class Option(Parameter):1441 """Options are usually optional values on the command line and1442 have some extra features that arguments don't have.1443 315 unmodified lines1759 1760 def get_usage_pieces(self, ctx):1761 return [self.make_metavar()]1762 1763+ def get_error_hint(self, ctx):1764+ return '"%s"' % self.make_metavar()1765+1766 def add_to_parser(self, parser, ctx):1767 parser.add_argument(dest=self.name, nargs=self.nargs,1768 obj=self)1769 3 unmodified linesmodified:click/decorators.py+10 added-7 removed
83 unmodified lines84 else:85 help = inspect.cleandoc(help)86 attrs['help'] = help87 _check_for_unicode_literals()88- return cls(name=name or f.__name__.lower(),88+ return cls(name=name or f.__name__.lower().replace('_', '-'),89 callback=f, params=params, **attrs)90 91 92 def command(name=None, cls=None, **attrs):93- """Creates a new :class:`Command` and uses the decorated function as93+ r"""Creates a new :class:`Command` and uses the decorated function as94 callback. This will also automatically attach all decorated95 :func:`option`\s and :func:`argument`\s as parameters to the command.96 97 The name of the command defaults to the name of the function. If you6 unmodified lines104 that can be invoked as a command line utility or be attached to a105 command :class:`Group`.106 107 :param name: the name of the command. This defaults to the function108- name.108+ name with underscores replaced by dashes.109 :param cls: the command class to instantiate. This defaults to110 :class:`Command`.111 """112 if cls is None:50 unmodified lines163 :param cls: the option class to instantiate. This defaults to164 :class:`Option`.165 """166 def decorator(f):167+ # Issue 926, copy attrs, so pre-defined options can re-use the same cls=168+ option_attrs = attrs.copy()169+167- if 'help' in attrs:168- attrs['help'] = inspect.cleandoc(attrs['help'])169- OptionClass = attrs.pop('cls', Option)170- _param_memo(f, OptionClass(param_decls, **attrs))170+ if 'help' in option_attrs:171+ option_attrs['help'] = inspect.cleandoc(option_attrs['help'])172+ OptionClass = option_attrs.pop('cls', Option)173+ _param_memo(f, OptionClass(param_decls, **option_attrs))174 return f175 return decorator176 177 134 unmodified linesmodified:click/exceptions.py+17 added-9 removed
1 from ._compat import PY2, filename_to_ui, get_text_stderr2 from .utils import echo3 4 5+def _join_param_hints(param_hint):6+ if isinstance(param_hint, (tuple, list)):7+ return ' / '.join('"%s"' % x for x in param_hint)8+ return param_hint9+10+11 class ClickException(Exception):12 """An exception that Click can handle and show to the user."""13 14 #: The exit code for this exception9 unmodified lines24 25 def format_message(self):26 return self.message27 22- def __unicode__(self):28+ def __str__(self):29 return self.message30 25- def __str__(self):26- return self.message.encode('utf-8')31+ if PY2:32+ __unicode__ = __str__33 34+ def __str__(self):35+ return self.message.encode('utf-8')36+37 def show(self, file=None):38 if file is None:39 file = get_text_stderr()40 echo('Error: %s' % self.format_message(), file=file)56 unmodified lines97 def format_message(self):98 if self.param_hint is not None:99 param_hint = self.param_hint100 elif self.param is not None:92- 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.message95- if isinstance(param_hint, (tuple, list)):96- param_hint = ' / '.join('"%s"' % x for x in param_hint)104+ param_hint = _join_param_hints(param_hint)105+106 return 'Invalid value for %s: %s' % (param_hint, self.message)107 108 109 class MissingParameter(BadParameter):16 unmodified lines126 def format_message(self):127 if self.param_hint is not None:128 param_hint = self.param_hint129 elif self.param is not None:121- 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 = None124- if isinstance(param_hint, (tuple, list)):125- param_hint = ' / '.join('"%s"' % x for x in param_hint)133+ param_hint = _join_param_hints(param_hint)134 135 param_type = self.param_type136 if param_type is None and self.param is not None:137 param_type = self.param.param_type_name88 unmodified linesmodified:click/globals.py+1 added-1 removed
7 unmodified lines8 """Returns the current click context. This can be used as a way to9 access the current context object from anywhere. This is a more implicit10 alternative to the :func:`pass_context` decorator. This function is11 primarily useful for helpers such as :func:`echo` which might be12- interested in changing it's behavior based on the current context.12+ interested in changing its behavior based on the current context.13 14 To push the current context, :meth:`Context.scope` can be used.15 16 .. versionadded:: 5.032 unmodified linesmodified:click/termui.py+18 added-5 removed
1 import os2 import sys3 import struct4+import inspect5+import itertools6 7 from ._compat import raw_input, text_type, string_types, \8 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN9 from .utils import echo211 unmodified lines221 os.environ.get('COLUMNS', DEFAULT_COLUMNS))222 return int(cr[1]), int(cr[0])223 224 223-def echo_via_pager(text, color=None):225+def echo_via_pager(text_or_generator, color=None):226 """This function takes a text and shows it via an environment specific227 pager on stdout.228 229 .. versionchanged:: 3.0230 Added the `color` flag.231 230- :param text: the text to page.232+ :param text_or_generator: the text to page, or alternatively, a233+ generator emitting the text to page.234 :param color: controls if the pager supports ANSI colors or not. The235 default is autodetection.236 """237 color = resolve_color_default(color)235- if not isinstance(text, string_types):236- text = text_type(text)238+239+ if inspect.isgeneratorfunction(text_or_generator):240+ i = text_or_generator()241+ elif isinstance(text_or_generator, string_types):242+ i = [text_or_generator]243+ else:244+ i = iter(text_or_generator)245+246+ # convert every element of i to a text type if necessary247+ text_generator = (el if isinstance(el, string_types) else text_type(el)248+ for el in i)249+250 from ._termui_impl import pager238- return pager(text + '\n', color)251+ return pager(itertools.chain(text_generator, "\n"), color)252 253 254 def progressbar(iterable=None, length=None, label=None, show_eta=True,255 show_percent=None, show_pos=False,335 unmodified linesmodified:click/testing.py+52 added-15 removed
71 unmodified lines72 73 class Result(object):74 """Holds the captured result of an invoked CLI script."""75 76- def __init__(self, runner, output_bytes, exit_code, exception,77- exc_info=None):76+ def __init__(self, runner, stdout_bytes, stderr_bytes, exit_code,77+ exception, exc_info=None):78 #: The runner that created the result79 self.runner = runner80- #: The output as bytes.81- self.output_bytes = output_bytes80+ #: The standard output as bytes.81+ self.stdout_bytes = stdout_bytes82+ #: The standard error as bytes, or False(y) if not available83+ self.stderr_bytes = stderr_bytes84 #: The exit code as integer.85 self.exit_code = exit_code86 #: The exception that happend if one did.87 self.exception = exception1 unmodified line89 self.exc_info = exc_info90 91 @property92 def output(self):91- """The output as unicode string."""92- return self.output_bytes.decode(self.runner.charset, 'replace') \93+ """The (standard) output as unicode string."""94+ return self.stdout95+96+ @property97+ def stdout(self):98+ """The standard output as unicode string."""99+ return self.stdout_bytes.decode(self.runner.charset, 'replace') \100 .replace('\r\n', '\n')101 102+ @property103+ def stderr(self):104+ """The standard error as unicode string."""105+ if not self.stderr_bytes:106+ raise ValueError("stderr not separately captured")107+ return self.stderr_bytes.decode(self.runner.charset, 'replace') \108+ .replace('\r\n', '\n')109+110+111 def __repr__(self):96- return '<Result %s>' % (112+ return '<%s %s>' % (113+ type(self).__name__,114 self.exception and repr(self.exception) or 'okay',115 )116 117 10 unmodified lines128 :param echo_stdin: if this is set to `True`, then reading from stdin writes129 to stdout. This is useful for showing examples in130 some circumstances. Note that regular prompts131 will automatically echo the input.132+ :param mix_stderr: if this is set to `False`, then stdout and stderr are133+ preserved as independent streams. This is useful for134+ Unix-philosophy apps that have predictable stdout and135+ noisy stderr, such that each may be measured136+ independently137 """138 117- def __init__(self, charset=None, env=None, echo_stdin=False):139+ def __init__(self, charset=None, env=None, echo_stdin=False,140+ mix_stderr=True):141 if charset is None:142 charset = 'utf-8'143 self.charset = charset144 self.env = env or {}145 self.echo_stdin = echo_stdin146+ self.mix_stderr = mix_stderr147 148 def get_default_prog_name(self, cli):149 """Given a command object it will return the default program name150 for it. The default is the `name` attribute or ``"root"`` if not36 unmodified lines187 188 env = self.make_env(env)189 190 if PY2:167- sys.stdout = sys.stderr = bytes_output = StringIO()191+ bytes_output = StringIO()192 if self.echo_stdin:193 input = EchoingStdin(input, bytes_output)194+ sys.stdout = bytes_output195+ if not self.mix_stderr:196+ bytes_error = StringIO()197+ sys.stderr = bytes_error198 else:199 bytes_output = io.BytesIO()200 if self.echo_stdin:201 input = EchoingStdin(input, bytes_output)202 input = io.TextIOWrapper(input, encoding=self.charset)175- sys.stdout = sys.stderr = io.TextIOWrapper(203+ sys.stdout = io.TextIOWrapper(204 bytes_output, encoding=self.charset)205+ if not self.mix_stderr:206+ bytes_error = io.BytesIO()207+ sys.stderr = io.TextIOWrapper(208+ bytes_error, encoding=self.charset)209 210+ if self.mix_stderr:211+ sys.stderr = sys.stdout212+213 sys.stdin = input214 215 def visible_input(prompt=None):216 sys.stdout.write(prompt or '')40 unmodified lines257 except Exception:258 pass259 else:260 os.environ[key] = value226- yield bytes_output261+ yield (bytes_output, not self.mix_stderr and bytes_error)262 finally:263 for key, value in iteritems(old_env):264 if value is None:265 try:11 unmodified lines277 clickpkg.utils.should_strip_ansi = old_should_strip_ansi278 clickpkg.formatting.FORCED_WIDTH = old_forced_width279 280 def invoke(self, cli, args=None, input=None, env=None,246- catch_exceptions=True, color=False, **extra):281+ catch_exceptions=True, color=False, mix_stderr=False, **extra):282 """Invokes a command in an isolated environment. The arguments are283 forwarded directly to the command line script, the `extra` keyword284 arguments are passed to the :meth:`~clickpkg.Command.main` function of285 the command.23 unmodified lines309 :param color: whether the output should contain color codes. The310 application can still override this explicitly.311 """312 exc_info = None278- with self.isolation(input=input, env=env, color=color) as out:313+ with self.isolation(input=input, env=env, color=color) as outstreams:314 exception = None315 exit_code = 0316 317 if isinstance(args, string_types):23 unmodified lines341 exit_code = 1342 exc_info = sys.exc_info()343 finally:344 sys.stdout.flush()310- output = out.getvalue()345+ stdout = outstreams[0].getvalue()346+ stderr = outstreams[1] and outstreams[1].getvalue()347 348 return Result(runner=self,313- output_bytes=output,349+ stdout_bytes=stdout,350+ stderr_bytes=stderr,351 exit_code=exit_code,352 exception=exception,353 exc_info=exc_info)354 16 unmodified linesmodified:click/types.py+10 added-7 removed
127 unmodified lines128 class Choice(ParamType):129 """The choice type allows a value to be checked against a fixed set of130 supported values. All of these values have to be strings.131 132+ You should only pass *choices* as list or tuple. Other iterables (like133+ generators) may lead to surprising results.134+135 See :ref:`choice-opts` for an example.136 """137 name = 'choice'138 137 unmodified lines276 def convert(self, value, param, ctx):277 if isinstance(value, bool):278 return bool(value)279 value = value.lower()277- if value in ('true', '1', 'yes', 'y'):280+ if value in ('true', 't', '1', 'yes', 'y'):281 return True279- elif value in ('false', '0', 'no', 'n'):282+ elif value in ('false', 'f', '0', 'no', 'n'):283 return False284 self.fail('%s is not a valid boolean' % value, param, ctx)285 286 def __repr__(self):117 unmodified lines404 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.405- :param type: optionally a string type that should be used to406- represent the path. The default is `None` which407- means the return value will be either bytes or408- unicode depending on what makes most sense given the409- input data Click deals with.408+ :param path_type: optionally a string type that should be used to409+ represent the path. The default is `None` which410+ means the return value will be either bytes or411+ unicode depending on what makes most sense given the412+ input data Click deals with.413 """414 envvar_list_splitter = os.path.pathsep415 416 def __init__(self, exists=False, file_okay=True, dir_okay=True,178 unmodified linesmodified:click/utils.py+1 added-1 removed
182 unmodified lines183 - add transparent handling of ANSI color codes on Windows.184 - hide ANSI codes automatically if the destination file is not a185 terminal.186 187- .. _colorama: http://pypi.python.org/pypi/colorama187+ .. _colorama: https://pypi.org/project/colorama/188 189 .. versionchanged:: 6.0190 As of Click 6.0 the echo function will properly support unicode191 output on the windows console. Not that click does not modify225 unmodified linesmodified:docs/_templates/sidebarintro.html+1 added-1 removed
5 unmodified lines6 </p>7 <h3>Useful Links</h3>8 <ul>9 <li><a href="http://click.pocoo.org/">The Click Website</a></li>10- <li><a href="http://pypi.python.org/pypi/click">click @ PyPI</a></li>10+ <li><a href="https://pypi.org/project/click/">click @ PyPI</a></li>11 <li><a href="http://github.com/pallets/click">click @ github</a></li>12 <li><a href="http://github.com/pallets/click/issues">Issue Tracker</a></li>13 </ul>modified:docs/advanced.rst+3 added-3 removed
293 unmodified lines294 ))295 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')296 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)297 def cli(verbose, timeit_args):298- """A wrapper around Python's timeit."""299- cmdline = ['python', '-mtimeit'] + list(timeit_args)298+ """A fake wrapper around Python's timeit."""299+ cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)300 if verbose:301 click.echo('Invoking: %s' % ' '.join(cmdline))302 call(cmdline)303 16 unmodified lines320 So for instance if ``--foo=bar`` or ``--foo bar`` are passed they321 generally end up like that. Note that because the parser cannot know322 if an option will accept an argument or not, the ``bar`` part might be323 handled as an argument.324-* Unknown short options might be partially handled and reassmebled if324+* Unknown short options might be partially handled and reassembled if325 necessary. For instance in the above example there is an option326 called ``-v`` which enables verbose mode. If the command would be327 ignored with ``-va`` then the ``-v`` part would be handled by Click328 (as it is known) and ``-a`` would end up in the leftover parameters51 unmodified linesmodified:docs/arguments.rst+18 added
241 unmodified lines242 243 .. click:run::244 245 invoke(touch, ['--', '-foo.txt', 'bar.txt'])246+247+If you don't like the ``--`` marker, you can set ignore_unknown_options to248+True to avoid checking unknown options:249+250+.. click:example::251+252+ @click.command(context_settings={"ignore_unknown_options": True})253+ @click.argument('files', nargs=-1, type=click.Path())254+ def touch(files):255+ for filename in files:256+ click.echo(filename)257+258+And from the command line:259+260+.. click:run::261+262+ invoke(touch, ['-foo.txt', 'bar.txt'])263+modified:docs/clickdoctools.py+8 added-1 removed
15 unmodified lines16 17 from sphinx.domains import Domain18 from sphinx.util.compat import Directive19 20+PY2 = sys.version_info[0] == 221 22+if PY2:23+ text_type = unicode24+else:25+ text_type = str26+ 27+28 class EchoingStdin(object):29 30 def __init__(self, input, output):31 self._input = input44 unmodified lines76 77 78 @contextlib.contextmanager79 def isolation(input=None, env=None):73- if isinstance(input, unicode):80+ if isinstance(input, text_type):81 input = input.encode('utf-8')82 input = StringIO(input or '')83 output = StringIO()84 sys.stdin = EchoingStdin(input, output)198 unmodified linesmodified:docs/commands.rst+1 added-1 removed
27 unmodified lines28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))29 30 @cli.command()31 def sync():32- click.echo('Synching')32+ click.echo('Syncing')33 34 Here is what this looks like:35 36 .. click:run::522 unmodified linesmodified:docs/complex.rst+5 added-5 removed
151 unmodified lines152 One obvious way to remedy this is to store a reference to the repo in the153 plugin, but then a command needs to be aware that it's attached below such a154 plugin.155 156-There is a much better system that can built by taking advantage of the linked157-nature of contexts. We know that the plugin context is linked to the context158-that created our repo. Because of that, we can start a search for the last159-level where the object stored by the context was a repo.156+There is a much better system that can be built by taking advantage of the157+linked nature of contexts. We know that the plugin context is linked to the158+context that created our repo. Because of that, we can start a search for159+the last level where the object stored by the context was a repo.160 161 Built-in support for this is provided by the :func:`make_pass_decorator`162 factory, which will create decorators for us that find objects (it163 internally calls into :meth:`Context.find_object`). In our case, we45 unmodified lines209 210 @click.command()211 @pass_repo212 def cp(repo):213- click.echo(repo)213+ click.echo(isinstance(repo, Repo))214 215 As you can see:216 217 .. click:run::2 unmodified linesmodified:docs/options.rst+5 added
290 unmodified lines291 invoke(digest, args=['--hash-type=foo'])292 println()293 invoke(digest, args=['--help'])294 295+.. note::296+297+ You should only pass the choices as list or tuple. Other iterables (like298+ generators) may lead to surprising results.299+300 .. _option-prompting:301 302 Prompting303 ---------407 unmodified linesmodified:docs/parameters.rst+2 added-2 removed
45 unmodified lines46 A parameter that only accepts floating point values.47 48 ``bool`` / :data:`click.BOOL`:49 A parameter that accepts boolean values. This is automatically used50- for boolean flags. If used with string values ``1``, ``yes``, ``y``51- and ``true`` convert to `True` and ``0``, ``no``, ``n`` and ``false``50+ for boolean flags. If used with string values ``1``, ``yes``, ``y``, ``t``51+ and ``true`` convert to `True` and ``0``, ``no``, ``n``, ``f`` and ``false``52 convert to `False`.53 54 :data:`click.UUID`:55 A parameter that accepts UUID values. This is not automatically68 unmodified linesmodified:docs/python3.rst+1 added-1 removed
4 unmodified lines5 6 Click supports Python 3, but like all other command line utility libraries,7 it suffers from the Unicode text model in Python 3. All examples in the8 documentation were written so that they could run on both Python 2.x and9-Python 3.3 or higher.9+Python 3.4 or higher.10 11 At the moment, it is strongly recommended to use Python 2 for Click12 utilities unless Python 3 is a hard requirement.13 170 unmodified linesmodified:docs/quickstart.rst+1 added-1 removed
49 unmodified lines50 ``pip`` first. For more information about this, see `installing pip`_.51 Once you have it installed, run the ``pip`` command from above, but without52 the `sudo` prefix.53 54-.. _installing pip: http://pip.readthedocs.org/en/latest/installing.html54+.. _installing pip: https://pip.readthedocs.io/en/latest/installing.html55 56 Once you have virtualenv installed, just fire up a shell and create57 your own environment. I usually create a project folder and a `venv`58 folder within::216 unmodified linesmodified:docs/utils.rst+12 added-1 removed
93 unmodified lines94 click.secho('Some more text', bg='blue', fg='white')95 click.secho('ATTENTION', blink=True, bold=True)96 97 98-.. _colorama: https://pypi.python.org/pypi/colorama98+.. _colorama: https://pypi.org/project/colorama/99 100 Pager Support101 -------------102 10 unmodified lines113 def less():114 click.echo_via_pager('\n'.join('Line %d' % idx115 for idx in range(200)))116 117+If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:118 119+.. click:example::120+ def _generate_output():121+ for idx in range(50000):122+ yield "Line %d\n" % idx123+124+ @click.command()125+ def less():126+ click.echo_via_pager(_generate_output())127+128+129 Screen Clearing130 ---------------131 132 .. versionadded:: 2.0277 unmodified linesmodified:examples/bashcompletion/bashcompletion.py+12 added-2 removed
1 import click2 import os3 4+5 @click.group()6 def cli():7 pass8 9+10 def get_env_vars(ctx, args, incomplete):9- return os.environ.keys()11+ for key in os.environ.keys():12+ if incomplete in key:13+ yield key14 15+16 @cli.command()17 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)18 def cmd1(envvar):19 click.echo('Environment variable: %s' % envvar)20 click.echo('Value: %s' % os.environ[envvar])21 22+23 @click.group()24 def group():25 pass26 27+28 def list_users(ctx, args, incomplete):29 # Here you can generate completions dynamically30 users = ['bob', 'alice']24- return users31+ for user in users:32+ if user.startswith(incomplete):33+ yield user34 35+36 @group.command()37 @click.argument("user", type=click.STRING, autocompletion=list_users)38 def subcmd(user):39 click.echo('Chosen user is %s' % user)2 unmodified linesmodified:examples/validation/validation.py+1 added-1 removed
1 import click2 try:3- from urllib import parser as urlparse3+ from urllib import parse as urlparse4 except ImportError:5 import urlparse6 7 37 unmodified linesmodified:tests/test_arguments.py+2 added-2 removed
186 unmodified lines187 click.echo('arg:' + '|'.join(arg))188 189 result = runner.invoke(cmd2, [])190 assert result.exit_code == 2191- assert 'Missing argument "arg"' in result.output191+ assert 'Missing argument "ARG..."' in result.output192 193 194 def test_missing_arg(runner):195 @click.command()2 unmodified lines198 click.echo('arg:' + arg)199 200 result = runner.invoke(cmd, [])201 assert result.exit_code == 2202- assert 'Missing argument "arg".' in result.output202+ assert 'Missing argument "ARG".' in result.output203 204 205 def test_implicit_non_required(runner):206 @click.command()83 unmodified linesmodified:tests/test_bashcomplete.py+25 added-8 removed
84 unmodified lines85 86 COLORS = ['red', 'green', 'blue']87 def get_colors(ctx, args, incomplete):88 for c in COLORS:89+ if c.startswith(incomplete):89- yield c90+ yield c91 92+ def search_colors(ctx, args, incomplete):93+ for c in COLORS:94+ if incomplete in c:95+ yield c96+97 CSUB_OPT_CHOICES = ['foo', 'bar']98 CSUB_CHOICES = ['bar', 'baz']99 @bsub.command('csub')100 @click.option('--csub-opt', type=click.Choice(CSUB_OPT_CHOICES))101 @click.option('--csub', type=click.Choice(CSUB_CHOICES))102+ @click.option('--search-color', autocompletion=search_colors)103 @click.argument('color', autocompletion=get_colors)104 def csub(csub_opt, color):105 pass106 2 unmodified lines109 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']106- assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '-')) == ['--csub-opt', '--csub']113+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '-')) == ['--csub-opt', '--csub', '--search-color']114 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], '')) == CSUB_OPT_CHOICES115 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '--csub')) == ['--csub-opt', '--csub']116 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub'], '')) == CSUB_CHOICES117 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], 'f')) == ['foo']118 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '')) == COLORS119 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], 'b')) == ['blue']120+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--search-color'], 'een')) == ['green']121 122 123 def test_chaining():124 @click.group('cli', chain=True)7 unmodified lines132 pass133 134 @cli.command('bsub')135 @click.option('--bsub-opt')128- @click.argument('arg', type=click.Choice(['arg1', 'arg2']))136+ @click.argument('arg', type=click.Choice(['arg1', 'arg2']), required=True)137 def bsub(bsub_opt, arg):138 pass139 140+ @cli.command('csub')141+ @click.option('--csub-opt')142+ @click.argument('arg', type=click.Choice(['carg1', 'carg2']), required=False)143+ def csub(csub_opt, arg):144+ pass145+146 assert list(get_choices(cli, 'lol', [], '-')) == ['--cli-opt']133- assert list(get_choices(cli, 'lol', [], '')) == ['asub', 'bsub']147+ assert list(get_choices(cli, 'lol', [], '')) == ['asub', 'bsub', 'csub']148 assert list(get_choices(cli, 'lol', ['asub'], '-')) == ['--asub-opt']135- assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub']136- assert list(get_choices(cli, 'lol', ['bsub'], '')) == ['arg1', 'arg2', 'asub']149+ assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub', 'csub']150+ assert list(get_choices(cli, 'lol', ['bsub'], '')) == ['arg1', 'arg2']151+ assert list(get_choices(cli, 'lol', ['asub', '--asub-opt'], '')) == []152 assert list(get_choices(cli, 'lol', ['asub', '--asub-opt', '5', 'bsub'], '-')) == ['--bsub-opt']153 assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '-')) == ['--bsub-opt']154+ assert list(get_choices(cli, 'lol', ['asub', 'csub'], '')) == ['carg1', 'carg2', 'bsub']155+ assert list(get_choices(cli, 'lol', ['asub', 'csub'], '-')) == ['--csub-opt']156 157 158 def test_argument_choice():159 @click.command()111 unmodified lines271 @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))272 def bsub(bsub_opt):273 pass274 258- assert list(get_choices(cli, 'lol', ['sub'], '')) == ['subarg1', 'subarg2']275+ assert list(get_choices(cli, 'lol', ['sub'], '')) == ['subarg1', 'subarg2', 'bsub']276 assert list(get_choices(cli, 'lol', ['sub', '--sub-opt'], '')) == ['subopt1', 'subopt2']277 assert list(get_choices(cli, 'lol', ['sub', '--sub-opt', 'subopt1'], '')) == \261- ['subarg1', 'subarg2']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'], '')) == \4 unmodified linesmodified:tests/test_basic.py+23 added-1 removed
178 unmodified lines179 assert not result.exception180 assert result.output == '%s\n' % (default)181 182 183+def test_boolean_conversion(runner):184+ for default in True, False:185+ @click.command()186+ @click.option('--flag', default=default, type=bool)187+ def cli(flag):188+ click.echo(flag)189+190+ for value in 'true', 't', '1', 'yes', 'y':191+ result = runner.invoke(cli, ['--flag', value])192+ assert not result.exception193+ assert result.output == 'True\n'194+195+ for value in 'false', 'f', '0', 'no', 'n':196+ result = runner.invoke(cli, ['--flag', value])197+ assert not result.exception198+ assert result.output == 'False\n'199+200+ result = runner.invoke(cli, [])201+ assert not result.exception202+ assert result.output == '%s\n' % default203+204+205 def test_file_option(runner):206 @click.command()207 @click.option('--file', type=click.File('w'))208 def input(file):202 unmodified lines411 412 def test_evaluation_order(runner):413 called = []414 393- def memo(ctx, value):415+ def memo(ctx, param, value):416 called.append(value)417 return value418 419 @click.command()79 unmodified linesmodified:tests/test_commands.py+64 added-2 removed
1 # -*- coding: utf-8 -*-2 import re3+4 import click5+import pytest6 7 8 def test_other_command_invoke(runner):9 @click.command()53 unmodified lines63 assert re.search(64 r'Commands:\n\s+'65 r'long\s+This is a long text that is too long to show\.\.\.\n\s+'66 r'short\s+This is a short text\.\n\s+'65- r'special_chars\s+Login and store the token in ~/.netrc\.\s*',67+ r'special-chars\s+Login and store the token in ~/.netrc\.\s*',68 result.output) is not None69 70 71 def test_default_maps(runner):135 unmodified lines207 @click.command()208 @click.option('--foo', type=click.INT, default=42)209 @click.pass_context210 def other_cmd(ctx, foo):209- assert ctx.info_name == 'other_cmd'211+ assert ctx.info_name == 'other-cmd'212 click.echo(foo)213 214 result = runner.invoke(cli, [])215 assert not result.exception38 unmodified lines254 assert result.output.splitlines() == [255 'Verbosity: 4',256 'Args: -foo|-x|--muhaha|x|y|-x',257 ]258+259+260+def test_subcommand_naming(runner):261+ @click.group()262+ def cli():263+ pass264+265+ @cli.command()266+ def foo_bar():267+ click.echo('foo-bar')268+269+ result = runner.invoke(cli, ['foo-bar'])270+ assert not result.exception271+ assert result.output.splitlines() == ['foo-bar']272+273+274+def test_environment_variables(runner):275+ @click.group()276+ def cli():277+ pass278+279+ @cli.command()280+ @click.option('--name', envvar='CLICK_NAME')281+ def foo(name):282+ click.echo(name)283+284+ result = runner.invoke(cli, ['foo'], env={'CLICK_NAME': 'environment'})285+286+ assert not result.exception287+ assert result.output == 'environment\n'288+289+290+# Ensures the variables are read in the following order:291+# 1. CLI292+# 2. Environment293+# 3. Defaults294+variable_precedence_testdata = [295+ (['foo', '--name=cli'], {'CLICK_NAME': 'environment'}, 'cli\n'),296+ (['foo'], {'CLICK_NAME': 'environment'}, 'environment\n'),297+ (['foo'], None, 'defaults\n'),298+]299+300+301+@pytest.mark.parametrize("command,environment,expected",302+ variable_precedence_testdata)303+def test_variable_precendence_00(runner, command, environment, expected):304+ @click.group()305+ def cli():306+ pass307+308+ @cli.command()309+ @click.option('--name', envvar='CLICK_NAME')310+ def foo(name):311+ click.echo(name)312+313+ defaults = {'foo': {'name': 'defaults'}}314+ result = runner.invoke(cli, command, default_map=defaults, env=environment)315+316+ assert not result.exception317+ assert result.output == expectedmodified:tests/test_compat.py+5 added-4 removed
1 import click2+import pytest3 4 5 if click.__version__ >= '3.0':6 def test_legacy_callbacks(runner):4 unmodified lines11 @click.option('--foo', callback=legacy_callback)12 def cli(foo):13 click.echo(foo)14 14- result = runner.invoke(cli, ['--foo', 'wat'])15- assert result.exit_code == 016- assert 'WAT' in result.output17- assert 'Invoked legacy parameter callback' in result.output15+ with pytest.warns(Warning, match='Invoked legacy parameter callback'):16+ result = runner.invoke(cli, ['--foo', 'wat'])17+ assert result.exit_code == 018+ assert 'WAT' in result.output19 20 21 def test_bash_func_name():22 from click._bashcomplete import get_completion_script3 unmodified linesmodified:tests/test_formatting.py+44 added-8 removed
72 unmodified lines73 """74 75 # 54 is chosen as a length where the second line is one character76 # longer than the maximum length.77- result = runner.invoke(cli, ['a_very_long', 'command', '--help'],77+ result = runner.invoke(cli, ['a-very-long', 'command', '--help'],78 terminal_width=54)79 assert not result.exception80 assert result.output.splitlines() == [81- 'Usage: cli a_very_long command [OPTIONS] FIRST SECOND',81+ 'Usage: cli a-very-long command [OPTIONS] FIRST SECOND',82 ' THIRD FOURTH FIFTH',83 ' SIXTH',84 '',85 ' A command.',24 unmodified lines110 def command():111 """A command.112 """113 114- result = runner.invoke(cli, ['a_very_very_very_long', 'command', '--help'],114+ result = runner.invoke(cli, ['a-very-very-very-long', 'command', '--help'],115 terminal_width=54)116 assert not result.exception117 assert result.output.splitlines() == [118- 'Usage: cli a_very_very_very_long command ',118+ 'Usage: cli a-very-very-very-long command ',119 ' [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH',120 ' SIXTH',121 '',122 ' A command.',35 unmodified lines158 assert result.output.splitlines() == [159 'Usage: cmd [OPTIONS] ARG',160 'Try "cmd --help" for help.',161 '',162- 'Error: Missing argument "arg".'162+ 'Error: Missing argument "ARG".'163 ]164 165 166+def test_formatting_usage_error_metavar_missing_arg(runner):167+ """168+ :author: @r-m-n169+ Including attribution to #612170+ """171+ @click.command()172+ @click.argument('arg', metavar='metavar')173+ def cmd(arg):174+ pass175+176+ result = runner.invoke(cmd, [])177+ assert result.exit_code == 2178+ assert result.output.splitlines() == [179+ 'Usage: cmd [OPTIONS] metavar',180+ 'Try "cmd --help" for help.',181+ '',182+ 'Error: Missing argument "metavar".'183+ ]184+185+186+def test_formatting_usage_error_metavar_bad_arg(runner):187+ @click.command()188+ @click.argument('arg', type=click.INT, metavar='metavar')189+ def cmd(arg):190+ pass191+192+ result = runner.invoke(cmd, ['3.14'])193+ assert result.exit_code == 2194+ assert result.output.splitlines() == [195+ 'Usage: cmd [OPTIONS] metavar',196+ 'Try "cmd --help" for help.',197+ '',198+ 'Error: Invalid value for "metavar": 3.14 is not a valid integer'199+ ]200+201+202 def test_formatting_usage_error_nested(runner):203 @click.group()204 def cmd():205 pass8 unmodified lines214 assert result.output.splitlines() == [215 'Usage: cmd foo [OPTIONS] BAR',216 'Try "cmd foo --help" for help.',217 '',182- 'Error: Missing argument "bar".'218+ 'Error: Missing argument "BAR".'219 ]220 221 222 def test_formatting_usage_error_no_help(runner):6 unmodified lines229 assert result.exit_code == 2230 assert result.output.splitlines() == [231 'Usage: cmd [OPTIONS] ARG',232 '',197- 'Error: Missing argument "arg".'233+ 'Error: Missing argument "ARG".'234 ]235 236 237 def test_formatting_usage_custom_help(runner):7 unmodified lines245 assert result.output.splitlines() == [246 'Usage: cmd [OPTIONS] ARG',247 'Try "cmd --man" for help.',248 '',213- 'Error: Missing argument "arg".'249+ 'Error: Missing argument "ARG".'250 ]modified:tests/test_imports.py+1 added-2 removed
30 unmodified lines31 32 ALLOWED_IMPORTS = set([33 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',35- 'threading', 'colorama', 'errno'35+ 'threading', 'colorama', 'errno', 'fcntl'36 ])37 38 if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',7 unmodified lines47 48 if sys.version_info[0] != 2:49 rv = rv.decode('utf-8')50 imported = json.loads(rv)51- print(imported)51 52 for module in imported:53 if module == 'click' or module.startswith('click.'):54 continue1 unmodified linemodified:tests/test_options.py+31 added-2 removed
82 unmodified lines83 assert not result.exception84 assert result.output == 'verbosity=0\n'85 86 result = runner.invoke(cli, ['--help'])87- assert re.search('-v\s+Verbosity', result.output) is not None87+ assert re.search(r'-v\s+Verbosity', result.output) is not None88 89 90 @pytest.mark.parametrize('unknown_flag', ['--foo', '-f'])91 def test_unknown_options(runner, unknown_flag):106 unmodified lines198 assert result.output == 'x|1\ny|2\n'199 200 201 def test_custom_validation(runner):202- def validate_pos_int(ctx, value):202+ def validate_pos_int(ctx, param, value):203 if value < 0:204 raise click.BadParameter('Value needs to be positive')205 return value206 103 unmodified lines310 assert 'I am a help text' in result.output311 assert 'you wont see me' not in result.output312 313 314+def test_option_custom_class_reusable(runner):315+ """Ensure we can reuse a custom class option. See Issue #926"""316+317+ class CustomOption(click.Option):318+ def get_help_record(self, ctx):319+ '''a dumb override of a help text for testing'''320+ return ('--help', 'I am a help text')321+322+ # Assign to a variable to re-use the decorator.323+ testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')324+325+ @click.command()326+ @testoption327+ def cmd1(testoption):328+ click.echo(testoption)329+330+ @click.command()331+ @testoption332+ def cmd2(testoption):333+ click.echo(testoption)334+335+ # Both of the commands should have the --help option now.336+ for cmd in (cmd1, cmd2):337+338+ result = runner.invoke(cmd, ['--help'])339+ assert 'I am a help text' in result.output340+ assert 'you wont see me' not in result.output341+342+343 def test_aliases_for_flags(runner):344 @click.command()345 @click.option('--warnings/--no-warnings', ' /-W', default=True)346 def cli(warnings):46 unmodified linesmodified:tests/test_termui.py+15 added-2 removed
42 unmodified lines43 result = runner.invoke(cli, [])44 assert result.exception is None45 46 47+def test_progressbar_hidden(runner, monkeypatch):48+ label = 'whatever'49+50+ @click.command()51+ def cli():52+ with click.progressbar(tuple(range(10)), label=label) as progress:53+ for thing in progress:54+ pass55+56+ monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)57+ assert runner.invoke(cli, []).output == ''58+59+60 def test_choices_list_in_prompt(runner, monkeypatch):61 @click.command()62 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),63 prompt=True)13 unmodified lines77 assert '(none, day, week, month)' not in result.output78 79 80 def test_secho(runner):68- with runner.isolation() as out:81+ with runner.isolation() as outstreams:82 click.secho(None, nl=False)70- bytes = out.getvalue()83+ bytes = outstreams[0].getvalue()84 assert bytes == b''modified:tests/test_testing.py+24 added
202 unmodified lines203 204 assert os.environ == env_orig205 206 207+def test_stderr():208+ @click.command()209+ def cli_stderr():210+ click.echo("stdout")211+ click.echo("stderr", err=True)212+213+ runner = CliRunner(mix_stderr=False)214+215+ result = runner.invoke(cli_stderr)216+217+ assert result.output == 'stdout\n'218+ assert result.stdout == 'stdout\n'219+ assert result.stderr == 'stderr\n'220+221+ runner_mix = CliRunner(mix_stderr=True)222+ result_mix = runner_mix.invoke(cli_stderr)223+224+ assert result_mix.output == 'stdout\nstderr\n'225+ assert result_mix.stdout == 'stdout\nstderr\n'226+227+ with pytest.raises(ValueError):228+ result_mix.stderr229+230+231 @pytest.mark.parametrize('args, expected_output', [232 (None, 'bar\n'),233 ([], 'bar\n'),234 ('', 'bar\n'),14 unmodified linesmodified:tests/test_utils.py+37 added-14 removed
8 unmodified lines9 from click._compat import WIN, PY210 11 12 def test_echo(runner):13- with runner.isolation() as out:13+ with runner.isolation() as outstreams:14 click.echo(u'\N{SNOWMAN}')15 click.echo(b'\x44\x44')16 click.echo(42, nl=False)17 click.echo(b'a', nl=False)18 click.echo('\x1b[31mx\x1b[39m', nl=False)19- bytes = out.getvalue().replace(b'\r\n', b'\n')19+ bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')20 assert bytes == b'\xe2\x98\x83\nDD\n42ax'21 22 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 310 unmodified lines34 @click.command()35 def cli():36 click.echo(b'\xf6')37 result = runner.invoke(cli, [])38- assert result.output_bytes == b'\xf6\n'38+ assert result.stdout_bytes == b'\xf6\n'39 40 # Ensure we do not strip for bytes.41- with runner.isolation() as out:41+ with runner.isolation() as outstreams:42 click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)43- assert out.getvalue() == b'\x1b[31mx\x1b[39m'43+ assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'44 45 46 def test_echo_custom_file():47 import io97 unmodified lines145 out, err = capsys.readouterr()146 assert out == 'Password: \nScrew you.\n'147 148 149+def _test_gen_func():150+ yield 'a'151+ yield 'b'152+ yield 'c'153+ yield 'abc'154+155+156 @pytest.mark.skipif(WIN, reason='Different behavior on windows.')157 @pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])158+@pytest.mark.parametrize('test', [159+ # We need lambda here, because pytest will160+ # reuse the parameters, and then the generators161+ # are already used and will not yield anymore162+ ('just text\n', lambda: 'just text'),163+ ('iterable\n', lambda: ["itera", "ble"]),164+ ('abcabc\n', lambda: _test_gen_func),165+ ('abcabc\n', lambda: _test_gen_func()),166+ ('012345\n', lambda: (c for c in range(6))),167+])151-def test_echo_via_pager(monkeypatch, capfd, cat):168+def test_echo_via_pager(monkeypatch, capfd, cat, test):169 monkeypatch.setitem(os.environ, 'PAGER', cat)170 monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)171+172+ expected_output = test[0]173+ test_input = test[1]()174+154- click.echo_via_pager('haha')175+ click.echo_via_pager(test_input)176+177 out, err = capfd.readouterr()156- assert out == 'haha\n'178+ assert out == expected_output179 180 181 @pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')182 def test_echo_color_flag(monkeypatch, capfd):106 unmodified lines289 def test_iter_keepopenfile(tmpdir):290 expected = list(map(str, range(10)))291 p = tmpdir.mkdir('testdir').join('testfile')292 p.write(os.linesep.join(expected))271- f = p.open()272- for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):273- assert e_line == a_line.strip()293+ with p.open() as f:294+ for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):295+ assert e_line == a_line.strip()296 297 298 @pytest.mark.xfail(WIN and not PY2, reason='God knows ...')299 def test_iter_lazyfile(tmpdir):300 expected = list(map(str, range(10)))301 p = tmpdir.mkdir('testdir').join('testfile')302 p.write(os.linesep.join(expected))303+ with p.open() as f:281- f = p.open()282- for e_line, a_line in zip(expected, click.utils.LazyFile(f.name)):283- assert e_line == a_line.strip()304+ with click.utils.LazyFile(f.name) as lf:305+ for e_line, a_line in zip(expected, lf):306+ assert e_line == a_line.strip()added:.coveragerc+3 added
1+[run]2+branch = true3+source = click,testsmodified:.gitignore+2 added
1 unmodified line2 *.pyc3 *.pyo4 *.egg-ignore5 *.egg-info6+.pytest_cache7 dist8 build9 docs/_build10 click.egg-info11+venv/12 .tox13 .cache14 .ropeproject15 .ideadeleted:.travis-colorama-requirements.txt-1 removed
1-coloramadeleted:.travis-default-requirements.txt
modified:.travis.yml+22 added-7 removed
1+sudo: false2 language: python3 python:3- - "2.6"4 - "2.7"5- - "3.3"5 - "3.4"6 - "3.5"7 - "3.6"8 - "pypy"9 10 env:12- - REQUIREMENTS=colorama13- - REQUIREMENTS=default11+ - TEST_EXTRA=12+ - TEST_EXTRA=colorama13 14 install:16- - pip install -r .travis-$REQUIREMENTS-requirements.txt17- - pip install --editable .15+ - pip install tox16 19-script: make test17+script:18+ - |19+ set -ex20+ if [[ $TRAVIS_PYTHON_VERSION == pypy ]]; then21+ TOX_PY=pypy22+ else23+ TOX_PY="py${TRAVIS_PYTHON_VERSION/./}"24+ fi25+ export TOXENV="${TOX_PY}-coverage"26+ if [[ $TEST_EXTRA == colorama ]]; then27+ TOXENV="$TOXENV-colorama"28+ fi29+ tox30+ set +x31 32 branches:33 only:34 - master1 unmodified line36 - /^.*-maintenance$/37 38 notifications:39 email: false40+41+after_success:42+ - pip install codecov43+ - travis_retry codecov --env TOXENV -X fix search gcov --required --flags $TOX_PY $TEST_EXTRAmodified:CHANGES+18 added-1 removed
21 unmodified lines22 - 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 inproper completions on 26+- Fix bug that caused bashcompletion to give improper completions on 27 chained commands. See #774.28 - Add support for bright colors.29+- 't' and 'f' are now converted to True and False. 30+- Fix bug that caused bashcompletion to give improper completions on31+ chained commands when a required option/argument was being completed.32+ See #790.33+- Allow autocompletion function to determine whether or not to return34+ completions that start with the incomplete argument.35+- Subcommands that are named by the function now automatically have the36+ underscore replaced with a dash. So if you register a function named37+ `my_command` it becomes `my-command` in the command line interface.38+- Stdout is now automatically set to non blocking.39+- Use realpath to convert atomic file internally into its full canonical40+ path so that changing working directories does not harm it.41+- Force stdout/stderr writable. This works around issues with badly patched42+ standard streams like those from jupyter.43 44 Version 6.845 -----------46 4 unmodified lines51 - Fix bug in test runner when calling ``sys.exit`` with ``None``. See #739.52 - Fix crash on Windows console, see #744.53 - Fix bashcompletion on chained commands. See #754.54 - Fix option naming routine to match documentation. See #79355+- Fixed the behavior of click error messages with regards to unicode on 2.x56+ and 3.x respectively. Message is now always unicode and the str and unicode57+ special methods work as you expect on that platform.58 59 Version 6.760 -----------61 342 unmodified linesmodified:CONTRIBUTING.rst+1 added-1 removed
39 unmodified lines40 Running the testsuite41 ---------------------42 43 You probably want to set up a `virtualenv44-<http://virtualenv.readthedocs.org/en/latest/index.html>`_.44+<https://virtualenv.readthedocs.io/en/latest/index.html>`_.45 46 The minimal requirement for running the testsuite is ``py.test``. You can47 install it with::48 13 unmodified linesmodified:Makefile+1 added-1 removed
1 test:2- @cd tests; PYTHONPATH=.. py.test --tb=short2+ @cd tests; PYTHONPATH=.. pytest --tb=short3 4 upload-docs:5 $(MAKE) -C docs dirhtml6 rsync -a docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/click.pocoo.org/static/5 unmodified linesdeleted:README-20 removed
1-$ click_2-3- Click is a Python package for creating beautiful command line interfaces4- in a composable way with as little code as necessary. It's the "Command5- Line Interface Creation Kit". It's highly configurable but comes with6- sensible defaults out of the box.7-8- It aims to make the process of writing command line tools quick and fun9- while also preventing any frustration caused by the inability to implement10- an intended CLI API.11-12- Click in three points:13-14- - arbitrary nesting of commands15- - automatic help page generation16- - supports lazy loading of subcommands at runtime17-18- Read the docs at http://click.pocoo.org/19-20- This library is stable and active. Feedback is always welcome!added:README.rst+92 added
1+\$ click\_2+==========3+4+What's Click?5+-------------6+7+Click is a Python package for creating beautiful command line interfaces8+in a composable way with as little code as necessary. It's the "Command9+Line Interface Creation Kit". It's highly configurable but comes with10+sensible defaults out of the box.11+12+It aims to make the process of writing command line tools quick and fun13+while also preventing any frustration caused by the inability to implement14+an intended CLI API.15+16+Click in three points:17+ - arbitrary nesting of commands18+ - automatic help page generation19+ - supports lazy loading of subcommands at runtime20+21+22+Installing23+----------24+25+Install and update using `pip`_:26+27+.. code-block:: text28+29+ $ pip install click30+31+A Simple Example32+----------------33+34+What does it look like? Here is an example of a simple Click program:35+36+.. code-block:: python37+38+ import click39+ 40+ @click.command()41+ @click.option('--count', default=1, help='Number of greetings.')42+ @click.option('--name', prompt='Your name',43+ help='The person to greet.')44+ def hello(count, name):45+ """Simple program that greets NAME for a total of COUNT times."""46+ for x in range(count):47+ click.echo('Hello %s!' % name)48+ 49+ if __name__ == '__main__':50+ hello()51+52+And what it looks like when run:53+54+.. code-block:: text55+56+ $ python hello.py --count=357+ Your name: John58+ Hello John!59+ Hello John!60+ Hello John!61+62+Donate63+------64+65+The Pallets organization develops and supports Flask and the libraries66+it uses. In order to grow the community of contributors and users, and67+allow the maintainers to devote more time to the projects, `please68+donate today`_.69+70+.. _please donate today: https://psfmember.org/civicrm/contribute/transact?reset=1&id=2071+72+73+Links74+-----75+76+* Website: https://www.palletsprojects.com/p/click/77+* Documentation: http://click.pocoo.org/78+* License: `BSD <https://github.com/pallets/click/blob/master/LICENSE>`_79+* Releases: https://pypi.org/project/click/80+* Code: https://github.com/pallets/click81+* Issue tracker: https://github.com/pallets/click/issues82+* Test status:83+84+ * Linux, Mac: https://travis-ci.org/pallets/click85+ * Windows: https://ci.appveyor.com/project/pallets/click86+87+* Test coverage: https://codecov.io/gh/pallets/click88+89+.. _WSGI: https://wsgi.readthedocs.io90+.. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/91+.. _Jinja: https://www.palletsprojects.com/p/jinja/92+.. _pip: https://pip.pypa.io/en/stable/quickstart/modified:setup.cfg+3 added
1 unmodified line2 universal=13 4 [metadata]5 license_file = LICENSE6+7+[tool:pytest]8+addopts = -p no:warnings --tb=shortmodified:setup.py+22 added-6 removed
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+import io4 import re2-import ast5 from setuptools import setup6 7 8 _version_re = re.compile(r'__version__\s+=\s+(.*)')9 10 9-with open('click/__init__.py', 'rb') as f:10- version = str(ast.literal_eval(_version_re.search(11- f.read().decode('utf-8')).group(1)))11+with io.open('README.rst', 'rt', encoding='utf8') as f:12+ readme = f.read()13 14+with io.open('click/__init__.py', 'rt', encoding='utf8') as f:15+ version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)16 17 setup(18 name='click',19+ version=version,20+ url='https://www.palletsprojects.com/p/click/',21 author='Armin Ronacher',22 author_email='armin.ronacher@active-4.com',18- version=version,19- url='http://github.com/pallets/click',23+ maintainer='Pallets team',24+ maintainer_email='contact@palletsprojects.com',25+ long_description=readme,26 packages=['click'],27 description='A simple wrapper around optparse for '28 'powerful command line utilities.',29+ license='BSD',30 classifiers=[31+ 'Development Status :: 5 - Production/Stable',32+ 'Intended Audience :: Developers',33 'License :: OSI Approved :: BSD License',34+ 'Operating System :: OS Independent'35 'Programming Language :: Python',36+ 'Programming Language :: Python :: 2',37+ 'Programming Language :: Python :: 2.7',38 'Programming Language :: Python :: 3',39+ 'Programming Language :: Python :: 3.4',40+ 'Programming Language :: Python :: 3.5',41+ 'Programming Language :: Python :: 3.6',42 ],43+ python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",44 )modified:tox.ini+7 added-4 removed
1 [tox]2-envlist = py26,py27,py33,py34,pypy2+envlist = py27,py34,py35,py36,pypy3+skip_missing_interpreters = true4 5 [testenv]6 passenv = LANG6-commands = make test7+commands = {env:TEST_RUNNER:pytest} {posargs}8 deps =8- colorama9 pytest10-whitelist_externals = make10+ colorama: colorama11+ coverage: coverage12+setenv =13+ coverage: TEST_RUNNER=coverage run -m pytest