Merge remote-tracking branch 'click/master' into feature/bash_autocompletion_6.6
Before adoption: this commit came in with the history the project adopted, so no landing records it.
# Conflicts: # click/__init__.py # click/_bashcomplete.py # tests/test_bashcomplete.py
authored by Nicholas Wiles · committed by Nicholas Wiles · parents dcc0719, c3da861 · Browse files · 36 files·+559 added−124 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
36 files+559 added−124 removed
- tests:+286 added−16 removed
- other:+273 added−108 removed
Provenance
- Commit
4fd8955- Tree
031e156- Author
Nicholas Wiles <nwiles@google.com>- Committer
Nicholas Wiles <nwiles@google.com>- Parent 1
dcc0719- Parent 2
c3da861
36 files changed+559 added−124 removed
modified:click/__init__.py+3 added-3 removed
26 unmodified lines27 password_option, version_option, help_option28 29 # Types30 from .types import ParamType, File, Path, Choice, IntRange, Tuple, \31- STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED31+ STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange32 33 # Utilities34 from .utils import echo, get_binary_stream, get_text_stream, open_file, \35 format_filename, get_app_dir, get_os_args29 unmodified lines65 'version_option', 'help_option',66 67 # Types68 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple', 'STRING',69- 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',69+ 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED', 'FloatRange'70 71 # Utilities72 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',73 'format_filename', 'get_app_dir', 'get_os_args',20 unmodified lines94 # literals.95 disable_unicode_literals_warning = False96 97 98-__version__ = '6.6.bashautocompletion'98+__version__ = '7.0-dev'modified:click/_bashcomplete.py+1 added-1 removed
27 unmodified lines28 29 30 def resolve_ctx(cli, prog_name, args):31 ctx = cli.make_context(prog_name, args, resilient_parsing=True)32- while ctx.args + ctx.protected_args and isinstance(ctx.command, MultiCommand):32+ while ctx.protected_args + ctx.args and isinstance(ctx.command, MultiCommand):33 a = ctx.protected_args + ctx.args34 cmd = ctx.command.get_command(ctx, a[0])35 if cmd is None:36 return None61 unmodified linesmodified:click/_compat.py+12 added-3 removed
6 unmodified lines7 8 9 PY2 = sys.version_info[0] == 210 WIN = sys.platform.startswith('win')11+CYGWIN = sys.platform.startswith('cygwin')12 DEFAULT_COLUMNS = 8013 14 15 _ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')123 unmodified lines139 text_type = unicode140 bytes = str141 raw_input = raw_input142 string_types = (str, unicode)143+ int_types = (int, long)144 iteritems = lambda x: x.iteritems()145 range_type = xrange146 147 def is_bytes(x):13 unmodified lines161 # correct option here.162 #163 # This code also lives in _winconsole for the fallback to the console164 # emulation stream.163- if WIN:165+ #166+ # There are also Windows environments where the `msvcrt` module is not167+ # available (which is why we use try-catch instead of the WIN variable168+ # here), such as the Google App Engine development server on Windows. In169+ # those cases there is just nothing we can do.170+ try:171 import msvcrt172+ except ImportError:173+ set_binary_mode = lambda x: x174+ else:175 def set_binary_mode(f):176 try:177 fileno = f.fileno()178 except Exception:179 pass180 else:181 msvcrt.setmode(fileno, os.O_BINARY)182 return f173- else:174- set_binary_mode = lambda x: x183 184 def isidentifier(x):185 return _identifier_re.search(x) is not None186 32 unmodified lines219 import io220 text_type = str221 raw_input = input222 string_types = (str,)223+ int_types = (int,)224 range_type = range225 isidentifier = lambda x: x.isidentifier()226 iteritems = lambda x: iter(x.items())227 424 unmodified linesmodified:click/_termui_impl.py+12 added-3 removed
12 unmodified lines13 import sys14 import time15 import math16 from ._compat import _default_text_stdout, range_type, PY2, isatty, \17- open_stream, strip_ansi, term_len, get_best_encoding, WIN17+ open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \18+ CYGWIN19 from .utils import echo20 from .exceptions import ClickException21 22 8 unmodified lines31 def _length_hint(obj):32 """Returns the length hint of an object."""33 try:34 return len(obj)34- except TypeError:35+ except (AttributeError, TypeError):36 try:37 get_hint = type(obj).__length_hint__38 except AttributeError:39 return None1 unmodified line41 hint = get_hint(obj)42 except TypeError:43 return None44 if hint is NotImplemented or \44- not isinstance(hint, (int, long)) or \45+ not isinstance(hint, int_types) or \46 hint < 0:47 return None48 return hint49 428 unmodified lines478 else:479 args = 'start %s "" "%s"' % (480 wait and '/WAIT' or '', url.replace('"', ''))481 return os.system(args)482+ elif CYGWIN:483+ if locate:484+ url = _unquote_file(url)485+ args = 'cygstart "%s"' % (os.path.dirname(url).replace('"', ''))486+ else:487+ args = 'cygstart %s "%s"' % (488+ wait and '-w' or '', url.replace('"', ''))489+ return os.system(args)490 491 try:492 if locate:493 url = os.path.dirname(_unquote_file(url)) or '.'63 unmodified linesmodified:click/_unicodefun.py+5 added-4 removed
12 unmodified lines13 14 15 def _find_unicode_literals_frame():16 import __future__17+ if not hasattr(sys, '_getframe'): # not all Python implementations have it18+ return 019 frm = sys._getframe(1)20 idx = 121 while frm is not None:22 if frm.f_globals.get('__name__', '').startswith('click.'):72 unmodified lines95 )96 else:97 extra += (98 'This system lists a couple of UTF-8 supporting locales that\n'97- 'you can pick from. The following suitable locales where\n'99+ 'you can pick from. The following suitable locales were\n'100 'discovered: %s'101 ) % ', '.join(sorted(good_locales))102 103 bad_locale = None11 unmodified lines115 ) % bad_locale116 117 raise RuntimeError('Click will abort further execution because Python 3 '118 'was configured to use ASCII as encoding for the '117- 'environment. Either run this under Python 2 or '118- 'consult http://click.pocoo.org/python3/ for '119- 'mitigation steps.' + extra)119+ 'environment. Consult http://click.pocoo.org/python3/'120+ 'for mitigation steps.' + extra)modified:click/_winconsole.py+1 added-1 removed
259 unmodified lines260 hasattr(f, 'isatty') and f.isatty():261 func = _stream_factories.get(f.fileno())262 if func is not None:263 if not PY2:264- f = getattr(f, 'buffer')264+ f = getattr(f, 'buffer', None)265 if f is None:266 return None267 else:268 # If we are on Python 2 we need to set the stream that we5 unmodified linesmodified:click/core.py+25 added-9 removed
1+import errno2 import os3 import sys4 from contextlib import contextmanager5 from itertools import repeat648 unmodified lines654 the program name is constructed by taking the file655 name from ``sys.argv[0]``.656 :param complete_var: the environment variable that controls the657 bash completion support. The default is657- ``"_<prog_name>_COMPLETE"`` with prog name in658+ ``"_<prog_name>_COMPLETE"`` with prog_name in659 uppercase.660 :param standalone_mode: the default behavior is to invoke the script661 in standalone mode. Click will then662 handle exceptions and convert them into6 unmodified lines669 :param extra: extra keyword arguments are forwarded to the context670 constructor. See :class:`Context` for more information.671 """672 # If we are in Python 3, we will verify that the environment is672- # sane at this point of reject further execution to avoid a673+ # sane at this point or reject further execution to avoid a674 # broken script.675 if not PY2:676 _verify_python3_env()677 else:27 unmodified lines705 if not standalone_mode:706 raise707 e.show()708 sys.exit(e.exit_code)709+ except IOError as e:710+ if e.errno == errno.EPIPE:711+ sys.exit(1)712+ else:713+ raise714 except Abort:715 if not standalone_mode:716 raise717 echo('Aborted!', file=sys.stderr)24 unmodified lines742 :param short_help: the short help to use for this command. This is743 shown on the command listing of the parent command.744 :param add_help_option: by default each command registers a ``--help``745 option. This can be disabled by this parameter.746+ :param hidden: hide this command from help outputs.747 """748 749 def __init__(self, name, context_settings=None, callback=None,750 params=None, help=None, epilog=None, short_help=None,744- options_metavar='[OPTIONS]', add_help_option=True):751+ options_metavar='[OPTIONS]', add_help_option=True,752+ hidden=False):753 BaseCommand.__init__(self, name, context_settings)754 #: the callback to execute when the command fires. This might be755 #: `None` in which case nothing happens.756 self.callback = callback7 unmodified lines764 if short_help is None and help:765 short_help = make_default_short_help(help)766 self.short_help = short_help767 self.add_help_option = add_help_option768+ self.hidden = hidden769 770 def get_usage(self, ctx):771 formatter = ctx.make_formatter()772 self.format_usage(ctx, formatter)231 unmodified lines1004 cmd = self.get_command(ctx, subcommand)1005 # What is this, the tool lied about a command. Ignore it1006 if cmd is None:1007 continue1008+ if cmd.hidden:1009+ continue1010 1011 help = cmd.short_help or ''1012 rows.append((subcommand, help))1013 415 unmodified lines1429 All other parameters are passed onwards to the parameter constructor.1430 1431 :param show_default: controls if the default value should be shown on the1432 help page. Normally, defaults are not shown.1422- :param prompt: if set to `True` or a non empty string then the user will1423- be prompted for input if not set. If set to `True` the1424- prompt will be the option name capitalized.1433+ :param prompt: if set to `True` or a non empty string then the user will be1434+ prompted for input. If set to `True` the prompt will be the1435+ option name capitalized.1436 :param confirmation_prompt: if set then the value will need to be confirmed1437 if it was prompted for.1438 :param hide_input: if this is `True` then the input on the prompt will be1439 hidden from the user. This is useful for password12 unmodified lines1452 parameter will be pulled from an environment1453 variable in case a prefix is defined on the1454 context.1455 :param help: the help string.1456+ :param hidden: hide this option from help outputs.1457 """1458 param_type_name = 'option'1459 1460 def __init__(self, param_decls=None, show_default=False,1461 prompt=False, confirmation_prompt=False,1462 hide_input=False, is_flag=None, flag_value=None,1463 multiple=False, count=False, allow_from_autoenv=True,1452- type=None, help=None, **attrs):1464+ type=None, help=None, hidden=False, show_choices=True, **attrs):1465 default_is_missing = attrs.get('default', _missing) is _missing1466 Parameter.__init__(self, param_decls, type=type, **attrs)1467 1468 if prompt is True:4 unmodified lines1473 prompt_text = prompt1474 self.prompt = prompt_text1475 self.confirmation_prompt = confirmation_prompt1476 self.hide_input = hide_input1477+ self.hidden = hidden1478 1479 # Flags1480 if is_flag is None:1481 if flag_value is not None:24 unmodified lines1506 self.multiple = multiple1507 self.allow_from_autoenv = allow_from_autoenv1508 self.help = help1509 self.show_default = show_default1510+ self.show_choices = show_choices1511 1512 # Sanity check for stuff we don't support1513 if __debug__:1514 if self.nargs < 0:87 unmodified lines1602 kwargs['action'] = action1603 parser.add_option(self.opts, **kwargs)1604 1605 def get_help_record(self, ctx):1606+ if self.hidden:1607+ return1608 any_prefix_is_slash = []1609 1610 def _write_opts(opts):1611 rv, any_slashes = join_options(opts)46 unmodified lines1658 # differently.1659 if self.is_bool_flag:1660 return confirm(self.prompt, default)1661 1646- return prompt(self.prompt, default=default,1647- hide_input=self.hide_input,1662+ return prompt(self.prompt, default=default, type=self.type,1663+ hide_input=self.hide_input, show_choices=self.show_choices,1664 confirmation_prompt=self.confirmation_prompt,1665 value_proc=lambda x: self.process_value(ctx, x))1666 1667 def resolve_envvar_value(self, ctx):89 unmodified linesmodified:click/decorators.py+5 added-1 removed
233 unmodified lines234 (``'%(prog)s, version %(version)s'``)235 :param others: everything else is forwarded to :func:`option`.236 """237 if version is None:238+ if hasattr(sys, '_getframe'):238- module = sys._getframe(1).f_globals.get('__name__')239+ module = sys._getframe(1).f_globals.get('__name__')240+ else:241+ module = ''242+243 def decorator(f):244 prog_name = attrs.pop('prog_name', None)245 message = attrs.pop('message', '%(prog)s, version %(version)s')246 62 unmodified linesmodified:click/exceptions.py+21 added-5 removed
7 unmodified lines8 #: The exit code for this exception9 exit_code = 110 11 def __init__(self, message):12+ ctor_msg = message13 if PY2:13- if message is not None:14- message = message.encode('utf-8')15- Exception.__init__(self, message)14+ if ctor_msg is not None:15+ ctor_msg = ctor_msg.encode('utf-8')16+ Exception.__init__(self, ctor_msg)17 self.message = message18 19 def format_message(self):20 return self.message21 22+ def __unicode__(self):23+ return self.message24+25+ def __str__(self):26+ return self.message.encode('utf-8')27+28 def show(self, file=None):29 if file is None:30 file = get_text_stderr()31 echo('Error: %s' % self.format_message(), file=file)11 unmodified lines43 44 def __init__(self, message, ctx=None):45 ClickException.__init__(self, message)46 self.ctx = ctx47+ self.cmd = self.ctx and self.ctx.command or None48 49 def show(self, file=None):50 if file is None:51 file = get_text_stderr()52 color = None53+ hint = ''54+ if (self.cmd is not None and55+ self.cmd.get_help_option(self.ctx) is not None):56+ hint = ('Try "%s %s" for help.\n'57+ % (self.ctx.command_path, self.ctx.help_option_names[0]))58 if self.ctx is not None:59 color = self.ctx.color47- echo(self.ctx.get_usage() + '\n', file=file, color=color)60+ echo(self.ctx.get_usage() + '\n%s' % hint, file=file, color=color)61 echo('Error: %s' % self.format_message(), file=file, color=color)62 63 64 class BadParameter(UsageError):111 unmodified lines176 was incorrect. This is for instance raised if the number of arguments177 for an option is not correct.178 179 .. versionadded:: 4.0180+181+ :param option_name: the name of the option being used incorrectly.182 """183 169- def __init__(self, message, ctx=None):184+ def __init__(self, option_name, message, ctx=None):185 UsageError.__init__(self, message, ctx)186+ self.option_name = option_name187 188 189 class BadArgumentUsage(UsageError):190 """Raised if an argument is generally supplied but the use of the argument27 unmodified linesmodified:click/parser.py+3 added-3 removed
72 unmodified lines73 74 75 def _error_opt_args(nargs, opt):76 if nargs == 1:77- raise BadOptionUsage('%s option requires an argument' % opt)78- raise BadOptionUsage('%s option requires %d arguments' % (opt, nargs))77+ raise BadOptionUsage(opt, '%s option requires an argument' % opt)78+ raise BadOptionUsage(opt, '%s option requires %d arguments' % (opt, nargs))79 80 81 def split_opt(opt):82 first = opt[:1]258 unmodified lines341 value = tuple(state.rargs[:nargs])342 del state.rargs[:nargs]343 344 elif explicit_value is not None:345- raise BadOptionUsage('%s option does not take a value' % opt)345+ raise BadOptionUsage(opt, '%s option does not take a value' % opt)346 347 else:348 value = None349 77 unmodified linesmodified:click/termui.py+19 added-9 removed
4 unmodified lines5 from ._compat import raw_input, text_type, string_types, \6 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN7 from .utils import echo8 from .exceptions import Abort, UsageError9-from .types import convert_type9+from .types import convert_type, Choice10 from .globals import resolve_color_default11 12 13 # The prompt functions to use. The doc tools currently override these9 unmodified lines23 import getpass24 return getpass.getpass(prompt)25 26 27-def _build_prompt(text, suffix, show_default=False, default=None):27+def _build_prompt(text, suffix, show_default=False, default=None, show_choices=True, type=None):28 prompt = text29+ if type is not None and show_choices and isinstance(type, Choice):30+ prompt += ' (' + ", ".join(map(str, type.choices)) + ')'31 if default is not None and show_default:32 prompt = '%s [%s]' % (prompt, default)33 return prompt + suffix34 35 34-def prompt(text, default=None, hide_input=False,35- confirmation_prompt=False, type=None,36- value_proc=None, prompt_suffix=': ',37- show_default=True, err=False):36+def prompt(text, default=None, hide_input=False, confirmation_prompt=False,37+ type=None, value_proc=None, prompt_suffix=': ', show_default=True,38+ err=False, show_choices=True):39 """Prompts a user for input. This is a convenience function that can40 be used to prompt a user for input later.41 42 If the user aborts the input by sending a interrupt signal, this43 function will catch it and raise a :exc:`Abort` exception.44 45+ .. versionadded:: 7.046+ Added the show_choices parameter.47+48 .. versionadded:: 6.049 Added unicode support for cmd.exe on Windows.50 51 .. versionadded:: 4.012 unmodified lines64 :param prompt_suffix: a suffix that should be added to the prompt.65 :param show_default: shows or hides the default value in the prompt.66 :param err: if set to true the file defaults to ``stderr`` instead of67 ``stdout``, the same as with echo.68+ :param show_choices: Show or hide choices if the passed type is a Choice.69+ For example if type is a Choice of either day or week,70+ show_choices is true and text is "Group by" then the71+ prompt will be "Group by (day, week): ".72 """73 result = None74 75 def prompt_func(text):13 unmodified lines89 90 if value_proc is None:91 value_proc = convert_type(type, default)92 85- prompt = _build_prompt(text, prompt_suffix, show_default, default)93+ prompt = _build_prompt(text, prompt_suffix, show_default, default, show_choices, type)94 95 while 1:96 while 1:97 value = prompt_func(prompt)314 unmodified lines412 """413 return strip_ansi(text)414 415 408-def secho(text, file=None, nl=True, err=False, color=None, **styles):416+def secho(message=None, file=None, nl=True, err=False, color=None, **styles):417 """This function combines :func:`echo` and :func:`style` into one418 call. As such the following two calls are the same::419 420 click.secho('Hello World!', fg='green')3 unmodified lines424 depending on which one they go with.425 426 .. versionadded:: 2.0427 """428+ if message is not None:429+ message = style(message, **styles)420- return echo(style(text, **styles), file=file, nl=nl, err=err, color=color)430+ return echo(message, file=file, nl=nl, err=err, color=color)431 432 433 def edit(text=None, editor=None, env=None, require_save=True,434 extension='.txt', filename=None):115 unmodified linesmodified:click/testing.py+19 added-8 removed
1 unmodified line2 import sys3 import shutil4 import tempfile5 import contextlib6+import shlex7 7-from ._compat import iteritems, PY28+from ._compat import iteritems, PY2, string_types9 10 11 # If someone wants to vendor click, we want to ensure the12 # correct package is discovered. Ideally we could use a183 unmodified lines196 sys.stdout.flush()197 return char198 199 default_color = color200+201 def should_strip_ansi(stream=None, color=None):202 if color is None:203 return not default_color204 return not color9 unmodified lines214 215 old_env = {}216 try:217 for key, value in iteritems(env):216- old_env[key] = os.environ.get(value)218+ old_env[key] = os.environ.get(key)219 if value is None:220 try:221 del os.environ[key]222 except Exception:38 unmodified lines261 .. versionadded:: 4.0262 The ``color`` parameter was added.263 264 :param cli: the command to invoke263- :param args: the arguments to invoke265+ :param args: the arguments to invoke. It may be given as an iterable266+ or a string. When given as string it will be interpreted267+ as a Unix shell command. More details at268+ :func:`shlex.split`.269 :param input: the input data for `sys.stdin`.270 :param env: the environment overrides.271 :param catch_exceptions: Whether to catch any other exceptions than272 ``SystemExit``.5 unmodified lines278 with self.isolation(input=input, env=env, color=color) as out:279 exception = None280 exit_code = 0281 282+ if isinstance(args, string_types):283+ args = shlex.split(args)284+285 try:286 cli.main(args=args or (),287 prog_name=self.get_default_prog_name(cli), **extra)288 except SystemExit as e:281- if e.code != 0:282- exception = e283-289 exc_info = sys.exc_info()285-290 exit_code = e.code291+ if exit_code is None:292+ exit_code = 0293+294+ if exit_code != 0:295+ exception = e296+297 if not isinstance(exit_code, int):298 sys.stdout.write(str(exit_code))299 sys.stdout.write('\n')300 exit_code = 1301+302 except Exception as e:303 if not catch_exceptions:304 raise305 exception = e295- exit_code = -1306+ exit_code = 1307 exc_info = sys.exc_info()308 finally:309 sys.stdout.flush()310 output = out.getvalue()23 unmodified linesmodified:click/types.py+57 added-16 removed
212 unmodified lines213 def __repr__(self):214 return 'IntRange(%r, %r)' % (self.min, self.max)215 216 217+class FloatParamType(ParamType):218+ name = 'float'219+220+ def convert(self, value, param, ctx):221+ try:222+ return float(value)223+ except (UnicodeError, ValueError):224+ self.fail('%s is not a valid floating point value' %225+ value, param, ctx)226+227+ def __repr__(self):228+ return 'FLOAT'229+230+231+class FloatRange(FloatParamType):232+ """A parameter that works similar to :data:`click.FLOAT` but restricts233+ the value to fit into a range. The default behavior is to fail if the234+ value falls outside the range, but it can also be silently clamped235+ between the two edges.236+237+ See :ref:`ranges` for an example.238+ """239+ name = 'float range'240+241+ def __init__(self, min=None, max=None, clamp=False):242+ self.min = min243+ self.max = max244+ self.clamp = clamp245+246+ def convert(self, value, param, ctx):247+ rv = FloatParamType.convert(self, value, param, ctx)248+ if self.clamp:249+ if self.min is not None and rv < self.min:250+ return self.min251+ if self.max is not None and rv > self.max:252+ return self.max253+ if self.min is not None and rv < self.min or \254+ self.max is not None and rv > self.max:255+ if self.min is None:256+ self.fail('%s is bigger than the maximum valid value '257+ '%s.' % (rv, self.max), param, ctx)258+ elif self.max is None:259+ self.fail('%s is smaller than the minimum valid value '260+ '%s.' % (rv, self.min), param, ctx)261+ else:262+ self.fail('%s is not in the valid range of %s to %s.'263+ % (rv, self.min, self.max), param, ctx)264+ return rv265+266+ def __repr__(self):267+ return 'FloatRange(%r, %r)' % (self.min, self.max)268+269+270 class BoolParamType(ParamType):271 name = 'boolean'272 273 def convert(self, value, param, ctx):9 unmodified lines283 def __repr__(self):284 return 'BOOL'285 286 234-class FloatParamType(ParamType):235- name = 'float'236-237- def convert(self, value, param, ctx):238- try:239- return float(value)240- except (UnicodeError, ValueError):241- self.fail('%s is not a valid floating point value' %242- value, param, ctx)243-244- def __repr__(self):245- return 'FLOAT'246-247-287 class UUIDParameterType(ParamType):288 name = 'uuid'289 290 def convert(self, value, param, ctx):105 unmodified lines396 :param writable: if true, a writable check is performed.397 :param readable: if true, a readable check is performed.398 :param resolve_path: if this is true, then the path is fully resolved399 before the value is passed onwards. This means361- that it's absolute and symlinks are resolved.400+ that it's absolute and symlinks are resolved. It401+ will not expand a tilde-prefix, as this is402+ supposed to be done by the shell only.403 :param allow_dash: If this is set to `True`, a single dash to indicate404 standard streams is permitted.405 :param type: optionally a string type that should be used to406 represent the path. The default is `None` which17 unmodified lines424 425 if self.file_okay and not self.dir_okay:426 self.name = 'file'427 self.path_type = 'File'387- if self.dir_okay and not self.file_okay:428+ elif self.dir_okay and not self.file_okay:429 self.name = 'directory'430 self.path_type = 'Directory'431 else:432 self.name = 'path'159 unmodified linesmodified:click/utils.py+2 added-1 removed
41 unmodified lines42 return text_type(value)43 44 45 def make_default_short_help(help, max_length=45):46+ """Return a condensed version of help string."""47 words = help.split()48 total_length = 049 result = []50 done = False120 unmodified lines171 matter how badly configured the system is.172 173 Primarily it means that you can print binary data as well as Unicode174 data on both 2.x and 3.x to the given file in the most appropriate way174- possible. This is a very carefree function as in that it will try its175+ possible. This is a very carefree function in that it will try its176 best to not fail. As of Click 6.0 this includes support for unicode177 output on the Windows console.178 179 In addition to that, if `colorama`_ is installed, the echo function will237 unmodified linesmodified:docs/_templates/sidebarintro.html+2 added-2 removed
6 unmodified lines7 <h3>Useful Links</h3>8 <ul>9 <li><a href="http://click.pocoo.org/">The Click Website</a></li>10 <li><a href="http://pypi.python.org/pypi/click">click @ PyPI</a></li>11- <li><a href="http://github.com/mitsuhiko/click">click @ github</a></li>12- <li><a href="http://github.com/mitsuhiko/click/issues">Issue Tracker</a></li>11+ <li><a href="http://github.com/pallets/click">click @ github</a></li>12+ <li><a href="http://github.com/pallets/click/issues">Issue Tracker</a></li>13 </ul>modified:docs/advanced.rst+2 added-2 removed
275 unmodified lines276 command will abort with an error that there are leftover arguments.277 If you go with this solution, the extra arguments will be collected in278 :attr:`Context.args`.279 2. You can attach a :func:`argument` with ``nargs`` set to `-1` which280- will eat up all leftover arguments. In this case it's recommeded to280+ will eat up all leftover arguments. In this case it's recommended to281 set the `type` to :data:`UNPROCESSED` to avoid any string processing282 on those arguments as otherwise they are forced into unicode strings283 automatically which is often not what you want.284 60 unmodified lines345 346 .. versionadded:: 5.0347 348 Starting with Click 5.0 it is possible to access the current context from349-anywhere within the same through through the use of the349+anywhere within the same thread through the use of the350 :func:`get_current_context` function which returns it. This is primarily351 useful for accessing the context bound object as well as some flags that352 are stored on it to customize the runtime behavior. For instance the353 :func:`echo` function does this to infer the default value of the `color`26 unmodified linesmodified:docs/bashcomplete.rst+1 added-1 removed
78 unmodified lines79 with dashes replaced by underscores.80 81 If your tool is called ``foo-bar``, then the magic variable is called82 ``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will83-spit out the activation script which can be trivally activated.83+spit out the activation script which can be trivially activated.84 85 For instance, to enable Bash completion for your ``foo-bar`` script, this86 is what you would need to put into your ``.bashrc``::87 20 unmodified linesmodified:docs/commands.rst+2 added-2 removed
415 unmodified lines416 :func:`open_file`.417 418 For a more complex example that also improves upon handling of the419 pipelines have a look at the `imagepipe multi command chaining demo420-<https://github.com/mitsuhiko/click/tree/master/examples/imagepipe>`__ in420+<https://github.com/pallets/click/tree/master/examples/imagepipe>`__ in421 the Click repository. It implements a pipeline based image editing tool422 that has a nice internal structure for the pipelines.423 424 11 unmodified lines436 you're not satisfied with the defaults.437 438 The default map can be nested arbitrarily for each subcommand and439 provided when the script is invoked. Alternatively, it can also be440-overriden at any point by commands. For instance, a top-level command could440+overridden at any point by commands. For instance, a top-level command could441 load the defaults from a configuration file.442 443 Example usage:444 114 unmodified linesmodified:docs/parameters.rst+3 added
65 unmodified lines66 67 .. autoclass:: IntRange68 :noindex:69 70+.. autoclass:: FloatRange71+ :noindex:72+73 Custom parameter types can be implemented by subclassing74 :class:`click.ParamType`. For simple cases, passing a Python function that75 fails with a `ValueError` is also supported, though discouraged.76 47 unmodified linesmodified:docs/python3.rst+1 added-1 removed
6 unmodified lines7 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.10 11-At the moment, it is strongly recommended is to use Python 2 for Click11+At the moment, it is strongly recommended to use Python 2 for Click12 utilities unless Python 3 is a hard requirement.13 14 .. _python3-limitations:15 168 unmodified linesmodified:docs/quickstart.rst+10 added-10 removed
77 unmodified lines78 And if you want to go back to the real world, use the following command::79 80 $ deactivate81 82-After doing this, the prompt of your shell should be as familar as before.82+After doing this, the prompt of your shell should be as familiar as before.83 84 Now, let's move on. Enter the following command to get Click activated in your85 virtualenv::86 14 unmodified lines101 Examples of Click applications can be found in the documentation as well102 as in the GitHub repository together with readme files:103 104 * ``inout``: `File input and output105- <https://github.com/mitsuhiko/click/tree/master/examples/inout>`_105+ <https://github.com/pallets/click/tree/master/examples/inout>`_106 * ``naval``: `Port of docopt naval example107- <https://github.com/mitsuhiko/click/tree/master/examples/naval>`_107+ <https://github.com/pallets/click/tree/master/examples/naval>`_108 * ``aliases``: `Command alias example109- <https://github.com/mitsuhiko/click/tree/master/examples/aliases>`_109+ <https://github.com/pallets/click/tree/master/examples/aliases>`_110 * ``repo``: `Git-/Mercurial-like command line interface111- <https://github.com/mitsuhiko/click/tree/master/examples/repo>`_111+ <https://github.com/pallets/click/tree/master/examples/repo>`_112 * ``complex``: `Complex example with plugin loading113- <https://github.com/mitsuhiko/click/tree/master/examples/complex>`_113+ <https://github.com/pallets/click/tree/master/examples/complex>`_114 * ``validation``: `Custom parameter validation example115- <https://github.com/mitsuhiko/click/tree/master/examples/validation>`_115+ <https://github.com/pallets/click/tree/master/examples/validation>`_116 * ``colors``: `Colorama ANSI color support117- <https://github.com/mitsuhiko/click/tree/master/examples/colors>`_117+ <https://github.com/pallets/click/tree/master/examples/colors>`_118 * ``termui``: `Terminal UI functions demo119- <https://github.com/mitsuhiko/click/tree/master/examples/termui>`_119+ <https://github.com/pallets/click/tree/master/examples/termui>`_120 * ``imagepipe``: `Multi command chaining demo121- <https://github.com/mitsuhiko/click/tree/master/examples/imagepipe>`_121+ <https://github.com/pallets/click/tree/master/examples/imagepipe>`_122 123 Basic Concepts124 --------------125 149 unmodified linesmodified:docs/upgrading.rst+1 added-1 removed
42 unmodified lines43 44 Multicommand Chaining API45 `````````````````````````46 47-Click 3 introduced multicommand chaning. This required a change in how47+Click 3 introduced multicommand chaining. This required a change in how48 Click internally dispatches. Unfortunately this change was not correctly49 implemented and it appeared that it was possible to provide an API that50 can inform the super command about all the subcommands that will be51 invoked.49 unmodified linesmodified:docs/utils.rst+2 added-2 removed
224 unmodified lines225 226 .. versionadded:: 2.0227 228 Click supports launching applications through :func:`launch`. This can be229-used to open the default application assocated with a URL or filetype.229+used to open the default application associated with a URL or filetype.230 This can be used to launch web browsers or picture viewers, for instance.231 In addition to this, it can also launch the file manager and automatically232 select the provided file.233 31 unmodified lines265 streams respond to Unicode and binary data.266 267 Because of this, click provides the :func:`get_binary_stream` and268 :func:`get_text_stream` functions, which produce consistent results with269-different Python versions and for a wide variety pf terminal configurations.269+different Python versions and for a wide variety of terminal configurations.270 271 The end result is that these functions will always return a functional272 stream object (except in very odd cases in Python 3; see273 :ref:`python3-limitations`).125 unmodified linesmodified:tests/test_bashcomplete.py+45 added-15 removed
1 unmodified line2 3 import click4 from click._bashcomplete import get_choices5 6-def test_basic():6+7+def test_single_command():8+ @click.command()9+ @click.option('--local-opt')10+ def cli(local_opt):11+ pass12+13+ assert list(get_choices(cli, 'lol', [], '-')) == ['--local-opt']14+ assert list(get_choices(cli, 'lol', [], '')) == []15+16+17+def test_small_chain():18 @click.group()19 @click.option('--global-opt')20 def cli(global_opt):21 pass2 unmodified lines24 @click.option('--local-opt')25 def sub(local_opt):26 pass27 17- COLORS = ['red', 'green', 'blue']18- @cli.command()19- @click.argument('color', autocompletion=COLORS)20- def sub2(color):28+ assert list(get_choices(cli, 'lol', [], '')) == ['sub']29+ assert list(get_choices(cli, 'lol', [], '-')) == ['--global-opt']30+ assert list(get_choices(cli, 'lol', ['sub'], '')) == []31+ assert list(get_choices(cli, 'lol', ['sub'], '-')) == ['--local-opt']32+33+34+def test_long_chain():35+ @click.group('cli')36+ @click.option('--cli-opt')37+ def cli(cli_opt):38 pass39 40+ @cli.group('asub')41+ @click.option('--asub-opt')42+ def asub(asub_opt):43+ pass44+45+ @asub.group('bsub')46+ @click.option('--bsub-opt')47+ def bsub(bsub_opt):48+ pass49+50+ COLORS = ['red', 'green', 'blue']51 def get_colors(ctx, args, incomplete):52 return COLORS53 26- @cli.command()54+ @bsub.command('csub')55+ @click.option('--csub-opt')56 @click.argument('color', autocompletion=get_colors)28- def sub3(color):57+ def csub(csub_opt, color):58 pass59 31- assert list(get_choices(cli, 'lol', [], '')) == ['sub', 'sub2', 'sub3']32- assert list(get_choices(cli, 'lol', [], '-')) == ['--global-opt']33- assert list(get_choices(cli, 'lol', ['sub'], '')) == []34- assert list(get_choices(cli, 'lol', ['sub'], '-')) == ['--local-opt']35- assert list(get_choices(cli, 'lol', ['sub2'], '')) == COLORS36- assert list(get_choices(cli, 'lol', ['sub2'], 'g')) == ['green']37- assert list(get_choices(cli, 'lol', ['sub3'], '')) == COLORS38- assert list(get_choices(cli, 'lol', ['sub2'], 'b')) == ['blue']60+ assert list(get_choices(cli, 'lol', [], '-')) == ['--cli-opt']61+ assert list(get_choices(cli, 'lol', [], '')) == ['asub']62+ assert list(get_choices(cli, 'lol', ['asub'], '-')) == ['--asub-opt']63+ assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub']64+ assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '-')) == ['--bsub-opt']65+ assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '')) == ['csub']66+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '-')) == ['--csub-opt']67+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '')) == COLORS68+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], 'b')) == ['blue']modified:tests/test_basic.py+77 added
341 unmodified lines342 assert not result.exception343 assert result.output == '0\n'344 345 346+def test_float_range_option(runner):347+ @click.command()348+ @click.option('--x', type=click.FloatRange(0, 5))349+ def cli(x):350+ click.echo(x)351+352+ result = runner.invoke(cli, ['--x=5.0'])353+ assert not result.exception354+ assert result.output == '5.0\n'355+356+ result = runner.invoke(cli, ['--x=6.0'])357+ assert result.exit_code == 2358+ assert 'Invalid value for "--x": 6.0 is not in the valid range of 0 to 5.\n' \359+ in result.output360+361+ @click.command()362+ @click.option('--x', type=click.FloatRange(0, 5, clamp=True))363+ def clamp(x):364+ click.echo(x)365+366+ result = runner.invoke(clamp, ['--x=5.0'])367+ assert not result.exception368+ assert result.output == '5.0\n'369+370+ result = runner.invoke(clamp, ['--x=6.0'])371+ assert not result.exception372+ assert result.output == '5\n'373+374+ result = runner.invoke(clamp, ['--x=-1.0'])375+ assert not result.exception376+ assert result.output == '0\n'377+378+379 def test_required_option(runner):380 @click.command()381 @click.option('--foo', required=True)382 def cli(foo):46 unmodified lines429 'normal3',430 'normal1',431 'missing',432 ]433+434+435+def test_hidden_option(runner):436+ @click.command()437+ @click.option('--nope', hidden=True)438+ def cli(nope):439+ click.echo(nope)440+441+ result = runner.invoke(cli, ['--help'])442+ assert result.exit_code == 0443+ assert '--nope' not in result.output444+445+446+def test_hidden_command(runner):447+ @click.group()448+ def cli():449+ pass450+451+ @cli.command(hidden=True)452+ def nope():453+ pass454+455+ result = runner.invoke(cli, ['--help'])456+ assert result.exit_code == 0457+ assert 'nope' not in result.output458+459+460+def test_hidden_group(runner):461+ @click.group()462+ def cli():463+ pass464+465+ @cli.group(hidden=True)466+ def subgroup():467+ pass468+469+ @subgroup.command()470+ def nope():471+ pass472+473+ result = runner.invoke(cli, ['--help'])474+ assert result.exit_code == 0475+ assert 'subgroup' not in result.output476+ assert 'nope' not in result.outputmodified:tests/test_formatting.py+67 added
143 unmodified lines144 '',145 'Options:',146 ' --help Show this message and exit.',147 ]148+149+150+def test_formatting_usage_error(runner):151+ @click.command()152+ @click.argument('arg')153+ def cmd(arg):154+ click.echo('arg:' + arg)155+156+ result = runner.invoke(cmd, [])157+ assert result.exit_code == 2158+ assert result.output.splitlines() == [159+ 'Usage: cmd [OPTIONS] ARG',160+ 'Try "cmd --help" for help.',161+ '',162+ 'Error: Missing argument "arg".'163+ ]164+165+166+def test_formatting_usage_error_nested(runner):167+ @click.group()168+ def cmd():169+ pass170+171+ @cmd.command()172+ @click.argument('bar')173+ def foo(bar):174+ click.echo('foo:' + bar)175+176+ result = runner.invoke(cmd, ['foo'])177+ assert result.exit_code == 2178+ assert result.output.splitlines() == [179+ 'Usage: cmd foo [OPTIONS] BAR',180+ 'Try "cmd foo --help" for help.',181+ '',182+ 'Error: Missing argument "bar".'183+ ]184+185+186+def test_formatting_usage_error_no_help(runner):187+ @click.command(add_help_option=False)188+ @click.argument('arg')189+ def cmd(arg):190+ click.echo('arg:' + arg)191+192+ result = runner.invoke(cmd, [])193+ assert result.exit_code == 2194+ assert result.output.splitlines() == [195+ 'Usage: cmd [OPTIONS] ARG',196+ '',197+ 'Error: Missing argument "arg".'198+ ]199+200+201+def test_formatting_usage_custom_help(runner):202+ @click.command(context_settings=dict(help_option_names=['--man']))203+ @click.argument('arg')204+ def cmd(arg):205+ click.echo('arg:' + arg)206+207+ result = runner.invoke(cmd, [])208+ assert result.exit_code == 2209+ assert result.output.splitlines() == [210+ 'Usage: cmd [OPTIONS] ARG',211+ 'Try "cmd --man" for help.',212+ '',213+ 'Error: Missing argument "arg".'214+ ]modified:tests/test_imports.py+1 added-1 removed
30 unmodified lines31 32 ALLOWED_IMPORTS = set([33 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',35- 'threading', 'colorama'35+ 'threading', 'colorama', 'errno'36 ])37 38 if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',17 unmodified linesmodified:tests/test_termui.py+57 added
10 unmodified lines11 pass12 13 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)14 assert label in runner.invoke(cli, []).output15+16+17+def test_progressbar_length_hint(runner, monkeypatch):18+ class Hinted(object):19+ def __init__(self, n):20+ self.items = list(range(n))21+22+ def __length_hint__(self):23+ return len(self.items)24+25+ def __iter__(self):26+ return self27+28+ def __next__(self):29+ if self.items:30+ return self.items.pop()31+ else:32+ raise StopIteration33+34+ next = __next__35+36+ @click.command()37+ def cli():38+ with click.progressbar(Hinted(10), label='test') as progress:39+ for thing in progress:40+ pass41+42+ monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)43+ result = runner.invoke(cli, [])44+ assert result.exception is None45+46+47+def test_choices_list_in_prompt(runner, monkeypatch):48+ @click.command()49+ @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),50+ prompt=True)51+ def cli_with_choices(g):52+ pass53+54+ @click.command()55+ @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),56+ prompt=True, show_choices=False)57+ def cli_without_choices(g):58+ pass59+60+ result = runner.invoke(cli_with_choices, [], input='none')61+ assert '(none, day, week, month)' in result.output62+63+ result = runner.invoke(cli_without_choices, [], input='none')64+ assert '(none, day, week, month)' not in result.output65+66+67+def test_secho(runner):68+ with runner.isolation() as out:69+ click.secho(None, nl=False)70+ bytes = out.getvalue()71+ assert bytes == b''modified:tests/test_testing.py+39 added
1+import os2 import sys3 4 import pytest5 import click177 unmodified lines183 184 result = runner.invoke(cli_no_error)185 assert result.exit_code == 0186 assert result.output == 'hello world\n'187+188+189+def test_env():190+ @click.command()191+ def cli_env():192+ click.echo('ENV=%s' % os.environ['TEST_CLICK_ENV'])193+194+ runner = CliRunner()195+196+ env_orig = dict(os.environ)197+ env = dict(env_orig)198+ assert 'TEST_CLICK_ENV' not in env199+ env['TEST_CLICK_ENV'] = 'some_value'200+ result = runner.invoke(cli_env, env=env)201+ assert result.exit_code == 0202+ assert result.output == 'ENV=some_value\n'203+204+ assert os.environ == env_orig205+206+207+@pytest.mark.parametrize('args, expected_output', [208+ (None, 'bar\n'),209+ ([], 'bar\n'),210+ ('', 'bar\n'),211+ (['--foo', 'one two'], 'one two\n'),212+ ('--foo "one two"', 'one two\n'),213+])214+def test_args(args, expected_output):215+216+ @click.command()217+ @click.option('--foo', default='bar')218+ def cli_args(foo):219+ click.echo(foo)220+221+ runner = CliRunner()222+ result = runner.invoke(cli_args, args=args)223+ assert result.exit_code == 0224+ assert result.output == expected_outputmodified:.gitignore+2 added
6 unmodified lines7 build8 docs/_build9 click.egg-info10 .tox11+.cache12+.ropeprojectmodified:.travis.yml+7 added-7 removed
3 unmodified lines4 - "2.7"5 - "3.3"6 - "3.4"7 - "3.5"8+ - "3.6"9 - "pypy"10 11 env:12 - REQUIREMENTS=colorama4 unmodified lines17 - pip install --editable .18 19 script: make test20 21+branches:22+ only:23+ - master24+ - auto25+ - /^.*-maintenance$/26+27 notifications:28 email: false22- irc:23- channels:24- - "chat.freenode.net#pocoo"25- on_success: change26- on_failure: always27- use_notice: true28- skip_join: truemodified:CHANGES+38 added-1 removed
1 unmodified line2 ===============3 4 This contains all major version changes between Click releases.5 6+Version 7.07+-----------8+9+(upcoming release with new features, release date to be decided)10+11+- The user is now presented with the available choices if prompt=True and12+ type=click.Choice in a click.option. The choices are listed within13+ parentthesis like 'Choose fruit (apple, orange): '.14+- The exception objects now store unicode properly.15+- Added the ability to hide commands and options from help.16+- Added Float Range in Types.17+- `secho`'s first argument can now be `None`, like in `echo`.18+- Usage errors now hint at the `--help` option.19+- ``launch`` now works properly under Cygwin. See #650.20+- `CliRunner.invoke` now may receive `args` as a string representing21+ a Unix shell command. See #664.22+23+Version 6.824+-----------25+26+(bugfix release; yet to be released)27+28+- Disabled sys._getframes() on Python interpreters that don't support it. See29+ #728.30+- Fix bug in test runner when calling ``sys.exit`` with ``None``. See #739.31+- Fix crash on Windows console, see #744.32+33+Version 6.734+-----------35+36+(bugfix release; released on January 6th 2017)37+38+- Make `click.progressbar` work with `codecs.open` files. See #637.39+- Fix bug in bash completion with nested subcommands. See #639.40+- Fix test runner not saving caller env correctly. See #644.41+- Fix handling of SIGPIPE. See #62642+- Deal with broken Windows environments such as Google App Engine's. See #711.43+44 Version 6.645 -----------46 47 (bugfix release; released on April 4th 2016)16 unmodified lines64 - Fix argument checks for interpreter invoke with `-m` and `-c`65 on Windows.66 - Fixed a bug that cased locale detection to error out on Python 3.67 30-68 Version 6.269 -----------70 71 (bugfix release, released on November 27th 2015)306 unmodified linesmodified:CONTRIBUTING.rst+5 added
30 unmodified lines31 32 - Try to follow `PEP8 <http://legacy.python.org/dev/peps/pep-0008/>`_, but you33 may ignore the line-length-limit if following it would make the code uglier.34 35+- For features: Consider whether your feature would be a better fit for an36+ `external package <http://click.pocoo.org/contrib/>`_37+38+- For bugfixes: Submit against the latest maintenance branch instead of master!39+40 Running the testsuite41 ---------------------42 43 You probably want to set up a `virtualenv18 unmodified linesmodified:MANIFEST.in+7 added-10 removed
1 include Makefile CHANGES LICENSE2-recursive-include artwork *3-recursive-include tests *4-recursive-include examples *5-recursive-include docs *6-recursive-exclude docs *.pyc7-recursive-exclude docs *.pyo8-recursive-exclude tests *.pyc9-recursive-exclude tests *.pyo10-recursive-exclude examples *.pyc11-recursive-exclude examples *.pyo2+3+graft artwork4+graft tests5+graft examples6+graft docs7 prune docs/_build8+9+global-exclude *.py[co] .DS_Storemodified:setup.cfg+4 added-1 removed
1-[wheel]1+[bdist_wheel]2 universal=13+4+[metadata]5+license_file = LICENSEmodified:setup.py+1 added-1 removed
14 unmodified lines15 name='click',16 author='Armin Ronacher',17 author_email='armin.ronacher@active-4.com',18 version=version,19- url='http://github.com/mitsuhiko/click',19+ url='http://github.com/pallets/click',20 packages=['click'],21 description='A simple wrapper around optparse for '22 'powerful command line utilities.',23 classifiers=[5 unmodified lines