Merge pull request #1623 from MLH-Fellowship/461-export-dict
Before adoption: this commit came in with the history the project adopted, so no landing records it.
export dict of Click structure
authored by David Lord · committed by GitHub · parents a4bd11c, 4f38446 · Browse files · 4 files·+439 added−2 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+439 added−2 removed
- tests:+268 added−0 removed
- other:+171 added−2 removed
Provenance
- Commit
1658d72- Tree
78b0c8b- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
a4bd11c- Parent 2
4f38446
4 files changed+439 added−2 removed
modified:src/click/core.py+104 added-2 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)93 unmodified lines793 context_settings = {}794 #: 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}>"813 814 def get_usage(self, ctx):226 unmodified lines1041 self.no_args_is_help = no_args_is_help1042 self.hidden = hidden1043 self.deprecated = deprecated1044 1045+ def to_info_dict(self, ctx):1046+ info_dict = super().to_info_dict(ctx)1047+ info_dict.update(1048+ params=[param.to_info_dict() for param in self.get_params(ctx)],1049+ help=self.help,1050+ epilog=self.epilog,1051+ short_help=self.short_help,1052+ hidden=self.hidden,1053+ deprecated=self.deprecated,1054+ )1055+ return info_dict1056+1057 def __repr__(self):1058 return f"<{self.__class__.__name__} {self.name}>"1059 1060 def get_usage(self, ctx):224 unmodified lines1285 "Multi commands in chain mode cannot have"1286 " optional arguments."1287 )1288 1289+ def to_info_dict(self, ctx):1290+ info_dict = super().to_info_dict(ctx)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)1305 rv.append(self.subcommand_metavar)1306 return rv421 unmodified lines1728 self.metavar = metavar1729 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,1745+ "secondary_opts": self.secondary_opts,1746+ "type": self.type.to_info_dict(),1747+ "required": self.required,1748+ "nargs": self.nargs,1749+ "multiple": self.multiple,1750+ "default": self.default,1751+ "envvar": self.envvar,1752+ }1753+1754 def __repr__(self):1755 return f"<{self.__class__.__name__} {self.name}>"1756 1757 @property286 unmodified lines2044 raise TypeError(2045 "Options cannot be count and flags at the same time."2046 )2047 2048+ def to_info_dict(self):2049+ info_dict = super().to_info_dict()2050+ info_dict.update(2051+ help=self.help,2052+ prompt=self.prompt,2053+ is_flag=self.is_flag,2054+ flag_value=self.flag_value,2055+ count=self.count,2056+ hidden=self.hidden,2057+ )2058+ return info_dict2059+2060 def _parse_decls(self, decls, expose_value):2061 opts = []2062 secondary_opts = []2063 name = None268 unmodified linesmodified:src/click/types.py+63 added
41 unmodified lines42 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on43 #: 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}59+60 def __call__(self, value, param=None, ctx=None):61 if value is not None:62 return self.convert(value, param, ctx)63 56 unmodified lines120 def __init__(self, func):121 self.name = func.__name__122 self.func = func123 124+ def to_info_dict(self):125+ info_dict = super().to_info_dict()126+ info_dict["func"] = self.func127+ return info_dict128+129 def convert(self, value, param, ctx):130 try:131 return self.func(value)132 except ValueError:61 unmodified lines194 def __init__(self, choices, case_sensitive=True):195 self.choices = choices196 self.case_sensitive = case_sensitive197 198+ def to_info_dict(self):199+ info_dict = super().to_info_dict()200+ info_dict["choices"] = self.choices201+ info_dict["case_sensitive"] = self.case_sensitive202+ return info_dict203+204 def get_metavar(self, param):205 choices_str = "|".join(self.choices)206 207 # Use curly braces to indicate a required argument.67 unmodified lines275 276 def __init__(self, formats=None):277 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]278 279+ def to_info_dict(self):280+ info_dict = super().to_info_dict()281+ info_dict["formats"] = self.formats282+ return info_dict283+284 def get_metavar(self, param):285 return f"[{'|'.join(self.formats)}]"286 287 def _try_to_convert_date(self, value, format):34 unmodified lines322 self.min_open = min_open323 self.max_open = max_open324 self.clamp = clamp325 326+ def to_info_dict(self):327+ info_dict = super().to_info_dict()328+ info_dict.update(329+ min=self.min,330+ max=self.max,331+ min_open=self.min_open,332+ max_open=self.max_open,333+ clamp=self.clamp,334+ )335+ return info_dict336+337 def convert(self, value, param, ctx):338 import operator339 340 rv = super().convert(value, param, ctx)191 unmodified lines532 self.errors = errors533 self.lazy = lazy534 self.atomic = atomic535 536+ def to_info_dict(self):537+ info_dict = super().to_info_dict()538+ info_dict.update(mode=self.mode, encoding=self.encoding)539+ return info_dict540+541 def resolve_lazy_flag(self, value):542 if self.lazy is not None:543 return self.lazy544 if value == "-":101 unmodified lines646 else:647 self.name = "path"648 self.path_type = "Path"649 650+ def to_info_dict(self):651+ info_dict = super().to_info_dict()652+ info_dict.update(653+ exists=self.exists,654+ file_okay=self.file_okay,655+ dir_okay=self.dir_okay,656+ writable=self.writable,657+ readable=self.readable,658+ allow_dash=self.allow_dash,659+ )660+ return info_dict661+662 def coerce_path_result(self, rv):663 if self.type is not None and not isinstance(rv, self.type):664 if self.type is str:665 rv = rv.decode(get_filesystem_encoding())65 unmodified lines731 732 def __init__(self, types):733 self.types = [convert_type(ty) for ty in types]734 735+ def to_info_dict(self):736+ info_dict = super().to_info_dict()737+ info_dict["types"] = [t.to_info_dict() for t in self.types]738+ return info_dict739+740 @property741 def name(self):742 return f"<{' '.join(ty.name for ty in self.types)}>"743 87 unmodified linesadded:tests/test_info_dict.py+268 added
1+import pytest2+3+import click.types4+5+# Common (obj, expect) pairs used to construct multiple tests.6+STRING_PARAM_TYPE = (click.STRING, {"param_type": "String", "name": "text"})7+INT_PARAM_TYPE = (click.INT, {"param_type": "Int", "name": "integer"})8+BOOL_PARAM_TYPE = (click.BOOL, {"param_type": "Bool", "name": "boolean"})9+HELP_OPTION = (10+ None,11+ {12+ "name": "help",13+ "param_type_name": "option",14+ "opts": ["--help"],15+ "secondary_opts": [],16+ "type": BOOL_PARAM_TYPE[1],17+ "required": False,18+ "nargs": 1,19+ "multiple": False,20+ "default": False,21+ "envvar": None,22+ "help": "Show this message and exit.",23+ "prompt": None,24+ "is_flag": True,25+ "flag_value": True,26+ "count": False,27+ "hidden": False,28+ },29+)30+NAME_ARGUMENT = (31+ click.Argument(["name"]),32+ {33+ "name": "name",34+ "param_type_name": "argument",35+ "opts": ["name"],36+ "secondary_opts": [],37+ "type": STRING_PARAM_TYPE[1],38+ "required": True,39+ "nargs": 1,40+ "multiple": False,41+ "default": None,42+ "envvar": None,43+ },44+)45+NUMBER_OPTION = (46+ click.Option(["-c", "--count", "number"], default=1),47+ {48+ "name": "number",49+ "param_type_name": "option",50+ "opts": ["-c", "--count"],51+ "secondary_opts": [],52+ "type": INT_PARAM_TYPE[1],53+ "required": False,54+ "nargs": 1,55+ "multiple": False,56+ "default": 1,57+ "envvar": None,58+ "help": None,59+ "prompt": None,60+ "is_flag": False,61+ "flag_value": False,62+ "count": False,63+ "hidden": False,64+ },65+)66+HELLO_COMMAND = (67+ click.Command("hello", params=[NUMBER_OPTION[0]]),68+ {69+ "name": "hello",70+ "params": [NUMBER_OPTION[1], HELP_OPTION[1]],71+ "help": None,72+ "epilog": None,73+ "short_help": None,74+ "hidden": False,75+ "deprecated": False,76+ },77+)78+HELLO_GROUP = (79+ click.Group("cli", [HELLO_COMMAND[0]]),80+ {81+ "name": "cli",82+ "params": [HELP_OPTION[1]],83+ "help": None,84+ "epilog": None,85+ "short_help": None,86+ "hidden": False,87+ "deprecated": False,88+ "commands": {"hello": HELLO_COMMAND[1]},89+ "chain": False,90+ },91+)92+93+94+@pytest.mark.parametrize(95+ ("obj", "expect"),96+ [97+ pytest.param(98+ click.types.FuncParamType(range),99+ {"param_type": "Func", "name": "range", "func": range},100+ id="Func ParamType",101+ ),102+ pytest.param(103+ click.UNPROCESSED,104+ {"param_type": "Unprocessed", "name": "text"},105+ id="UNPROCESSED ParamType",106+ ),107+ pytest.param(*STRING_PARAM_TYPE, id="STRING ParamType"),108+ pytest.param(109+ click.Choice(["a", "b"]),110+ {111+ "param_type": "Choice",112+ "name": "choice",113+ "choices": ["a", "b"],114+ "case_sensitive": True,115+ },116+ id="Choice ParamType",117+ ),118+ pytest.param(119+ click.DateTime(["%Y-%m-%d"]),120+ {"param_type": "DateTime", "name": "datetime", "formats": ["%Y-%m-%d"]},121+ id="DateTime ParamType",122+ ),123+ pytest.param(*INT_PARAM_TYPE, id="INT ParamType"),124+ pytest.param(125+ click.IntRange(0, 10, clamp=True),126+ {127+ "param_type": "IntRange",128+ "name": "integer range",129+ "min": 0,130+ "max": 10,131+ "min_open": False,132+ "max_open": False,133+ "clamp": True,134+ },135+ id="IntRange ParamType",136+ ),137+ pytest.param(138+ click.FLOAT, {"param_type": "Float", "name": "float"}, id="FLOAT ParamType"139+ ),140+ pytest.param(141+ click.FloatRange(-0.5, 0.5),142+ {143+ "param_type": "FloatRange",144+ "name": "float range",145+ "min": -0.5,146+ "max": 0.5,147+ "min_open": False,148+ "max_open": False,149+ "clamp": False,150+ },151+ id="FloatRange ParamType",152+ ),153+ pytest.param(*BOOL_PARAM_TYPE, id="Bool ParamType"),154+ pytest.param(155+ click.UUID, {"param_type": "UUID", "name": "uuid"}, id="UUID ParamType"156+ ),157+ pytest.param(158+ click.File(),159+ {"param_type": "File", "name": "filename", "mode": "r", "encoding": None},160+ id="File ParamType",161+ ),162+ pytest.param(163+ click.Path(),164+ {165+ "param_type": "Path",166+ "name": "path",167+ "exists": False,168+ "file_okay": True,169+ "dir_okay": True,170+ "writable": False,171+ "readable": True,172+ "allow_dash": False,173+ },174+ id="Path ParamType",175+ ),176+ pytest.param(177+ click.Tuple((click.STRING, click.INT)),178+ {179+ "param_type": "Tuple",180+ "name": "<text integer>",181+ "types": [STRING_PARAM_TYPE[1], INT_PARAM_TYPE[1]],182+ },183+ id="Tuple ParamType",184+ ),185+ pytest.param(*NUMBER_OPTION, id="Option"),186+ pytest.param(187+ click.Option(["--cache/--no-cache", "-c/-u"]),188+ {189+ "name": "cache",190+ "param_type_name": "option",191+ "opts": ["--cache", "-c"],192+ "secondary_opts": ["--no-cache", "-u"],193+ "type": BOOL_PARAM_TYPE[1],194+ "required": False,195+ "nargs": 1,196+ "multiple": False,197+ "default": False,198+ "envvar": None,199+ "help": None,200+ "prompt": None,201+ "is_flag": True,202+ "flag_value": True,203+ "count": False,204+ "hidden": False,205+ },206+ id="Flag Option",207+ ),208+ pytest.param(*NAME_ARGUMENT, id="Argument"),209+ ],210+)211+def test_parameter(obj, expect):212+ out = obj.to_info_dict()213+ assert out == expect214+215+216+@pytest.mark.parametrize(217+ ("obj", "expect"),218+ [219+ pytest.param(*HELLO_COMMAND, id="Command"),220+ pytest.param(*HELLO_GROUP, id="Group"),221+ pytest.param(222+ click.Group(223+ "base",224+ [click.Command("test", params=[NAME_ARGUMENT[0]]), HELLO_GROUP[0]],225+ ),226+ {227+ "name": "base",228+ "params": [HELP_OPTION[1]],229+ "help": None,230+ "epilog": None,231+ "short_help": None,232+ "hidden": False,233+ "deprecated": False,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+ },245+ },246+ "chain": False,247+ },248+ id="Nested Group",249+ ),250+ ],251+)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