Skip to content
Myr

Merge pull request #938 from txomon/feature/make-extendable

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

Make core extendable by making classes and initializations configurable

authored by David Lord · committed by GitHub · parents 97fde8b, aff5168 · Browse files · 7 files+242 added−40 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+242 added−40 removed

  • tests:+113 added−1 removed
  • other:+129 added−39 removed

7 files+242 added−40 removed

modified:src/click/_winconsole.py+1 added-1 removed
111 unmodified lines
112 def __init__(self, handle):113 self.handle = handle114115 def isatty(self):116 io.RawIOBase.isatty(self)116 super().isatty()117 return True118119120class _WindowsConsoleReader(_WindowsConsoleRawIOBase):
188 unmodified lines
modified:src/click/core.py+100 added-27 removed
243 unmodified lines
244 Even if an option is later created with show_default=False,245 this command-level setting overrides it.246 """247248 #: The formatter class to create with :meth:`make_formatter`.249 #:250 #: .. versionadded:: 8.0251 formatter_class = HelpFormatter252253 def __init__(254 self,255 command,256 parent=None,
222 unmodified lines
479 """480 return self._meta481482 def make_formatter(self):478 """Creates the formatter for the help and usage output."""479 return HelpFormatter(483 """Creates the :class:`~click.HelpFormatter` for the help and484 usage output.485486 To quickly customize the formatter class used without overriding487 this method, set the :attr:`formatter_class` attribute.488489 .. versionchanged:: 8.0490 Added the :attr:`formatter_class` attribute.491 """492 return self.formatter_class(493 width=self.terminal_width, max_width=self.max_content_width494 )495496 def call_on_close(self, f):
116 unmodified lines
613 # in defaults and make a new context for this command.614 if isinstance(callback, Command):615 other_cmd = callback616 callback = other_cmd.callback604 ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)617618 if callback is None:619 raise TypeError(620 "The given command does not have a callback that can be invoked."621 )622623 # Create a new context of the same type as this context.624 ctx = type(self)(other_cmd, info_name=other_cmd.name, parent=self)625626 for param in other_cmd.params:627 if param.name not in kwargs and param.expose_value:628 kwargs[param.name] = param.get_default(ctx)629
8 unmodified lines
638 it. This cannot invoke callbacks directly, only other commands.639 """640 self, cmd = args[:2]641626 # It's also possible to invoke another command which might or627 # might not have a callback.642 # Can only forward to other commands, not direct callbacks.643 if not isinstance(cmd, Command):644 raise TypeError("Callback is not a command.")645646 for param in self.params:
53 unmodified lines
700 :param context_settings: an optional dictionary with defaults that are701 passed to the context object.702 """703704 #: The context class to create with :meth:`make_context`.705 #:706 #: .. versionadded:: 8.0707 context_class = Context708 #: the default for the :attr:`Context.allow_extra_args` flag.709 allow_extra_args = False710 #: the default for the :attr:`Context.allow_interspersed_args` flag.711 allow_interspersed_args = True
24 unmodified lines
736 """This function when given an info name and arguments will kick737 off the parsing and create a new :class:`Context`. It does not738 invoke the actual command callback though.739740 To quickly customize the context class used without overriding741 this method, set the :attr:`context_class` attribute.742743 :param info_name: the info name for this invokation. Generally this744 is the most descriptive name for the script or745 command. For the toplevel script it's usually746 the name of the script, for commands below it it's
1 unmodified line
748 :param args: the arguments to parse as list of strings.749 :param parent: the parent context if available.750 :param extra: extra keyword arguments forwarded to the context751 constructor.752753 .. versionchanged:: 8.0754 Added the :attr:`context_class` attribute.755 """756 for key, value in self.context_settings.items():757 if key not in extra:758 extra[key] = value759734 ctx = Context(self, info_name=info_name, parent=parent, **extra)760 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)761762 with ctx.scope(cleanup=False):763 self.parse_args(ctx, args)764 return ctx765
169 unmodified lines
935 no_args_is_help=False,936 hidden=False,937 deprecated=False,938 ):912 BaseCommand.__init__(self, name, context_settings)939 super().__init__(name, context_settings)940 #: the callback to execute when the command fires. This might be941 #: `None` in which case nothing happens.942 self.callback = callback943 #: the list of parameters for this command in the order they
220 unmodified lines
1164 chain=False,1165 result_callback=None,1166 **attrs,1167 ):1141 Command.__init__(self, name, **attrs)1168 super().__init__(name, **attrs)1169 if no_args_is_help is None:1170 no_args_is_help = not invoke_without_command1171 self.no_args_is_help = no_args_is_help1172 self.invoke_without_command = invoke_without_command
16 unmodified lines
1189 " optional arguments."1190 )11911192 def collect_usage_pieces(self, ctx):1166 rv = Command.collect_usage_pieces(self, ctx)1193 rv = super().collect_usage_pieces(ctx)1194 rv.append(self.subcommand_metavar)1195 return rv11961197 def format_options(self, ctx, formatter):1171 Command.format_options(self, ctx, formatter)1198 super().format_options(ctx, formatter)1199 self.format_commands(ctx, formatter)12001201 def resultcallback(self, replace=False):1202 """Adds a result callback to the command. By default if a
67 unmodified lines
1270 if not args and self.no_args_is_help and not ctx.resilient_parsing:1271 echo(ctx.get_help(), color=ctx.color)1272 ctx.exit()12731247 rest = Command.parse_args(self, ctx, args)1274 rest = super().parse_args(ctx, args)12751276 if self.chain:1277 ctx.protected_args = rest1278 ctx.args = []1279 elif rest:
12 unmodified lines
1292 # No subcommand was invoked, so the result callback is1293 # invoked with None for regular groups, or an empty list1294 # for chained groups.1295 with ctx:1268 Command.invoke(self, ctx)1296 super().invoke(ctx)1297 return _process_result([] if self.chain else None)1298 ctx.fail("Missing command.")12991300 # Fetch args back out
9 unmodified lines
1310 # resources until the result processor has worked.1311 with ctx:1312 cmd_name, cmd, args = self.resolve_command(ctx, args)1313 ctx.invoked_subcommand = cmd_name1286 Command.invoke(self, ctx)1314 super().invoke(ctx)1315 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)1316 with sub_ctx:1317 return _process_result(sub_ctx.command.invoke(sub_ctx))1318
3 unmodified lines
1322 # set to ``*`` to inform the command that subcommands are executed1323 # but nothing else.1324 with ctx:1325 ctx.invoked_subcommand = "*" if args else None1298 Command.invoke(self, ctx)1326 super().invoke(ctx)13271328 # Otherwise we make every single context and invoke them in a1329 # chain. In that case the return value to the result processor1330 # is the list of all invoked subcommand's results.
61 unmodified lines
13921393 :param commands: a dictionary of commands.1394 """13951396 #: If set, this is used by the group's :meth:`command` decorator1397 #: as the default :class:`Command` class. This is useful to make all1398 #: subcommands use a custom command class.1399 #:1400 #: .. versionadded:: 8.01401 command_class = None14021403 #: If set, this is used by the group's :meth:`group` decorator1404 #: as the default :class:`Group` class. This is useful to make all1405 #: subgroups use a custom group class.1406 #:1407 #: If set to the special value :class:`type` (literally1408 #: ``group_class = type``), this group's class will be used as the1409 #: default class. This makes a custom group class continue to make1410 #: custom groups.1411 #:1412 #: .. versionadded:: 8.01413 group_class = None14141415 def __init__(self, name=None, commands=None, **attrs):1369 MultiCommand.__init__(self, name, **attrs)1416 super().__init__(name, **attrs)1417 #: the registered subcommands by their exported names.1418 self.commands = commands or {}14191420 def add_command(self, cmd, name=None):
7 unmodified lines
1428 self.commands[name] = cmd14291430 def command(self, *args, **kwargs):1431 """A shortcut decorator for declaring and attaching a command to1385 the group. This takes the same arguments as :func:`command` but1386 immediately registers the created command with this instance by1387 calling into :meth:`add_command`.1432 the group. This takes the same arguments as :func:`command` and1433 immediately registers the created command with this group by1434 calling :meth:`add_command`.14351436 To customize the command class used, set the1437 :attr:`command_class` attribute.14381439 .. versionchanged:: 8.01440 Added the :attr:`command_class` attribute.1441 """1442 from .decorators import command14431444 if self.command_class is not None and "cls" not in kwargs:1445 kwargs["cls"] = self.command_class14461447 def decorator(f):1448 cmd = command(*args, **kwargs)(f)1449 self.add_command(cmd)1450 return cmd
1 unmodified line
1452 return decorator14531454 def group(self, *args, **kwargs):1455 """A shortcut decorator for declaring and attaching a group to1400 the group. This takes the same arguments as :func:`group` but1401 immediately registers the created command with this instance by1402 calling into :meth:`add_command`.1456 the group. This takes the same arguments as :func:`group` and1457 immediately registers the created group with this group by1458 calling :meth:`add_command`.14591460 To customize the group class used, set the :attr:`group_class`1461 attribute.14621463 .. versionchanged:: 8.01464 Added the :attr:`group_class` attribute.1465 """1466 from .decorators import group14671468 if self.group_class is not None and "cls" not in kwargs:1469 if self.group_class is type:1470 kwargs["cls"] = type(self)1471 else:1472 kwargs["cls"] = self.group_class14731474 def decorator(f):1475 cmd = group(*args, **kwargs)(f)1476 self.add_command(cmd)1477 return cmd
14 unmodified lines
1492 provides all the commands for each of them.1493 """14941495 def __init__(self, name=None, sources=None, **attrs):1428 MultiCommand.__init__(self, name, **attrs)1496 super().__init__(name, **attrs)1497 #: The list of registered multi commands.1498 self.sources = sources or []14991500 def add_source(self, multi_cmd):
329 unmodified lines
1830 show_envvar=False,1831 **attrs,1832 ):1833 default_is_missing = attrs.get("default", _missing) is _missing1766 Parameter.__init__(self, param_decls, type=type, **attrs)1834 super().__init__(param_decls, type=type, **attrs)18351836 if prompt is True:1837 prompt_text = self.name.replace("_", " ").capitalize()1838 elif prompt is False:
208 unmodified lines
2047 for param in ctx.command.params:2048 if param.name == self.name and param.default:2049 return param.flag_value2050 return None1983 return Parameter.get_default(self, ctx)20512052 return super().get_default(ctx)20532054 def prompt_for_value(self, ctx):2055 """This is an alternative flow that can be activated in the full2056 value processing if a value does not exist. It will prompt the2057 user until a valid value exists and then returns the processed
17 unmodified lines
2075 value_proc=lambda x: self.process_value(ctx, x),2076 )20772078 def resolve_envvar_value(self, ctx):2010 rv = Parameter.resolve_envvar_value(self, ctx)2079 rv = super().resolve_envvar_value(ctx)20802081 if rv is not None:2082 return rv2083 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:2084 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
12 unmodified lines
20972098 def full_process_value(self, ctx, value):2099 if value is None and self.prompt is not None and not ctx.resilient_parsing:2100 return self.prompt_for_value(ctx)2031 return Parameter.full_process_value(self, ctx, value)21012102 return super().full_process_value(ctx, value)210321042105class Argument(Parameter):2106 """Arguments are positional parameters to a command. They generally2107 provide fewer features than options but can have infinite ``nargs``2108 and are required by default.
8 unmodified lines
2117 if attrs.get("default") is not None:2118 required = False2119 else:2120 required = attrs.get("nargs", 1) > 021212050 Parameter.__init__(self, param_decls, required=required, **attrs)2122 super().__init__(param_decls, required=required, **attrs)21232124 if self.default is not None and self.nargs < 0:2125 raise TypeError(2126 "nargs=-1 in combination with a default value is not supported."2127 )
42 unmodified lines
modified:src/click/exceptions.py+8 added-9 removed
41 unmodified lines
4243 exit_code = 24445 def __init__(self, message, ctx=None):46 ClickException.__init__(self, message)46 super().__init__(message)47 self.ctx = ctx48 self.cmd = self.ctx.command if self.ctx else None4950 def show(self, file=None):
30 unmodified lines
81 each item is quoted and separated.82 """8384 def __init__(self, message, ctx=None, param=None, param_hint=None):85 UsageError.__init__(self, message, ctx)85 super().__init__(message, ctx)86 self.param = param87 self.param_hint = param_hint8889 def format_message(self):
22 unmodified lines
112113 def __init__(114 self, message=None, ctx=None, param=None, param_hint=None, param_type=None115 ):116 BadParameter.__init__(self, message, ctx, param, param_hint)116 super().__init__(message, ctx, param, param_hint)117 self.param_type = param_type118119 def format_message(self):120 if self.param_hint is not None:
37 unmodified lines
158159 def __init__(self, option_name, message=None, possibilities=None, ctx=None):160 if message is None:161 message = f"no such option: {option_name}"162 UsageError.__init__(self, message, ctx)162163 super().__init__(message, ctx)164 self.option_name = option_name165 self.possibilities = possibilities166167 def format_message(self):
17 unmodified lines
185 :param option_name: the name of the option being used incorrectly.186 """187188 def __init__(self, option_name, message, ctx=None):188 UsageError.__init__(self, message, ctx)189 super().__init__(message, ctx)190 self.option_name = option_name191192193class BadArgumentUsage(UsageError):
3 unmodified lines
197198 .. versionadded:: 6.0199 """200200 def __init__(self, message, ctx=None):201 UsageError.__init__(self, message, ctx)201203202class FileError(ClickException):203 """Raised if a file cannot be opened."""204205 def __init__(self, filename, hint=None):206 ui_filename = filename_to_ui(filename)207 if hint is None:208 hint = "unknown error"211 ClickException.__init__(self, hint)209210 super().__init__(hint)211 self.ui_filename = ui_filename212 self.filename = filename213214 def format_message(self):
18 unmodified lines
modified:src/click/types.py+4 added-2 removed
276 unmodified lines
277 self.max = max278 self.clamp = clamp279280 def convert(self, value, param, ctx):281 rv = IntParamType.convert(self, value, param, ctx)281 rv = super().convert(value, param, ctx)282283 if self.clamp:284 if self.min is not None and rv < self.min:285 return self.min286 if self.max is not None and rv > self.max:
57 unmodified lines
344 self.max = max345 self.clamp = clamp346347 def convert(self, value, param, ctx):347 rv = FloatParamType.convert(self, value, param, ctx)348 rv = super().convert(value, param, ctx)349350 if self.clamp:351 if self.min is not None and rv < self.min:352 return self.min353 if self.max is not None and rv > self.max:
375 unmodified lines
modified:tests/test_commands.py+1 added-1 removed
131 unmodified lines
132 pass133134 class OptParseCommand(click.BaseCommand):135 def __init__(self, name, parser, callback):136 click.BaseCommand.__init__(self, name)136 super().__init__(name)137 self.parser = parser138 self.callback = callback139140 def parse_args(self, ctx, args):
176 unmodified lines
added:tests/test_custom_classes.py+112 added
1import click234def test_command_context_class():5 """A command with a custom ``context_class`` should produce a6 context using that type.7 """89 class CustomContext(click.Context):10 pass1112 class CustomCommand(click.Command):13 context_class = CustomContext1415 command = CustomCommand("test")16 context = command.make_context("test", [])17 assert isinstance(context, CustomContext)181920def test_context_invoke_type(runner):21 """A command invoked from a custom context should have a new22 context with the same type.23 """2425 class CustomContext(click.Context):26 pass2728 class CustomCommand(click.Command):29 context_class = CustomContext3031 @click.command()32 @click.argument("first_id", type=int)33 @click.pass_context34 def second(ctx, first_id):35 assert isinstance(ctx, CustomContext)36 assert id(ctx) != first_id3738 @click.command(cls=CustomCommand)39 @click.pass_context40 def first(ctx):41 assert isinstance(ctx, CustomContext)42 ctx.invoke(second, first_id=id(ctx))4344 assert not runner.invoke(first).exception454647def test_context_formatter_class():48 """A context with a custom ``formatter_class`` should format help49 using that type.50 """5152 class CustomFormatter(click.HelpFormatter):53 def write_heading(self, heading):54 heading = click.style(heading, fg="yellow")55 return super().write_heading(heading)5657 class CustomContext(click.Context):58 formatter_class = CustomFormatter5960 context = CustomContext(61 click.Command("test", params=[click.Option(["--value"])]), color=True62 )63 assert "\x1b[33mOptions\x1b[0m:" in context.get_help()646566def test_group_command_class(runner):67 """A group with a custom ``command_class`` should create subcommands68 of that type by default.69 """7071 class CustomCommand(click.Command):72 pass7374 class CustomGroup(click.Group):75 command_class = CustomCommand7677 group = CustomGroup()78 subcommand = group.command()(lambda: None)79 assert type(subcommand) is CustomCommand80 subcommand = group.command(cls=click.Command)(lambda: None)81 assert type(subcommand) is click.Command828384def test_group_group_class(runner):85 """A group with a custom ``group_class`` should create subgroups86 of that type by default.87 """8889 class CustomSubGroup(click.Group):90 pass9192 class CustomGroup(click.Group):93 group_class = CustomSubGroup9495 group = CustomGroup()96 subgroup = group.group()(lambda: None)97 assert type(subgroup) is CustomSubGroup98 subgroup = group.command(cls=click.Group)(lambda: None)99 assert type(subgroup) is click.Group100101102def test_group_group_class_self(runner):103 """A group with ``group_class = type`` should create subgroups of104 the same type as itself.105 """106107 class CustomGroup(click.Group):108 group_class = type109110 group = CustomGroup()111 subgroup = group.group()(lambda: None)112 assert type(subgroup) is CustomGroup
modified:CHANGES.rst+16 added
41 unmodified lines
42- Non-string objects passed to ``style()`` and ``secho()`` will be43 converted to string. :pr:`1146`44- ``edit(require_save=True)`` will detect saves for editors that exit45 very fast on filesystems with 1 second resolution. :pr:`1050`46- New class attributes make it easier to use custom core objects47 throughout an entire application. :pr:`938`4849 - ``Command.context_class`` controls the context created when50 running the command.51 - ``Context.invoke`` creates new contexts of the same type, so a52 custom type will persist to invoked subcommands.53 - ``Context.formatter_class`` controls the formatter used to54 generate help and usage.55 - ``Group.command_class`` changes the default type for56 subcommands with ``@group.command()``.57 - ``Group.group_class`` changes the default type for subgroups58 with ``@group.group()``. Setting it to ``type`` will create59 subgroups of the same type as the group itself.60 - Core objects use ``super()`` consistently for better support of61 subclassing.626364Version 7.1.265-------------6667Released 2020-04-27
633 unmodified lines