implement Context.to_info_dict
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Context has extra information, and traverses the entire CLI. Group.commands is a dict. Push a new context when traversing subcommands. Add docs and changelog.
authored by David Lord · committed by David Lord · parent d874b0a · Browse files · 4 files·+91 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+91 added−18 removed
- tests:+20 added−9 removed
- other:+71 added−9 removed
Provenance
- Commit
4f38446- Tree
78b0c8b- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
d874b0a
4 files changed+91 added−18 removed
modified:src/click/core.py+59 added-9 removed
411 unmodified lines412 self._depth = 0413 self._source_by_paramname = {}414 self._exit_stack = ExitStack()415 416+ def to_info_dict(self):417+ """Gather information that could be useful for a tool generating418+ user-facing documentation. This traverses the entire CLI419+ structure.420+421+ .. code-block:: python422+423+ with Context(cli) as ctx:424+ info = ctx.to_info_dict()425+426+ .. versionadded:: 8.0427+ """428+ return {429+ "command": self.command.to_info_dict(self),430+ "info_name": self.info_name,431+ "allow_extra_args": self.allow_extra_args,432+ "allow_interspersed_args": self.allow_interspersed_args,433+ "ignore_unknown_options": self.ignore_unknown_options,434+ "auto_envvar_prefix": self.auto_envvar_prefix,435+ }436+437 def __enter__(self):438 self._depth += 1439 push_context(self)440 return self211 unmodified lines652 context and command.653 """654 return self.command.get_help(self)655 656+ def _make_sub_context(self, command):657+ """Create a new context of the same type as this context, but658+ for a new command.659+660+ :meta private:661+ """662+ return type(self)(command, info_name=command.name, parent=self)663+664 def invoke(*args, **kwargs): # noqa: B902665 """Invokes a command callback in exactly the way it expects. There666 are two ways to invoke this method:667 23 unmodified lines691 raise TypeError(692 "The given command does not have a callback that can be invoked."693 )694 666- # Create a new context of the same type as this context.667- ctx = type(self)(other_cmd, info_name=other_cmd.name, parent=self)695+ ctx = self._make_sub_context(other_cmd)696 697 for param in other_cmd.params:698 if param.name not in kwargs and param.expose_value:699 kwargs[param.name] = param.get_default(ctx)94 unmodified lines794 #: an optional dictionary with defaults passed to the context.795 self.context_settings = context_settings796 797 def to_info_dict(self, ctx):798+ """Gather information that could be useful for a tool generating799+ user-facing documentation. This traverses the entire structure800+ below this command.801+802+ Use :meth:`click.Context.to_info_dict` to traverse the entire803+ CLI structure.804+805+ :param ctx: A :class:`Context` representing this command.806+807+ .. versionadded:: 8.0808+ """809 return {"name": self.name}810 811 def __repr__(self):812 return f"<{self.__class__.__name__} {self.name}>"474 unmodified lines1287 )1288 1289 def to_info_dict(self, ctx):1290 info_dict = super().to_info_dict(ctx)1252- info_dict.update(1253- commands=[1254- self.get_command(ctx, cmd_name).to_info_dict(ctx)1255- for cmd_name in self.list_commands(ctx)1256- ],1257- chain=self.chain,1258- )1291+ commands = {}1292+1293+ for name in self.list_commands(ctx):1294+ command = self.get_command(ctx, name)1295+ sub_ctx = ctx._make_sub_context(command)1296+1297+ with sub_ctx.scope(cleanup=False):1298+ commands[name] = command.to_info_dict(sub_ctx)1299+1300+ info_dict.update(commands=commands, chain=self.chain)1301 return info_dict1302 1303 def collect_usage_pieces(self, ctx):1304 rv = super().collect_usage_pieces(ctx)424 unmodified lines1729 self.envvar = envvar1730 self.autocompletion = autocompletion1731 1732 def to_info_dict(self):1733+ """Gather information that could be useful for a tool generating1734+ user-facing documentation.1735+1736+ Use :meth:`click.Context.to_info_dict` to traverse the entire1737+ CLI structure.1738+1739+ .. versionadded:: 8.01740+ """1741 return {1742 "name": self.name,1743 "param_type_name": self.param_type_name,1744 "opts": self.opts,587 unmodified linesmodified:src/click/types.py+8 added
42 unmodified lines43 #: Windows).44 envvar_list_splitter = None45 46 def to_info_dict(self):47+ """Gather information that could be useful for a tool generating48+ user-facing documentation.49+50+ Use :meth:`click.Context.to_info_dict` to traverse the entire51+ CLI structure.52+53+ .. versionadded:: 8.054+ """55 # The class name without the "ParamType" suffix.56 param_type = type(self).__name__.partition("ParamType")[0]57 param_type = param_type.partition("ParameterType")[0]58 return {"param_type": param_type, "name": self.name}772 unmodified linesmodified:tests/test_info_dict.py+20 added-9 removed
83 unmodified lines84 "epilog": None,85 "short_help": None,86 "hidden": False,87 "deprecated": False,88- "commands": [HELLO_COMMAND[1]],88+ "commands": {"hello": HELLO_COMMAND[1]},89 "chain": False,90 },91 )92 115 unmodified lines208 pytest.param(*NAME_ARGUMENT, id="Argument"),209 ],210 )211 def test_parameter(obj, expect):212- """Test to_info_dict for types and parameters."""212 out = obj.to_info_dict()213 assert out == expect214 215 14 unmodified lines230 "epilog": None,231 "short_help": None,232 "hidden": False,233 "deprecated": False,235- "commands": [236- HELLO_GROUP[1],237- {234+ "commands": {235+ "cli": HELLO_GROUP[1],236+ "test": {237 "name": "test",238 "params": [NAME_ARGUMENT[1], HELP_OPTION[1]],239 "help": None,240 "epilog": None,241 "short_help": None,242 "hidden": False,243 "deprecated": False,244 },246- ],245+ },246 "chain": False,247 },248 id="Nested Group",249 ),250 ],251 )253-def test_ctx_obj(obj, expect):254- """Test to_info_dict for objects that have a make_context method."""255- ctx = obj.make_context("test", [], resilient_parsing=True)252+def test_command(obj, expect):253+ ctx = click.Context(obj)254 out = obj.to_info_dict(ctx)255 assert out == expect256+257+258+def test_context():259+ ctx = click.Context(HELLO_COMMAND[0])260+ out = ctx.to_info_dict()261+ assert out == {262+ "command": HELLO_COMMAND[1],263+ "info_name": None,264+ "allow_extra_args": False,265+ "allow_interspersed_args": True,266+ "ignore_unknown_options": False,267+ "auto_envvar_prefix": None,268+ }modified:CHANGES.rst+4 added
84 unmodified lines85 - When creating a ``Group``, allow passing a list of commands instead86 of a dict. :issue:`1339`87 - When a long option name isn't valid, use ``difflib`` to make better88 suggestions for possible corrections. :issue:`1446`89+- Core objects have a ``to_info_dict()`` method. This gathers90+ information about the object's structure that could be useful for a91+ tool generating user-facing documentation. To get the structure of92+ an entire CLI, use ``Context(cli).to_info_dict()``. :issue:`461`93 94 95 Version 7.1.296 -------------635 unmodified lines