Skip to content
Myr

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

36 files+559 added−124 removed

modified:click/__init__.py+3 added-3 removed
26 unmodified lines
27 password_option, version_option, help_option2829# Types30from .types import ParamType, File, Path, Choice, IntRange, Tuple, \31 STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED31 STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange3233# Utilities34from .utils import echo, get_binary_stream, get_text_stream, open_file, \35 format_filename, get_app_dir, get_os_args
29 unmodified lines
65 'version_option', 'help_option',6667 # Types68 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple', 'STRING',69 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',69 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED', 'FloatRange'7071 # Utilities72 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',73 'format_filename', 'get_app_dir', 'get_os_args',
20 unmodified lines
94# literals.95disable_unicode_literals_warning = False969798__version__ = '6.6.bashautocompletion'98__version__ = '7.0-dev'
modified:click/_bashcomplete.py+1 added-1 removed
27 unmodified lines
282930def 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 None
61 unmodified lines
modified:click/_compat.py+12 added-3 removed
6 unmodified lines
789PY2 = sys.version_info[0] == 210WIN = sys.platform.startswith('win')11CYGWIN = sys.platform.startswith('cygwin')12DEFAULT_COLUMNS = 80131415_ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')
123 unmodified lines
139 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 = xrange146147 def is_bytes(x):
13 unmodified lines
161 # 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: x183184 def isidentifier(x):185 return _identifier_re.search(x) is not None186
32 unmodified lines
219 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 lines
modified:click/_termui_impl.py+12 added-3 removed
12 unmodified lines
13import sys14import time15import math16from ._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 CYGWIN19from .utils import echo20from .exceptions import ClickException2122
8 unmodified lines
31def _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 None
1 unmodified line
41 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 lines
478 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)490491 try:492 if locate:493 url = os.path.dirname(_unquote_file(url)) or '.'
63 unmodified lines
modified:click/_unicodefun.py+5 added-4 removed
12 unmodified lines
131415def _find_unicode_literals_frame():16 import __future__17 if not hasattr(sys, '_getframe'): # not all Python implementations have it18 return 019 frm = sys._getframe(1)20 idx = 121 while frm is not None:22 if frm.f_globals.get('__name__', '').startswith('click.'):
72 unmodified lines
95 )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))102103 bad_locale = None
11 unmodified lines
115 ) % bad_locale116117 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 lines
260 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 we
5 unmodified lines
modified:click/core.py+25 added-9 removed
1import errno2import os3import sys4from contextlib import contextmanager5from itertools import repeat
648 unmodified lines
654 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 into
6 unmodified lines
669 :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 lines
705 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 lines
742 :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 """748749 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 = callback
7 unmodified lines
764 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 = hidden769770 def get_usage(self, ctx):771 formatter = ctx.make_formatter()772 self.format_usage(ctx, formatter)
231 unmodified lines
1004 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 continue10101011 help = cmd.short_help or ''1012 rows.append((subcommand, help))1013
415 unmodified lines
1429 All other parameters are passed onwards to the parameter constructor.14301431 :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 password
12 unmodified lines
1452 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'14591460 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)14671468 if prompt is True:
4 unmodified lines
1473 prompt_text = prompt1474 self.prompt = prompt_text1475 self.confirmation_prompt = confirmation_prompt1476 self.hide_input = hide_input1477 self.hidden = hidden14781479 # Flags1480 if is_flag is None:1481 if flag_value is not None:
24 unmodified lines
1506 self.multiple = multiple1507 self.allow_from_autoenv = allow_from_autoenv1508 self.help = help1509 self.show_default = show_default1510 self.show_choices = show_choices15111512 # Sanity check for stuff we don't support1513 if __debug__:1514 if self.nargs < 0:
87 unmodified lines
1602 kwargs['action'] = action1603 parser.add_option(self.opts, **kwargs)16041605 def get_help_record(self, ctx):1606 if self.hidden:1607 return1608 any_prefix_is_slash = []16091610 def _write_opts(opts):1611 rv, any_slashes = join_options(opts)
46 unmodified lines
1658 # differently.1659 if self.is_bool_flag:1660 return confirm(self.prompt, default)16611646 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))16661667 def resolve_envvar_value(self, ctx):
89 unmodified lines
modified:click/decorators.py+5 added-1 removed
233 unmodified lines
234 (``'%(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 = ''242243 def decorator(f):244 prog_name = attrs.pop('prog_name', None)245 message = attrs.pop('message', '%(prog)s, version %(version)s')246
62 unmodified lines
modified:click/exceptions.py+21 added-5 removed
7 unmodified lines
8 #: The exit code for this exception9 exit_code = 11011 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 = message1819 def format_message(self):20 return self.message2122 def __unicode__(self):23 return self.message2425 def __str__(self):26 return self.message.encode('utf-8')2728 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 lines
4344 def __init__(self, message, ctx=None):45 ClickException.__init__(self, message)46 self.ctx = ctx47 self.cmd = self.ctx and self.ctx.command or None4849 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)626364class BadParameter(UsageError):
111 unmodified lines
176 was incorrect. This is for instance raised if the number of arguments177 for an option is not correct.178179 .. versionadded:: 4.0180181 :param option_name: the name of the option being used incorrectly.182 """183169 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_name187188189class BadArgumentUsage(UsageError):190 """Raised if an argument is generally supplied but the use of the argument
27 unmodified lines
modified:click/parser.py+3 added-3 removed
72 unmodified lines
737475def _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))798081def split_opt(opt):82 first = opt[:1]
258 unmodified lines
341 value = tuple(state.rargs[:nargs])342 del state.rargs[:nargs]343344 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)346347 else:348 value = None349
77 unmodified lines
modified:click/termui.py+19 added-9 removed
4 unmodified lines
5from ._compat import raw_input, text_type, string_types, \6 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN7from .utils import echo8from .exceptions import Abort, UsageError9from .types import convert_type9from .types import convert_type, Choice10from .globals import resolve_color_default111213# The prompt functions to use. The doc tools currently override these
9 unmodified lines
23 import getpass24 return getpass.getpass(prompt)252627def _build_prompt(text, suffix, show_default=False, default=None):27def _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 + suffix343534def 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):36def 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.4142 If the user aborts the input by sending a interrupt signal, this43 function will catch it and raise a :exc:`Abort` exception.4445 .. versionadded:: 7.046 Added the show_choices parameter.4748 .. versionadded:: 6.049 Added unicode support for cmd.exe on Windows.5051 .. versionadded:: 4.0
12 unmodified lines
64 :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 = None7475 def prompt_func(text):
13 unmodified lines
8990 if value_proc is None:91 value_proc = convert_type(type, default)9285 prompt = _build_prompt(text, prompt_suffix, show_default, default)93 prompt = _build_prompt(text, prompt_suffix, show_default, default, show_choices, type)9495 while 1:96 while 1:97 value = prompt_func(prompt)
314 unmodified lines
412 """413 return strip_ansi(text)414415408def secho(text, file=None, nl=True, err=False, color=None, **styles):416def 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::419420 click.secho('Hello World!', fg='green')
3 unmodified lines
424 depending on which one they go with.425426 .. 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)431432433def edit(text=None, editor=None, env=None, require_save=True,434 extension='.txt', filename=None):
115 unmodified lines
modified:click/testing.py+19 added-8 removed
1 unmodified line
2import sys3import shutil4import tempfile5import contextlib6import shlex77from ._compat import iteritems, PY28from ._compat import iteritems, PY2, string_types91011# If someone wants to vendor click, we want to ensure the12# correct package is discovered. Ideally we could use a
183 unmodified lines
196 sys.stdout.flush()197 return char198199 default_color = color200201 def should_strip_ansi(stream=None, color=None):202 if color is None:203 return not default_color204 return not color
9 unmodified lines
214215 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 lines
261 .. versionadded:: 4.0262 The ``color`` parameter was added.263264 :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 lines
278 with self.isolation(input=input, env=env, color=color) as out:279 exception = None280 exit_code = 0281282 if isinstance(args, string_types):283 args = shlex.split(args)284285 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 = e283289 exc_info = sys.exc_info()285290 exit_code = e.code291 if exit_code is None:292 exit_code = 0293294 if exit_code != 0:295 exception = e296297 if not isinstance(exit_code, int):298 sys.stdout.write(str(exit_code))299 sys.stdout.write('\n')300 exit_code = 1301302 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 lines
modified:click/types.py+57 added-16 removed
212 unmodified lines
213 def __repr__(self):214 return 'IntRange(%r, %r)' % (self.min, self.max)215216217class FloatParamType(ParamType):218 name = 'float'219220 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)226227 def __repr__(self):228 return 'FLOAT'229230231class 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.236237 See :ref:`ranges` for an example.238 """239 name = 'float range'240241 def __init__(self, min=None, max=None, clamp=False):242 self.min = min243 self.max = max244 self.clamp = clamp245246 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 rv265266 def __repr__(self):267 return 'FloatRange(%r, %r)' % (self.min, self.max)268269270class BoolParamType(ParamType):271 name = 'boolean'272273 def convert(self, value, param, ctx):
9 unmodified lines
283 def __repr__(self):284 return 'BOOL'285286234class FloatParamType(ParamType):235 name = 'float'236237 def convert(self, value, param, ctx):238 try:239 return float(value)240 except (UnicodeError, ValueError):241 self.fail('%s is not a valid floating point value' %242 value, param, ctx)243244 def __repr__(self):245 return 'FLOAT'246247287class UUIDParameterType(ParamType):288 name = 'uuid'289290 def convert(self, value, param, ctx):
105 unmodified lines
396 :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` which
17 unmodified lines
424425 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 lines
modified:click/utils.py+2 added-1 removed
41 unmodified lines
42 return text_type(value)434445def make_default_short_help(help, max_length=45):46 """Return a condensed version of help string."""47 words = help.split()48 total_length = 049 result = []50 done = False
120 unmodified lines
171 matter how badly configured the system is.172173 Primarily it means that you can print binary data as well as Unicode174 data on both 2.x and 3.x to the given file in the most appropriate way174 possible. This is a very carefree function as in that it will try its175 possible. This is a very carefree function in that it will try its176 best to not fail. As of Click 6.0 this includes support for unicode177 output on the Windows console.178179 In addition to that, if `colorama`_ is installed, the echo function will
237 unmodified lines
modified:docs/_templates/sidebarintro.html+2 added-2 removed
6 unmodified lines
7<h3>Useful Links</h3>8<ul>9 <li><a href="http://click.pocoo.org/">The Click Website</a></li>10 <li><a href="http://pypi.python.org/pypi/click">click @ PyPI</a></li>11 <li><a href="http://github.com/mitsuhiko/click">click @ github</a></li>12 <li><a href="http://github.com/mitsuhiko/click/issues">Issue Tracker</a></li>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 lines
276 command will abort with an error that there are leftover arguments.277 If you go with this solution, the extra arguments will be collected in278 :attr:`Context.args`.2792. You can attach a :func:`argument` with ``nargs`` set to `-1` which280 will eat up all leftover arguments. In this case it's recommeded to280 will eat up all leftover arguments. In this case it's recommended to281 set the `type` to :data:`UNPROCESSED` to avoid any string processing282 on those arguments as otherwise they are forced into unicode strings283 automatically which is often not what you want.284
60 unmodified lines
345346.. versionadded:: 5.0347348Starting with Click 5.0 it is possible to access the current context from349anywhere within the same through through the use of the349anywhere within the same thread through the use of the350:func:`get_current_context` function which returns it. This is primarily351useful for accessing the context bound object as well as some flags that352are stored on it to customize the runtime behavior. For instance the353:func:`echo` function does this to infer the default value of the `color`
26 unmodified lines
modified:docs/bashcomplete.rst+1 added-1 removed
78 unmodified lines
79with dashes replaced by underscores.8081If your tool is called ``foo-bar``, then the magic variable is called82``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will83spit out the activation script which can be trivally activated.83spit out the activation script which can be trivially activated.8485For instance, to enable Bash completion for your ``foo-bar`` script, this86is what you would need to put into your ``.bashrc``::87
20 unmodified lines
modified:docs/commands.rst+2 added-2 removed
415 unmodified lines
416:func:`open_file`.417418For a more complex example that also improves upon handling of the419pipelines have a look at the `imagepipe multi command chaining demo420<https://github.com/mitsuhiko/click/tree/master/examples/imagepipe>`__ in420<https://github.com/pallets/click/tree/master/examples/imagepipe>`__ in421the Click repository. It implements a pipeline based image editing tool422that has a nice internal structure for the pipelines.423424
11 unmodified lines
436you're not satisfied with the defaults.437438The default map can be nested arbitrarily for each subcommand and439provided when the script is invoked. Alternatively, it can also be440overriden at any point by commands. For instance, a top-level command could440overridden at any point by commands. For instance, a top-level command could441load the defaults from a configuration file.442443Example usage:444
114 unmodified lines
modified:docs/parameters.rst+3 added
65 unmodified lines
6667.. autoclass:: IntRange68 :noindex:6970.. autoclass:: FloatRange71 :noindex:7273Custom parameter types can be implemented by subclassing74:class:`click.ParamType`. For simple cases, passing a Python function that75fails with a `ValueError` is also supported, though discouraged.76
47 unmodified lines
modified:docs/python3.rst+1 added-1 removed
6 unmodified lines
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.1011At the moment, it is strongly recommended is to use Python 2 for Click11At the moment, it is strongly recommended to use Python 2 for Click12utilities unless Python 3 is a hard requirement.1314.. _python3-limitations:15
168 unmodified lines
modified:docs/quickstart.rst+10 added-10 removed
77 unmodified lines
78And if you want to go back to the real world, use the following command::7980 $ deactivate8182After doing this, the prompt of your shell should be as familar as before.82After doing this, the prompt of your shell should be as familiar as before.8384Now, let's move on. Enter the following command to get Click activated in your85virtualenv::86
14 unmodified lines
101Examples of Click applications can be found in the documentation as well102as in the GitHub repository together with readme files:103104* ``inout``: `File input and output105 <https://github.com/mitsuhiko/click/tree/master/examples/inout>`_105 <https://github.com/pallets/click/tree/master/examples/inout>`_106* ``naval``: `Port of docopt naval example107 <https://github.com/mitsuhiko/click/tree/master/examples/naval>`_107 <https://github.com/pallets/click/tree/master/examples/naval>`_108* ``aliases``: `Command alias example109 <https://github.com/mitsuhiko/click/tree/master/examples/aliases>`_109 <https://github.com/pallets/click/tree/master/examples/aliases>`_110* ``repo``: `Git-/Mercurial-like command line interface111 <https://github.com/mitsuhiko/click/tree/master/examples/repo>`_111 <https://github.com/pallets/click/tree/master/examples/repo>`_112* ``complex``: `Complex example with plugin loading113 <https://github.com/mitsuhiko/click/tree/master/examples/complex>`_113 <https://github.com/pallets/click/tree/master/examples/complex>`_114* ``validation``: `Custom parameter validation example115 <https://github.com/mitsuhiko/click/tree/master/examples/validation>`_115 <https://github.com/pallets/click/tree/master/examples/validation>`_116* ``colors``: `Colorama ANSI color support117 <https://github.com/mitsuhiko/click/tree/master/examples/colors>`_117 <https://github.com/pallets/click/tree/master/examples/colors>`_118* ``termui``: `Terminal UI functions demo119 <https://github.com/mitsuhiko/click/tree/master/examples/termui>`_119 <https://github.com/pallets/click/tree/master/examples/termui>`_120* ``imagepipe``: `Multi command chaining demo121 <https://github.com/mitsuhiko/click/tree/master/examples/imagepipe>`_121 <https://github.com/pallets/click/tree/master/examples/imagepipe>`_122123Basic Concepts124--------------125
149 unmodified lines
modified:docs/upgrading.rst+1 added-1 removed
42 unmodified lines
4344Multicommand Chaining API45`````````````````````````4647Click 3 introduced multicommand chaning. This required a change in how47Click 3 introduced multicommand chaining. This required a change in how48Click internally dispatches. Unfortunately this change was not correctly49implemented and it appeared that it was possible to provide an API that50can inform the super command about all the subcommands that will be51invoked.
49 unmodified lines
modified:docs/utils.rst+2 added-2 removed
224 unmodified lines
225226.. versionadded:: 2.0227228Click supports launching applications through :func:`launch`. This can be229used to open the default application assocated with a URL or filetype.229used to open the default application associated with a URL or filetype.230This can be used to launch web browsers or picture viewers, for instance.231In addition to this, it can also launch the file manager and automatically232select the provided file.233
31 unmodified lines
265streams respond to Unicode and binary data.266267Because of this, click provides the :func:`get_binary_stream` and268:func:`get_text_stream` functions, which produce consistent results with269different Python versions and for a wide variety pf terminal configurations.269different Python versions and for a wide variety of terminal configurations.270271The end result is that these functions will always return a functional272stream object (except in very odd cases in Python 3; see273:ref:`python3-limitations`).
125 unmodified lines
modified:tests/test_bashcomplete.py+45 added-15 removed
1 unmodified line
23import click4from click._bashcomplete import get_choices56def test_basic():67def test_single_command():8 @click.command()9 @click.option('--local-opt')10 def cli(local_opt):11 pass1213 assert list(get_choices(cli, 'lol', [], '-')) == ['--local-opt']14 assert list(get_choices(cli, 'lol', [], '')) == []151617def test_small_chain():18 @click.group()19 @click.option('--global-opt')20 def cli(global_opt):21 pass
2 unmodified lines
24 @click.option('--local-opt')25 def sub(local_opt):26 pass2717 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']323334def test_long_chain():35 @click.group('cli')36 @click.option('--cli-opt')37 def cli(cli_opt):38 pass3940 @cli.group('asub')41 @click.option('--asub-opt')42 def asub(asub_opt):43 pass4445 @asub.group('bsub')46 @click.option('--bsub-opt')47 def bsub(bsub_opt):48 pass4950 COLORS = ['red', 'green', 'blue']51 def get_colors(ctx, args, incomplete):52 return COLORS5326 @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 pass5931 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 lines
342 assert not result.exception343 assert result.output == '0\n'344345346def 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)351352 result = runner.invoke(cli, ['--x=5.0'])353 assert not result.exception354 assert result.output == '5.0\n'355356 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.output360361 @click.command()362 @click.option('--x', type=click.FloatRange(0, 5, clamp=True))363 def clamp(x):364 click.echo(x)365366 result = runner.invoke(clamp, ['--x=5.0'])367 assert not result.exception368 assert result.output == '5.0\n'369370 result = runner.invoke(clamp, ['--x=6.0'])371 assert not result.exception372 assert result.output == '5\n'373374 result = runner.invoke(clamp, ['--x=-1.0'])375 assert not result.exception376 assert result.output == '0\n'377378379def test_required_option(runner):380 @click.command()381 @click.option('--foo', required=True)382 def cli(foo):
46 unmodified lines
429 'normal3',430 'normal1',431 'missing',432 ]433434435def test_hidden_option(runner):436 @click.command()437 @click.option('--nope', hidden=True)438 def cli(nope):439 click.echo(nope)440441 result = runner.invoke(cli, ['--help'])442 assert result.exit_code == 0443 assert '--nope' not in result.output444445446def test_hidden_command(runner):447 @click.group()448 def cli():449 pass450451 @cli.command(hidden=True)452 def nope():453 pass454455 result = runner.invoke(cli, ['--help'])456 assert result.exit_code == 0457 assert 'nope' not in result.output458459460def test_hidden_group(runner):461 @click.group()462 def cli():463 pass464465 @cli.group(hidden=True)466 def subgroup():467 pass468469 @subgroup.command()470 def nope():471 pass472473 result = runner.invoke(cli, ['--help'])474 assert result.exit_code == 0475 assert 'subgroup' not in result.output476 assert 'nope' not in result.output
modified:tests/test_formatting.py+67 added
143 unmodified lines
144 '',145 'Options:',146 ' --help Show this message and exit.',147 ]148149150def test_formatting_usage_error(runner):151 @click.command()152 @click.argument('arg')153 def cmd(arg):154 click.echo('arg:' + arg)155156 result = runner.invoke(cmd, [])157 assert result.exit_code == 2158 assert result.output.splitlines() == [159 'Usage: cmd [OPTIONS] ARG',160 'Try "cmd --help" for help.',161 '',162 'Error: Missing argument "arg".'163 ]164165166def test_formatting_usage_error_nested(runner):167 @click.group()168 def cmd():169 pass170171 @cmd.command()172 @click.argument('bar')173 def foo(bar):174 click.echo('foo:' + bar)175176 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 ]184185186def 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)191192 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 ]199200201def 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)206207 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 lines
3132ALLOWED_IMPORTS = set([33 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',35 'threading', 'colorama'35 'threading', 'colorama', 'errno'36])3738if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',
17 unmodified lines
modified:tests/test_termui.py+57 added
10 unmodified lines
11 pass1213 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)14 assert label in runner.invoke(cli, []).output151617def test_progressbar_length_hint(runner, monkeypatch):18 class Hinted(object):19 def __init__(self, n):20 self.items = list(range(n))2122 def __length_hint__(self):23 return len(self.items)2425 def __iter__(self):26 return self2728 def __next__(self):29 if self.items:30 return self.items.pop()31 else:32 raise StopIteration3334 next = __next__3536 @click.command()37 def cli():38 with click.progressbar(Hinted(10), label='test') as progress:39 for thing in progress:40 pass4142 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)43 result = runner.invoke(cli, [])44 assert result.exception is None454647def 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 pass5354 @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 pass5960 result = runner.invoke(cli_with_choices, [], input='none')61 assert '(none, day, week, month)' in result.output6263 result = runner.invoke(cli_without_choices, [], input='none')64 assert '(none, day, week, month)' not in result.output656667def 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
1import os2import sys34import pytest5import click
177 unmodified lines
183184 result = runner.invoke(cli_no_error)185 assert result.exit_code == 0186 assert result.output == 'hello world\n'187188189def test_env():190 @click.command()191 def cli_env():192 click.echo('ENV=%s' % os.environ['TEST_CLICK_ENV'])193194 runner = CliRunner()195196 env_orig = dict(os.environ)197 env = dict(env_orig)198 assert 'TEST_CLICK_ENV' not in env199 env['TEST_CLICK_ENV'] = 'some_value'200 result = runner.invoke(cli_env, env=env)201 assert result.exit_code == 0202 assert result.output == 'ENV=some_value\n'203204 assert os.environ == env_orig205206207@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])214def test_args(args, expected_output):215216 @click.command()217 @click.option('--foo', default='bar')218 def cli_args(foo):219 click.echo(foo)220221 runner = CliRunner()222 result = runner.invoke(cli_args, args=args)223 assert result.exit_code == 0224 assert result.output == expected_output
modified:.gitignore+2 added
6 unmodified lines
7build8docs/_build9click.egg-info10.tox11.cache12.ropeproject
modified:.travis.yml+7 added-7 removed
3 unmodified lines
4 - "2.7"5 - "3.3"6 - "3.4"7 - "3.5"8 - "3.6"9 - "pypy"1011env:12 - REQUIREMENTS=colorama
4 unmodified lines
17 - pip install --editable .1819script: make test2021branches:22 only:23 - master24 - auto25 - /^.*-maintenance$/2627notifications:28 email: false22 irc:23 channels:24 - "chat.freenode.net#pocoo"25 on_success: change26 on_failure: always27 use_notice: true28 skip_join: true
modified:CHANGES+38 added-1 removed
1 unmodified line
2===============34This contains all major version changes between Click releases.56Version 7.07-----------89(upcoming release with new features, release date to be decided)1011- 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.2223Version 6.824-----------2526(bugfix release; yet to be released)2728- 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.3233Version 6.734-----------3536(bugfix release; released on January 6th 2017)3738- 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.4344Version 6.645-----------4647(bugfix release; released on April 4th 2016)
16 unmodified lines
64- 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.673068Version 6.269-----------7071(bugfix release, released on November 27th 2015)
306 unmodified lines
modified:CONTRIBUTING.rst+5 added
30 unmodified lines
3132- Try to follow `PEP8 <http://legacy.python.org/dev/peps/pep-0008/>`_, but you33 may ignore the line-length-limit if following it would make the code uglier.3435- For features: Consider whether your feature would be a better fit for an36 `external package <http://click.pocoo.org/contrib/>`_3738- For bugfixes: Submit against the latest maintenance branch instead of master!3940Running the testsuite41---------------------4243You probably want to set up a `virtualenv
18 unmodified lines
modified:MANIFEST.in+7 added-10 removed
1include Makefile CHANGES LICENSE2recursive-include artwork *3recursive-include tests *4recursive-include examples *5recursive-include docs *6recursive-exclude docs *.pyc7recursive-exclude docs *.pyo8recursive-exclude tests *.pyc9recursive-exclude tests *.pyo10recursive-exclude examples *.pyc11recursive-exclude examples *.pyo23graft artwork4graft tests5graft examples6graft docs7prune docs/_build89global-exclude *.py[co] .DS_Store
modified:setup.cfg+4 added-1 removed
1[wheel]1[bdist_wheel]2universal=134[metadata]5license_file = LICENSE
modified:setup.py+1 added-1 removed
14 unmodified lines
15 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