Skip to content
Myr

User interface improvements.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- Changed how the help function is implemented to allow global overriding. - Added support for token normalization to implement case insensitive handling. - Added support for providing defaults for context settings.

authored by Armin Ronacher · committed by Armin Ronacher · parent 59b5a5e · Browse files · 7 files+184 added−33 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+184 added−33 removed

  • tests:+45 added−6 removed
  • other:+139 added−27 removed

7 files+184 added−33 removed

modified:click/core.py+92 added-25 removed
6 unmodified lines
7from .types import convert_type, IntRange, BOOL8from .utils import make_str, make_default_short_help, echo9from .exceptions import ClickException, UsageError, BadParameter, Abort10from .termui import prompt, confirm11from .formatting import HelpFormatter11from .formatting import HelpFormatter, join_options12from .parser import OptionParser, split_opt1314from ._compat import PY2, isidentifier14from ._compat import PY2, isidentifier, iteritems1516_missing = object()1718
74 unmodified lines
9394 A context can be used as context manager in which case it will call95 :meth:`close` on teardown.9697 .. versionadded:: 2.098 Added the `resilient_parsing`, `help_option_names`,99 `token_normalize_func` parameters.100101 :param command: the command class for this context.102 :param parent: the parent context.103 :param info_name: the info name for this invokation. Generally this104 is the most descriptive name for the script or
15 unmodified lines
120 :param resilient_parsing: if this flag is enabled then click will121 parse without any interactivity or callback122 invocation. This is useful for implementing123 things such as completion support.124 :param help_option_names: optionally a list of strings that define how125 the default help parameter is named. The126 default is ``['--help']``.127 :param token_normalize_func: an optional function that is used to128 normalize tokens (options, choices,129 etc.). This for instance can be used to130 implement case insensitive behavior.131 """132133 def __init__(self, command, parent=None, info_name=None, obj=None,134 auto_envvar_prefix=None, default_map=None,124 terminal_width=None, resilient_parsing=False):135 terminal_width=None, resilient_parsing=False,136 help_option_names=None, token_normalize_func=None):137 #: the parent context or `None` if none exists.138 self.parent = parent139 #: the :class:`Command` for this context.140 self.command = command
21 unmodified lines
162 terminal_width = parent.terminal_width163 #: The width of the terminal (None is autodetection).164 self.terminal_width = terminal_width165166 if help_option_names is None:167 if parent is not None:168 help_option_names = parent.help_option_names169 else:170 help_option_names = ['--help']171172 #: The name for the help options.173 self.help_option_names = help_option_names174175 if token_normalize_func is None and parent is not None:176 token_normalize_func = parent.token_normalize_func177178 #: An optional normalization function for tokens. This is179 #: options, choices, commands etc.180 self.token_normalize_func = token_normalize_func181182 #: Indicates if resilient parsing is enabled. In that case click183 #: will do its best to not cause any failures.184 self.resilient_parsing = resilient_parsing185
167 unmodified lines
353 parts of click take for granted, they are not supported for all354 operations. For instance, they cannot be used with the decorators355 usually and they have no built-in callback system.356357 .. versionchanged:: 2.0358 Added the `context_defaults` parameter.359360 :param name: the name of the command to use unless a group overrides it.361 :param context_defaults: an optional dictionary with defaults that are362 passed to the context object.363 """364332 def __init__(self, name):365 def __init__(self, name, context_defaults=None):366 #: the name the command thinks it has. Upon registering a command367 #: on a :class:`Group` the group will default the command name368 #: with this information. You should instead use the369 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.370 self.name = name371 #: an optional dictionary with defaults passed to the context.372 self.context_defaults = context_defaults373374 def get_usage(self, ctx):375 raise NotImplementedError('Base commands cannot get usage')376
19 unmodified lines
396 default_map = None397 if parent is not None and parent.default_map is not None:398 default_map = parent.default_map.get(info_name)399 extra['default_map'] = default_map400401 for key, value in iteritems(self.context_defaults or {}):402 if key not in extra:403 extra[key] = value404405 ctx = Context(self, info_name=info_name, parent=parent, **extra)406 self.parse_args(ctx, args)407 return ctx408
86 unmodified lines
495 """Commands are the basic building block of command line interfaces in496 click. A basic command handles command line parsing and might dispatch497 more parsing to commands nested below it.498499 .. versionchanged:: 2.0500 Added the `context_defaults` parameter.501502 :param name: the name of the command to use unless a group overrides it.503 :param context_defaults: an optional dictionary with defaults that are504 passed to the context object.505 :param callback: the callback to invoke. This is optional.506 :param params: the parameters to register with this command. This can507 be either :class:`Option` or :class:`Argument` objects.508 :param help: the help string to use for this command.
5 unmodified lines
514 option. This can be disabled by this parameter.515 """516 allow_extra_args = False517473 def __init__(self, name, callback=None, params=None, help=None,474 epilog=None, short_help=None,518 def __init__(self, name, context_defaults=None, callback=None,519 params=None, help=None, epilog=None, short_help=None,520 options_metavar='[OPTIONS]', add_help_option=True):476 BaseCommand.__init__(self, name)521 BaseCommand.__init__(self, name, context_defaults)522 #: the callback to execute when the command fires. This might be523 #: `None` in which case nothing happens.524 self.callback = callback525 #: the list of parameters for this command in the order they
5 unmodified lines
531 self.options_metavar = options_metavar532 if short_help is None and help:533 short_help = make_default_short_help(help)534 self.short_help = short_help490 if add_help_option:491 self.add_help_option()535 self.add_help_option = add_help_option536493 def add_help_option(self):494 """Adds a help option to the command."""495 help_option()(self)496537 def get_usage(self, ctx):538 formatter = ctx.make_formatter()539 self.format_usage(ctx, formatter)540 return formatter.getvalue().rstrip('\n')
11 unmodified lines
552 for param in self.params:553 rv.extend(param.get_usage_pieces(ctx))554 return rv555556 def get_help_option_names(self, ctx):557 """Returns the names for the help option."""558 all_names = set(ctx.help_option_names)559 for param in self.params:560 all_names.difference_update(param.opts)561 all_names.difference_update(param.secondary_opts)562 return all_names563564 def make_parser(self, ctx):565 """Creates the underlying option parser for this command."""566 parser = OptionParser(ctx)567 for param in self.params:568 param.add_to_parser(parser, ctx)569570 if self.add_help_option:571 help_options = self.get_help_option_names(ctx)572 if help_options:573 parser.add_option(help_options, action='store_const',574 const=True, dest='$help')575576 return parser577578 def get_help(self, ctx):579 """Formats the help into a string and returns it. This creates a
32 unmodified lines
612 rv = param.get_help_record(ctx)613 if rv is not None:614 opts.append(rv)615616 if self.add_help_option:617 help_options = self.get_help_option_names(ctx)618 if help_options:619 opts.append([join_options(help_options)[0],620 'Show this message and exit.'])621622 if opts:623 with formatter.section('Options'):624 formatter.write_dl(opts)625
7 unmodified lines
633 def parse_args(self, ctx, args):634 parser = self.make_parser(ctx)635 opts, args, param_order = parser.parse_args(args=args)636637 if opts.get('$help') and not ctx.resilient_parsing:638 echo(ctx.get_help())639 ctx.exit()640641 for param in iter_params_for_processing(param_order, self.params):642 value, args = param.handle_parse_result(ctx, opts, args)643644 if args and not self.allow_extra_args and not ctx.resilient_parsing:
84 unmodified lines
729 return Command.invoke(self, ctx)730 ctx.fail('Missing command.')731732 cmd_name = make_str(ctx.args[0])733 original_cmd_name = cmd_name734735 # Get the command736 cmd = self.get_command(ctx, cmd_name)737738 # If we can't find the command but there is a normalization739 # function available, we try with that one.740 if cmd is None and ctx.token_normalize_func is not None:741 cmd_name = ctx.token_normalize_func(cmd_name)742 cmd = self.get_command(ctx, cmd_name)743744 # If we don't find the command we want to show an error message745 # to the user that it was not provided. However, there is746 # something else we should do: if the first argument looks like747 # an option we want to kick off parsing again for arguments to
1 unmodified line
749 # place.750 if cmd is None:751 if split_opt(cmd_name)[0]:752 self.parse_args(ctx, ctx.args)679 ctx.fail('No such command "%s".' % cmd_name)753 ctx.fail('No such command "%s".' % original_cmd_name)754755 return self.invoke_subcommand(ctx, cmd, cmd_name, ctx.args[1:])756757 def invoke_subcommand(self, ctx, cmd, cmd_name, args):
441 unmodified lines
1199 def get_help_record(self, ctx):1200 any_prefix_is_slash = []12011202 def _write_opts(opts):1129 rv = []1130 for opt in opts:1131 prefix = split_opt(opt)[0]1132 if prefix == '/':1133 any_prefix_is_slash[:] = [True]1134 rv.append((len(prefix), opt))11351136 rv.sort(key=lambda x: x[0])11371138 rv = ', '.join(x[1] for x in rv)1203 rv, any_slashes = join_options(opts)1204 if any_slashes:1205 any_prefix_is_slash[:] = [True]1206 if not self.is_flag:1207 rv += ' ' + self.make_metavar()1208 return rv1209
120 unmodified lines
1330 obj=self)133113321333# Circular dependency between decorators and core1267from .decorators import command, group, help_option1334from .decorators import command, group
modified:click/formatting.py+21 added
1from contextlib import contextmanager2from .termui import get_terminal_size3from .parser import split_opt4from ._compat import term_len567def measure_table(rows):
208 unmodified lines
216217 def getvalue(self):218 """Returns the buffer contents."""219 return ''.join(self.buffer)220221222def join_options(options):223 """Given a list of option strings this joins them in the most appropriate224 way and returns them in the form ``(formatted_string,225 any_prefix_is_slash)`` where the second item in the tuple is a flag that226 indicates if any of the option prefixes was a slash.227 """228 rv = []229 any_prefix_is_slash = False230 for opt in options:231 prefix = split_opt(opt)[0]232 if prefix == '/':233 any_prefix_is_slash = True234 rv.append((len(prefix), opt))235236 rv.sort(key=lambda x: x[0])237238 rv = ', '.join(x[1] for x in rv)239 return rv, any_prefix_is_slash
modified:click/parser.py+12 added-2 removed
27 unmodified lines
28 return opt[:2], opt[2:]29 return first, opt[1:]303132def normalize_opt(opt, ctx):33 if ctx is None or ctx.token_normalize_func is None:34 return opt35 prefix, opt = split_opt(opt)36 return prefix + ctx.token_normalize_func(opt)373839def split_arg_string(string):40 """Given an argument string this attempts to split it into small parts."""41 rv = []42 for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
119 unmodified lines
162 that is returned from the parser.163 """164 if obj is None:165 obj = dest166 opts = [normalize_opt(opt, self.ctx) for opt in opts]167 option = Option(opts, dest, action=action, nargs=nargs,168 const=const, obj=obj)169 self._opt_prefixes.update(option.prefixes)170 for opt in option._short_opts:
104 unmodified lines
275 else:276 opt = arg277 had_explicit_value = False278279 opt = normalize_opt(opt, self.ctx)280281 opt = self._match_long_opt(opt)282 option = self._long_opt[opt]283 if option.takes_value:284 nargs = option.nargs
16 unmodified lines
301302 option.process(value, state)303304 def _process_opts(self, arg, state):295 if '=' in arg or arg in self._long_opt:305 if '=' in arg or normalize_opt(arg, self.ctx) in self._long_opt:306 return self._process_long_opt(arg, state)307308 stop = False309 i = 1310 prefix = arg[0]311 for ch in arg[1:]:302 opt = prefix + ch312 opt = normalize_opt(prefix + ch, self.ctx)313 option = self._short_opt.get(opt)314 i += 1315316 if not option:
31 unmodified lines
modified:click/types.py+10 added
121 unmodified lines
122 def get_missing_message(self, param):123 return 'Choose from %s.' % ', '.join(self.choices)124125 def convert(self, value, param, ctx):126 # Exact match127 if value in self.choices:128 return value129130 # Match through normalization131 if ctx is not None and \132 ctx.token_normalize_func is not None:133 value = ctx.token_normalize_func(value)134 for choice in self.choices:135 if ctx.token_normalize_func(choice) == value:136 return choice137138 self.fail('invalid choice: %s. (choose from %s)' %139 (value, ', '.join(self.choices)), param, ctx)140141 def __repr__(self):
310 unmodified lines
added:tests/test_normalization.py+39 added
1import click234CONTEXT_DEFAULTS = dict(token_normalize_func=lambda x: x.lower())567def test_option_normalization(runner):8 @click.command(context_defaults=CONTEXT_DEFAULTS)9 @click.option('--foo')10 @click.option('-x')11 def cli(foo, x):12 click.echo(foo)13 click.echo(x)1415 result = runner.invoke(cli, ['--FOO', '42', '-X', 23])16 assert result.output == '42\n23\n'171819def test_choice_normalization(runner):20 @click.command(context_defaults=CONTEXT_DEFAULTS)21 @click.option('--choice', type=click.Choice(['Foo', 'Bar']))22 def cli(choice):23 click.echo('Foo')2425 result = runner.invoke(cli, ['--CHOICE', 'FOO'])26 assert result.output == 'Foo\n'272829def test_command_normalization(runner):30 @click.group(context_defaults=CONTEXT_DEFAULTS)31 def cli():32 pass3334 @cli.command()35 def foo():36 click.echo('here!')3738 result = runner.invoke(cli, ['FOO'])39 assert result.output == 'here!\n'
modified:tests/test_options.py+6 added-6 removed
128 unmodified lines
129 assert result.output == '42\n'130131132def test_winstyle_options(runner):133 @click.command(add_help_option=False)133 @click.command()134 @click.option('/debug;/no-debug', help='Enables or disables debug mode.')135 @click.help_option('/?')135 def cmd(debug):136 click.echo(debug)137139 result = runner.invoke(cmd, ['/debug'])138 result = runner.invoke(cmd, ['/debug'], help_option_names=['/?'])139 assert result.output == 'True\n'141 result = runner.invoke(cmd, ['/no-debug'])140 result = runner.invoke(cmd, ['/no-debug'], help_option_names=['/?'])141 assert result.output == 'False\n'143 result = runner.invoke(cmd, [])142 result = runner.invoke(cmd, [], help_option_names=['/?'])143 assert result.output == 'False\n'145 result = runner.invoke(cmd, ['/?'])144 result = runner.invoke(cmd, ['/?'], help_option_names=['/?'])145 assert '/debug; /no-debug Enables or disables debug mode.' in result.output146 assert '/? Show this message and exit.' in result.output147148149def test_legacy_options(runner):150 @click.command()
21 unmodified lines
modified:CHANGES+4 added
38 unmodified lines
39- added :func:`pause` which works similar to the Windows ``pause`` cmd40 built-in but becomes an automatic noop if the application is not run41 through a terminal.42- added a bit of extra information about missing choice parameters.43- changed how the help function is implemented to allow global overriding44 of the help option.45- added support for token normalization to implement case insensitive handling.46- added support for providing defaults for context settings.4748Version 1.149-----------50
11 unmodified lines