Skip to content
Myr

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

51 files+831 added−274 removed

modified:.ci/appveyor.yml+16 added
modified:click/__init__.py+1 added-1 removed
64 unmodified lines
65 'version_option', 'help_option',6667 # Types68 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple', 'STRING',69 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED', 'FloatRange'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+56 added-42 removed
43 unmodified lines
44 """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.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 "--")
8 unmodified lines
73 :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 lines
94 :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 lines
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 args
1 unmodified line
116 :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 []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 running
4 unmodified lines
153 all_args = copy.deepcopy(args)154155 ctx = resolve_ctx(cli, prog_name, args)156 if ctx is None:133 return157 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:
2 unmodified lines
164 incomplete = partition_incomplete[2]165 elif incomplete == WORDBREAK:166 incomplete = ''167144 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 break191168 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 completions194172 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)195177 for item in choices:178 if item.startswith(incomplete):179 yield item180181196def 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 lines
modified:click/_compat.py+64 added-21 removed
10 unmodified lines
11CYGWIN = sys.platform.startswith('cygwin')12DEFAULT_COLUMNS = 80131415_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()202122def _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,28 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):5149 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)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 """9587 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:
47 unmodified lines
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 msvcrt172 except ImportError:173 set_binary_mode = lambda x: x174 else:190191 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 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 rv200 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 rv206 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 rv212 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 False339304 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'330 return _make_text_stream(binary_reader, encoding, errors)367 return _make_text_stream(binary_reader, encoding, errors,368 force_readable=force_readable)369332 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'358 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 rv385 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 rv391 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 rv397 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 == '-':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 lines
505 f = io.open(fd, mode, encoding=encoding, errors=errors)506 else:507 f = os.fdopen(fd, mode)508466 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+51 added-48 removed
11 unmodified lines
12import os13import sys14import time15import math1617from ._compat import _default_text_stdout, range_type, PY2, isatty, \18 open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \19 CYGWIN20from .utils import echo
171 unmodified lines
192 }).rstrip()193194 def render_progress(self):195 from .termui import get_terminal_size195 nl = False196197 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 return199214 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_width212218 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_width216225 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_len222223 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()231232 def make_step(self, n_steps):233 self.pos += n_steps
35 unmodified lines
269 __next__ = next270 del next271272275def pager(text, color=None):273def 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)289290 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)299300303def _pipepager(text, cmd, color):301def _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 subprocess
9 unmodified lines
315 color = True316 elif 'r' in less_flags or 'R' in less_flags:317 color = True318321 if not color:322 text = strip_ansi(text)323319 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)326327 c.stdin.write(text.encode(encoding, 'replace'))328 except (IOError, KeyboardInterrupt):329 pass330 else:331 c.stdin.close()332333 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting334 # search or other commands inside less).335 #
10 unmodified lines
346 else:347 break348349350def _tempfilepager(text, cmd, color):350def _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 lines
363 finally:364 os.unlink(filename)365366365def _nullpager(stream, text, color):367def _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)373374375class Editor(object):376
183 unmodified lines
modified:click/_unicodefun.py+6 added-3 removed
60 unmodified lines
6162 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 = False7273 # Make sure we're operating on text here.
44 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 '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 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 '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 lines
378379 @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.385386 The keys are supposed to be unique dotted strings. For instance
438 unmodified lines
825826 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 lines
1225 return sorted(rv)122612271228class 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 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: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 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.1443
315 unmodified lines
17591760 def get_usage_pieces(self, ctx):1761 return [self.make_metavar()]17621763 def get_error_hint(self, ctx):1764 return '"%s"' % self.make_metavar()17651766 def add_to_parser(self, parser, ctx):1767 parser.add_argument(dest=self.name, nargs=self.nargs,1768 obj=self)1769
3 unmodified lines
modified:click/decorators.py+10 added-7 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
134 unmodified lines
modified:click/exceptions.py+17 added-9 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)
56 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: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)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: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)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+18 added-5 removed
1import os2import sys3import struct4import inspect5import itertools67from ._compat import raw_input, text_type, string_types, \8 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN9from .utils import echo
211 unmodified lines
221 os.environ.get('COLUMNS', DEFAULT_COLUMNS))222 return int(cr[1]), int(cr[0])223224223def echo_via_pager(text, color=None):225def echo_via_pager(text_or_generator, color=None):226 """This function takes a text and shows it via an environment specific227 pager on stdout.228229 .. versionchanged:: 3.0230 Added the `color` flag.231230 :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)238239 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)245246 # 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)249250 from ._termui_impl import pager238 return pager(text + '\n', color)251 return pager(itertools.chain(text_generator, "\n"), color)252253254def progressbar(iterable=None, length=None, label=None, show_eta=True,255 show_percent=None, show_pos=False,
335 unmodified lines
modified:click/testing.py+52 added-15 removed
71 unmodified lines
7273class Result(object):74 """Holds the captured result of an invoked CLI script."""7576 def __init__(self, runner, output_bytes, exit_code, exception,77 exc_info=None):76 def __init__(self, runner, stdout_bytes, stderr_bytes, exit_code,77 exception, exc_info=None):78 #: The runner that created the result79 self.runner = runner80 #: The output as bytes.81 self.output_bytes = output_bytes80 #: The standard output as bytes.81 self.stdout_bytes = stdout_bytes82 #: The standard error as bytes, or False(y) if not available83 self.stderr_bytes = stderr_bytes84 #: The exit code as integer.85 self.exit_code = exit_code86 #: The exception that happend if one did.87 self.exception = exception
1 unmodified line
89 self.exc_info = exc_info9091 @property92 def output(self):91 """The output as unicode string."""92 return self.output_bytes.decode(self.runner.charset, 'replace') \93 """The (standard) output as unicode string."""94 return self.stdout9596 @property97 def stdout(self):98 """The standard output as unicode string."""99 return self.stdout_bytes.decode(self.runner.charset, 'replace') \100 .replace('\r\n', '\n')101102 @property103 def stderr(self):104 """The standard error as unicode string."""105 if not self.stderr_bytes:106 raise ValueError("stderr not separately captured")107 return self.stderr_bytes.decode(self.runner.charset, 'replace') \108 .replace('\r\n', '\n')109110111 def __repr__(self):96 return '<Result %s>' % (112 return '<%s %s>' % (113 type(self).__name__,114 self.exception and repr(self.exception) or 'okay',115 )116117
10 unmodified lines
128 :param echo_stdin: if this is set to `True`, then reading from stdin writes129 to stdout. This is useful for showing examples in130 some circumstances. Note that regular prompts131 will automatically echo the input.132 :param mix_stderr: if this is set to `False`, then stdout and stderr are133 preserved as independent streams. This is useful for134 Unix-philosophy apps that have predictable stdout and135 noisy stderr, such that each may be measured136 independently137 """138117 def __init__(self, charset=None, env=None, echo_stdin=False):139 def __init__(self, charset=None, env=None, echo_stdin=False,140 mix_stderr=True):141 if charset is None:142 charset = 'utf-8'143 self.charset = charset144 self.env = env or {}145 self.echo_stdin = echo_stdin146 self.mix_stderr = mix_stderr147148 def get_default_prog_name(self, cli):149 """Given a command object it will return the default program name150 for it. The default is the `name` attribute or ``"root"`` if not
36 unmodified lines
187188 env = self.make_env(env)189190 if PY2:167 sys.stdout = sys.stderr = bytes_output = StringIO()191 bytes_output = StringIO()192 if self.echo_stdin:193 input = EchoingStdin(input, bytes_output)194 sys.stdout = bytes_output195 if not self.mix_stderr:196 bytes_error = StringIO()197 sys.stderr = bytes_error198 else:199 bytes_output = io.BytesIO()200 if self.echo_stdin:201 input = EchoingStdin(input, bytes_output)202 input = io.TextIOWrapper(input, encoding=self.charset)175 sys.stdout = sys.stderr = io.TextIOWrapper(203 sys.stdout = io.TextIOWrapper(204 bytes_output, encoding=self.charset)205 if not self.mix_stderr:206 bytes_error = io.BytesIO()207 sys.stderr = io.TextIOWrapper(208 bytes_error, encoding=self.charset)209210 if self.mix_stderr:211 sys.stderr = sys.stdout212213 sys.stdin = input214215 def visible_input(prompt=None):216 sys.stdout.write(prompt or '')
40 unmodified lines
257 except Exception:258 pass259 else:260 os.environ[key] = value226 yield bytes_output261 yield (bytes_output, not self.mix_stderr and bytes_error)262 finally:263 for key, value in iteritems(old_env):264 if value is None:265 try:
11 unmodified lines
277 clickpkg.utils.should_strip_ansi = old_should_strip_ansi278 clickpkg.formatting.FORCED_WIDTH = old_forced_width279280 def invoke(self, cli, args=None, input=None, env=None,246 catch_exceptions=True, color=False, **extra):281 catch_exceptions=True, color=False, mix_stderr=False, **extra):282 """Invokes a command in an isolated environment. The arguments are283 forwarded directly to the command line script, the `extra` keyword284 arguments are passed to the :meth:`~clickpkg.Command.main` function of285 the command.
23 unmodified lines
309 :param color: whether the output should contain color codes. The310 application can still override this explicitly.311 """312 exc_info = None278 with self.isolation(input=input, env=env, color=color) as out:313 with self.isolation(input=input, env=env, color=color) as outstreams:314 exception = None315 exit_code = 0316317 if isinstance(args, string_types):
23 unmodified lines
341 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()347348 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 lines
modified:click/types.py+10 added-7 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
137 unmodified lines
276 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)285286 def __repr__(self):
117 unmodified lines
404 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.pathsep415416 def __init__(self, exists=False, file_okay=True, dir_okay=True,
178 unmodified lines
modified:click/utils.py+1 added-1 removed
182 unmodified lines
183 - add transparent handling of ANSI color codes on Windows.184 - hide ANSI codes automatically if the destination file is not a185 terminal.186187 .. _colorama: http://pypi.python.org/pypi/colorama187 .. _colorama: https://pypi.org/project/colorama/188189 .. versionchanged:: 6.0190 As of Click 6.0 the echo function will properly support unicode191 output on the windows console. Not that click does not modify
225 unmodified lines
modified:docs/_templates/sidebarintro.html+1 added-1 removed
5 unmodified lines
6</p>7<h3>Useful Links</h3>8<ul>9 <li><a href="http://click.pocoo.org/">The Click Website</a></li>10 <li><a href="http://pypi.python.org/pypi/click">click @ PyPI</a></li>10 <li><a href="https://pypi.org/project/click/">click @ PyPI</a></li>11 <li><a href="http://github.com/pallets/click">click @ github</a></li>12 <li><a href="http://github.com/pallets/click/issues">Issue Tracker</a></li>13</ul>
modified:docs/advanced.rst+3 added-3 removed
293 unmodified lines
294 ))295 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')296 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)297 def cli(verbose, timeit_args):298 """A wrapper around Python's timeit."""299 cmdline = ['python', '-mtimeit'] + list(timeit_args)298 """A fake wrapper around Python's timeit."""299 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)300 if verbose:301 click.echo('Invoking: %s' % ' '.join(cmdline))302 call(cmdline)303
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
51 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/clickdoctools.py+8 added-1 removed
15 unmodified lines
1617from sphinx.domains import Domain18from sphinx.util.compat 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+1 added-1 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::
522 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+5 added
290 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+2 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
68 unmodified lines
modified:docs/python3.rst+1 added-1 removed
4 unmodified lines
56Click supports Python 3, but like all other command line utility libraries,7it suffers from the Unicode text model in Python 3. All examples in the8documentation were written so that they could run on both Python 2.x and9Python 3.3 or higher.9Python 3.4 or higher.1011At the moment, it is strongly recommended to use Python 2 for Click12utilities unless Python 3 is a hard requirement.13
170 unmodified lines
modified:docs/quickstart.rst+1 added-1 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::
216 unmodified lines
modified:docs/utils.rst+12 added-1 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
277 unmodified lines
modified:examples/bashcompletion/bashcompletion.py+12 added-2 removed
1import click2import os345@click.group()6def cli():7 pass8910def 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 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']24 return users31 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)
2 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+2 added-2 removed
186 unmodified lines
187 click.echo('arg:' + '|'.join(arg))188189 result = runner.invoke(cmd2, [])190 assert result.exit_code == 2191 assert 'Missing argument "arg"' in result.output191 assert 'Missing argument "ARG..."' in result.output192193194def test_missing_arg(runner):195 @click.command()
2 unmodified lines
198 click.echo('arg:' + arg)199200 result = runner.invoke(cmd, [])201 assert result.exit_code == 2202 assert 'Missing argument "arg".' in result.output202 assert 'Missing argument "ARG".' in result.output203204205def test_implicit_non_required(runner):206 @click.command()
83 unmodified lines
modified:tests/test_bashcomplete.py+25 added-8 removed
84 unmodified lines
8586 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 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 pass106
2 unmodified lines
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']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']121122123def test_chaining():124 @click.group('cli', chain=True)
7 unmodified lines
132 pass133134 @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 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']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']156157158def test_argument_choice():159 @click.command()
111 unmodified lines
271 @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))272 def bsub(bsub_opt):273 pass274258 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 lines
modified:tests/test_basic.py+23 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):
202 unmodified lines
411412def test_evaluation_order(runner):413 called = []414393 def memo(ctx, value):415 def memo(ctx, param, value):416 called.append(value)417 return value418419 @click.command()
79 unmodified lines
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+44 added-8 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.',
35 unmodified lines
158 assert result.output.splitlines() == [159 'Usage: cmd [OPTIONS] ARG',160 'Try "cmd --help" for help.',161 '',162 'Error: Missing argument "arg".'162 'Error: Missing argument "ARG".'163 ]164165166def test_formatting_usage_error_metavar_missing_arg(runner):167 """168 :author: @r-m-n169 Including attribution to #612170 """171 @click.command()172 @click.argument('arg', metavar='metavar')173 def cmd(arg):174 pass175176 result = runner.invoke(cmd, [])177 assert result.exit_code == 2178 assert result.output.splitlines() == [179 'Usage: cmd [OPTIONS] metavar',180 'Try "cmd --help" for help.',181 '',182 'Error: Missing argument "metavar".'183 ]184185186def test_formatting_usage_error_metavar_bad_arg(runner):187 @click.command()188 @click.argument('arg', type=click.INT, metavar='metavar')189 def cmd(arg):190 pass191192 result = runner.invoke(cmd, ['3.14'])193 assert result.exit_code == 2194 assert result.output.splitlines() == [195 'Usage: cmd [OPTIONS] metavar',196 'Try "cmd --help" for help.',197 '',198 'Error: Invalid value for "metavar": 3.14 is not a valid integer'199 ]200201202def test_formatting_usage_error_nested(runner):203 @click.group()204 def cmd():205 pass
8 unmodified lines
214 assert result.output.splitlines() == [215 'Usage: cmd foo [OPTIONS] BAR',216 'Try "cmd foo --help" for help.',217 '',182 'Error: Missing argument "bar".'218 'Error: Missing argument "BAR".'219 ]220221222def test_formatting_usage_error_no_help(runner):
6 unmodified lines
229 assert result.exit_code == 2230 assert result.output.splitlines() == [231 'Usage: cmd [OPTIONS] ARG',232 '',197 'Error: Missing argument "arg".'233 'Error: Missing argument "ARG".'234 ]235236237def test_formatting_usage_custom_help(runner):
7 unmodified lines
245 assert result.output.splitlines() == [246 'Usage: cmd [OPTIONS] ARG',247 'Try "cmd --man" for help.',248 '',213 'Error: Missing argument "arg".'249 'Error: Missing argument "ARG".'250 ]
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', 'errno'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+31 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):
106 unmodified lines
198 assert result.output == 'x|1\ny|2\n'199200201def 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 lines
310 assert 'I am a help text' in result.output311 assert 'you wont see me' not in result.output312313314def test_option_custom_class_reusable(runner):315 """Ensure we can reuse a custom class option. See Issue #926"""316317 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')321322 # Assign to a variable to re-use the decorator.323 testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')324325 @click.command()326 @testoption327 def cmd1(testoption):328 click.echo(testoption)329330 @click.command()331 @testoption332 def cmd2(testoption):333 click.echo(testoption)334335 # Both of the commands should have the --help option now.336 for cmd in (cmd1, cmd2):337338 result = runner.invoke(cmd, ['--help'])339 assert 'I am a help text' in result.output340 assert 'you wont see me' not in result.output341342343def test_aliases_for_flags(runner):344 @click.command()345 @click.option('--warnings/--no-warnings', ' /-W', default=True)346 def cli(warnings):
46 unmodified lines
modified:tests/test_termui.py+15 added-2 removed
42 unmodified lines
43 result = runner.invoke(cli, [])44 assert result.exception is None454647def test_progressbar_hidden(runner, monkeypatch):48 label = 'whatever'4950 @click.command()51 def cli():52 with click.progressbar(tuple(range(10)), label=label) as progress:53 for thing in progress:54 pass5556 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)57 assert runner.invoke(cli, []).output == ''585960def 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 lines
77 assert '(none, day, week, month)' not in result.output787980def 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 lines
203204 assert os.environ == env_orig205206207def test_stderr():208 @click.command()209 def cli_stderr():210 click.echo("stdout")211 click.echo("stderr", err=True)212213 runner = CliRunner(mix_stderr=False)214215 result = runner.invoke(cli_stderr)216217 assert result.output == 'stdout\n'218 assert result.stdout == 'stdout\n'219 assert result.stderr == 'stderr\n'220221 runner_mix = CliRunner(mix_stderr=True)222 result_mix = runner_mix.invoke(cli_stderr)223224 assert result_mix.output == 'stdout\nstderr\n'225 assert result_mix.stdout == 'stdout\nstderr\n'226227 with pytest.raises(ValueError):228 result_mix.stderr229230231@pytest.mark.parametrize('args, expected_output', [232 (None, 'bar\n'),233 ([], 'bar\n'),234 ('', 'bar\n'),
14 unmodified lines
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()
added:.coveragerc+3 added
1[run]2branch = true3source = click,tests
modified:.gitignore+2 added
1 unmodified line
2*.pyc3*.pyo4*.egg-ignore5*.egg-info6.pytest_cache7dist8build9docs/_build10click.egg-info11venv/12.tox13.cache14.ropeproject15.idea
deleted:.travis-colorama-requirements.txt-1 removed
1colorama
deleted:.travis-default-requirements.txt
modified:.travis.yml+22 added-7 removed
1sudo: false2language: python3python:3 - "2.6"4 - "2.7"5 - "3.3"5 - "3.4"6 - "3.5"7 - "3.6"8 - "pypy"910env:12 - REQUIREMENTS=colorama13 - REQUIREMENTS=default11 - TEST_EXTRA=12 - TEST_EXTRA=colorama1314install:16 - pip install -r .travis-$REQUIREMENTS-requirements.txt17 - pip install --editable .15 - pip install tox1619script: make test17script: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 +x3132branches:33 only:34 - master
1 unmodified line
36 - /^.*-maintenance$/3738notifications:39 email: false4041after_success:42 - pip install codecov43 - travis_retry codecov --env TOXENV -X fix search gcov --required --flags $TOX_PY $TEST_EXTRA
modified:CHANGES+18 added-1 removed
21 unmodified lines
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 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.4344Version 6.845-----------46
4 unmodified lines
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-----------61
342 unmodified lines
modified:CONTRIBUTING.rst+1 added-1 removed
39 unmodified lines
40Running the testsuite41---------------------4243You probably want to set up a `virtualenv44<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
deleted:README-20 removed
1$ click_23 Click is a Python package for creating beautiful command line interfaces4 in a composable way with as little code as necessary. It's the "Command5 Line Interface Creation Kit". It's highly configurable but comes with6 sensible defaults out of the box.78 It aims to make the process of writing command line tools quick and fun9 while also preventing any frustration caused by the inability to implement10 an intended CLI API.1112 Click in three points:1314 - arbitrary nesting of commands15 - automatic help page generation16 - supports lazy loading of subcommands at runtime1718 Read the docs at http://click.pocoo.org/1920 This library is stable and active. Feedback is always welcome!
added:README.rst+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+3 added
1 unmodified line
2universal=134[metadata]5license_file = LICENSE67[tool:pytest]8addopts = -p no:warnings --tb=short
modified:setup.py+22 added-6 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import io4import re2import ast5from setuptools import setup678_version_re = re.compile(r'__version__\s+=\s+(.*)')9109with open('click/__init__.py', 'rb') as f:10 version = str(ast.literal_eval(_version_re.search(11 f.read().decode('utf-8')).group(1)))11with io.open('README.rst', 'rt', encoding='utf8') as f:12 readme = f.read()1314with io.open('click/__init__.py', 'rt', encoding='utf8') as f:15 version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)1617setup(18 name='click',19 version=version,20 url='https://www.palletsprojects.com/p/click/',21 author='Armin Ronacher',22 author_email='armin.ronacher@active-4.com',18 version=version,19 url='http://github.com/pallets/click',23 maintainer='Pallets team',24 maintainer_email='contact@palletsprojects.com',25 long_description=readme,26 packages=['click'],27 description='A simple wrapper around optparse for '28 'powerful command line utilities.',29 license='BSD',30 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]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