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
Provenance
- Commit
d75ea33- Tree
2855cfe- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
97fde8b- Parent 2
aff5168
7 files changed+242 added−40 removed
modified:src/click/_winconsole.py+1 added-1 removed
111 unmodified lines112 def __init__(self, handle):113 self.handle = handle114 115 def isatty(self):116- io.RawIOBase.isatty(self)116+ super().isatty()117 return True118 119 120 class _WindowsConsoleReader(_WindowsConsoleRawIOBase):188 unmodified linesmodified:src/click/core.py+100 added-27 removed
243 unmodified lines244 Even if an option is later created with show_default=False,245 this command-level setting overrides it.246 """247 248+ #: The formatter class to create with :meth:`make_formatter`.249+ #:250+ #: .. versionadded:: 8.0251+ formatter_class = HelpFormatter252+253 def __init__(254 self,255 command,256 parent=None,222 unmodified lines479 """480 return self._meta481 482 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.485+486+ To quickly customize the formatter class used without overriding487+ this method, set the :attr:`formatter_class` attribute.488+489+ .. 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 )495 496 def call_on_close(self, f):116 unmodified lines613 # 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)617+618 if callback is None:619 raise TypeError(620 "The given command does not have a callback that can be invoked."621 )622 623+ # Create a new context of the same type as this context.624+ ctx = type(self)(other_cmd, info_name=other_cmd.name, parent=self)625+626 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 lines638 it. This cannot invoke callbacks directly, only other commands.639 """640 self, cmd = args[:2]641 626- # 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.")645 646 for param in self.params:53 unmodified lines700 :param context_settings: an optional dictionary with defaults that are701 passed to the context object.702 """703 704+ #: 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 = True24 unmodified lines736 """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.739 740+ To quickly customize the context class used without overriding741+ this method, set the :attr:`context_class` attribute.742+743 :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's1 unmodified line748 :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.752+753+ .. 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] = value759+734- ctx = Context(self, info_name=info_name, parent=parent, **extra)760+ ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)761+762 with ctx.scope(cleanup=False):763 self.parse_args(ctx, args)764 return ctx765 169 unmodified lines935 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 they220 unmodified lines1164 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_command16 unmodified lines1189 " optional arguments."1190 )1191 1192 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 rv1196 1197 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)1200 1201 def resultcallback(self, replace=False):1202 """Adds a result callback to the command. By default if a67 unmodified lines1270 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()1273 1247- rest = Command.parse_args(self, ctx, args)1274+ rest = super().parse_args(ctx, args)1275+1276 if self.chain:1277 ctx.protected_args = rest1278 ctx.args = []1279 elif rest:12 unmodified lines1292 # 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.")1299 1300 # Fetch args back out9 unmodified lines1310 # 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 lines1322 # 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)1327 1328 # 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 lines1392 1393 :param commands: a dictionary of commands.1394 """1395 1396+ #: 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 = None1402+1403+ #: 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 = None1414+1415 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 {}1419 1420 def add_command(self, cmd, name=None):7 unmodified lines1428 self.commands[name] = cmd1429 1430 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`.1435+1436+ To customize the command class used, set the1437+ :attr:`command_class` attribute.1438+1439+ .. versionchanged:: 8.01440+ Added the :attr:`command_class` attribute.1441 """1442 from .decorators import command1443 1444+ if self.command_class is not None and "cls" not in kwargs:1445+ kwargs["cls"] = self.command_class1446+1447 def decorator(f):1448 cmd = command(*args, **kwargs)(f)1449 self.add_command(cmd)1450 return cmd1 unmodified line1452 return decorator1453 1454 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`.1459+1460+ To customize the group class used, set the :attr:`group_class`1461+ attribute.1462+1463+ .. versionchanged:: 8.01464+ Added the :attr:`group_class` attribute.1465 """1466 from .decorators import group1467 1468+ 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_class1473+1474 def decorator(f):1475 cmd = group(*args, **kwargs)(f)1476 self.add_command(cmd)1477 return cmd14 unmodified lines1492 provides all the commands for each of them.1493 """1494 1495 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 []1499 1500 def add_source(self, multi_cmd):329 unmodified lines1830 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)1835 1836 if prompt is True:1837 prompt_text = self.name.replace("_", " ").capitalize()1838 elif prompt is False:208 unmodified lines2047 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)2051 2052+ return super().get_default(ctx)2053+2054 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 processed17 unmodified lines2075 value_proc=lambda x: self.process_value(ctx, x),2076 )2077 2078 def resolve_envvar_value(self, ctx):2010- rv = Parameter.resolve_envvar_value(self, ctx)2079+ rv = super().resolve_envvar_value(ctx)2080+2081 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 lines2097 2098 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)2101 2102+ return super().full_process_value(ctx, value)2103 2104+2105 class 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 lines2117 if attrs.get("default") is not None:2118 required = False2119 else:2120 required = attrs.get("nargs", 1) > 02121+2050- Parameter.__init__(self, param_decls, required=required, **attrs)2122+ super().__init__(param_decls, required=required, **attrs)2123+2124 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 linesmodified:src/click/exceptions.py+8 added-9 removed
41 unmodified lines42 43 exit_code = 244 45 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 None49 50 def show(self, file=None):30 unmodified lines81 each item is quoted and separated.82 """83 84 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_hint88 89 def format_message(self):22 unmodified lines112 113 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_type118 119 def format_message(self):120 if self.param_hint is not None:37 unmodified lines158 159 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)162+163+ super().__init__(message, ctx)164 self.option_name = option_name165 self.possibilities = possibilities166 167 def format_message(self):17 unmodified lines185 :param option_name: the name of the option being used incorrectly.186 """187 188 def __init__(self, option_name, message, ctx=None):188- UsageError.__init__(self, message, ctx)189+ super().__init__(message, ctx)190 self.option_name = option_name191 192 193 class BadArgumentUsage(UsageError):3 unmodified lines197 198 .. versionadded:: 6.0199 """200 200- def __init__(self, message, ctx=None):201- UsageError.__init__(self, message, ctx)201 203-202 class FileError(ClickException):203 """Raised if a file cannot be opened."""204 205 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)209+210+ super().__init__(hint)211 self.ui_filename = ui_filename212 self.filename = filename213 214 def format_message(self):18 unmodified linesmodified:src/click/types.py+4 added-2 removed
276 unmodified lines277 self.max = max278 self.clamp = clamp279 280 def convert(self, value, param, ctx):281- rv = IntParamType.convert(self, value, param, ctx)281+ rv = super().convert(value, param, ctx)282+283 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 lines344 self.max = max345 self.clamp = clamp346 347 def convert(self, value, param, ctx):347- rv = FloatParamType.convert(self, value, param, ctx)348+ rv = super().convert(value, param, ctx)349+350 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 linesmodified:tests/test_commands.py+1 added-1 removed
131 unmodified lines132 pass133 134 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 = callback139 140 def parse_args(self, ctx, args):176 unmodified linesadded:tests/test_custom_classes.py+112 added
1+import click2+3+4+def test_command_context_class():5+ """A command with a custom ``context_class`` should produce a6+ context using that type.7+ """8+9+ class CustomContext(click.Context):10+ pass11+12+ class CustomCommand(click.Command):13+ context_class = CustomContext14+15+ command = CustomCommand("test")16+ context = command.make_context("test", [])17+ assert isinstance(context, CustomContext)18+19+20+def test_context_invoke_type(runner):21+ """A command invoked from a custom context should have a new22+ context with the same type.23+ """24+25+ class CustomContext(click.Context):26+ pass27+28+ class CustomCommand(click.Command):29+ context_class = CustomContext30+31+ @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_id37+38+ @click.command(cls=CustomCommand)39+ @click.pass_context40+ def first(ctx):41+ assert isinstance(ctx, CustomContext)42+ ctx.invoke(second, first_id=id(ctx))43+44+ assert not runner.invoke(first).exception45+46+47+def test_context_formatter_class():48+ """A context with a custom ``formatter_class`` should format help49+ using that type.50+ """51+52+ class CustomFormatter(click.HelpFormatter):53+ def write_heading(self, heading):54+ heading = click.style(heading, fg="yellow")55+ return super().write_heading(heading)56+57+ class CustomContext(click.Context):58+ formatter_class = CustomFormatter59+60+ context = CustomContext(61+ click.Command("test", params=[click.Option(["--value"])]), color=True62+ )63+ assert "\x1b[33mOptions\x1b[0m:" in context.get_help()64+65+66+def test_group_command_class(runner):67+ """A group with a custom ``command_class`` should create subcommands68+ of that type by default.69+ """70+71+ class CustomCommand(click.Command):72+ pass73+74+ class CustomGroup(click.Group):75+ command_class = CustomCommand76+77+ 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.Command82+83+84+def test_group_group_class(runner):85+ """A group with a custom ``group_class`` should create subgroups86+ of that type by default.87+ """88+89+ class CustomSubGroup(click.Group):90+ pass91+92+ class CustomGroup(click.Group):93+ group_class = CustomSubGroup94+95+ 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.Group100+101+102+def test_group_group_class_self(runner):103+ """A group with ``group_class = type`` should create subgroups of104+ the same type as itself.105+ """106+107+ class CustomGroup(click.Group):108+ group_class = type109+110+ group = CustomGroup()111+ subgroup = group.group()(lambda: None)112+ assert type(subgroup) is CustomGroupmodified:CHANGES.rst+16 added
41 unmodified lines42 - 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`48 49+ - ``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.62 63+64 Version 7.1.265 -------------66 67 Released 2020-04-27633 unmodified lines