implement export to dictionary
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by yk396 · committed by David Lord · parent a4bd11c · Browse files · 3 files·+364 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Chris Nguyen <chrisngyn99@gmail.com>
Diff stats
3 files+364 added−0 removed
- tests:+257 added−0 removed
- other:+107 added−0 removed
Provenance
- Commit
d874b0a- Tree
53589c6- Author
yk396 <yk396@cornell.edu>- Committer
David Lord <davidism@gmail.com>- Parent
a4bd11c
3 files changed+364 added−0 removed
modified:src/click/core.py+52 added
764 unmodified lines765 context_settings = {}766 #: an optional dictionary with defaults passed to the context.767 self.context_settings = context_settings768 769+ def to_info_dict(self, ctx):770+ return {"name": self.name}771+772 def __repr__(self):773 return f"<{self.__class__.__name__} {self.name}>"774 775 def get_usage(self, ctx):226 unmodified lines1002 self.no_args_is_help = no_args_is_help1003 self.hidden = hidden1004 self.deprecated = deprecated1005 1006+ def to_info_dict(self, ctx):1007+ info_dict = super().to_info_dict(ctx)1008+ info_dict.update(1009+ params=[param.to_info_dict() for param in self.get_params(ctx)],1010+ help=self.help,1011+ epilog=self.epilog,1012+ short_help=self.short_help,1013+ hidden=self.hidden,1014+ deprecated=self.deprecated,1015+ )1016+ return info_dict1017+1018 def __repr__(self):1019 return f"<{self.__class__.__name__} {self.name}>"1020 1021 def get_usage(self, ctx):224 unmodified lines1246 "Multi commands in chain mode cannot have"1247 " optional arguments."1248 )1249 1250+ def to_info_dict(self, ctx):1251+ 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+ )1259+ return info_dict1260+1261 def collect_usage_pieces(self, ctx):1262 rv = super().collect_usage_pieces(ctx)1263 rv.append(self.subcommand_metavar)1264 return rv421 unmodified lines1686 self.metavar = metavar1687 self.envvar = envvar1688 self.autocompletion = autocompletion1689 1690+ def to_info_dict(self):1691+ return {1692+ "name": self.name,1693+ "param_type_name": self.param_type_name,1694+ "opts": self.opts,1695+ "secondary_opts": self.secondary_opts,1696+ "type": self.type.to_info_dict(),1697+ "required": self.required,1698+ "nargs": self.nargs,1699+ "multiple": self.multiple,1700+ "default": self.default,1701+ "envvar": self.envvar,1702+ }1703+1704 def __repr__(self):1705 return f"<{self.__class__.__name__} {self.name}>"1706 1707 @property286 unmodified lines1994 raise TypeError(1995 "Options cannot be count and flags at the same time."1996 )1997 1998+ def to_info_dict(self):1999+ info_dict = super().to_info_dict()2000+ info_dict.update(2001+ help=self.help,2002+ prompt=self.prompt,2003+ is_flag=self.is_flag,2004+ flag_value=self.flag_value,2005+ count=self.count,2006+ hidden=self.hidden,2007+ )2008+ return info_dict2009+2010 def _parse_decls(self, decls, expose_value):2011 opts = []2012 secondary_opts = []2013 name = None268 unmodified linesmodified:src/click/types.py+55 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+ # The class name without the "ParamType" suffix.48+ param_type = type(self).__name__.partition("ParamType")[0]49+ param_type = param_type.partition("ParameterType")[0]50+ return {"param_type": param_type, "name": self.name}51+52 def __call__(self, value, param=None, ctx=None):53 if value is not None:54 return self.convert(value, param, ctx)55 56 unmodified lines112 def __init__(self, func):113 self.name = func.__name__114 self.func = func115 116+ def to_info_dict(self):117+ info_dict = super().to_info_dict()118+ info_dict["func"] = self.func119+ return info_dict120+121 def convert(self, value, param, ctx):122 try:123 return self.func(value)124 except ValueError:61 unmodified lines186 def __init__(self, choices, case_sensitive=True):187 self.choices = choices188 self.case_sensitive = case_sensitive189 190+ def to_info_dict(self):191+ info_dict = super().to_info_dict()192+ info_dict["choices"] = self.choices193+ info_dict["case_sensitive"] = self.case_sensitive194+ return info_dict195+196 def get_metavar(self, param):197 choices_str = "|".join(self.choices)198 199 # Use curly braces to indicate a required argument.67 unmodified lines267 268 def __init__(self, formats=None):269 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]270 271+ def to_info_dict(self):272+ info_dict = super().to_info_dict()273+ info_dict["formats"] = self.formats274+ return info_dict275+276 def get_metavar(self, param):277 return f"[{'|'.join(self.formats)}]"278 279 def _try_to_convert_date(self, value, format):34 unmodified lines314 self.min_open = min_open315 self.max_open = max_open316 self.clamp = clamp317 318+ def to_info_dict(self):319+ info_dict = super().to_info_dict()320+ info_dict.update(321+ min=self.min,322+ max=self.max,323+ min_open=self.min_open,324+ max_open=self.max_open,325+ clamp=self.clamp,326+ )327+ return info_dict328+329 def convert(self, value, param, ctx):330 import operator331 332 rv = super().convert(value, param, ctx)191 unmodified lines524 self.errors = errors525 self.lazy = lazy526 self.atomic = atomic527 528+ def to_info_dict(self):529+ info_dict = super().to_info_dict()530+ info_dict.update(mode=self.mode, encoding=self.encoding)531+ return info_dict532+533 def resolve_lazy_flag(self, value):534 if self.lazy is not None:535 return self.lazy536 if value == "-":101 unmodified lines638 else:639 self.name = "path"640 self.path_type = "Path"641 642+ def to_info_dict(self):643+ info_dict = super().to_info_dict()644+ info_dict.update(645+ exists=self.exists,646+ file_okay=self.file_okay,647+ dir_okay=self.dir_okay,648+ writable=self.writable,649+ readable=self.readable,650+ allow_dash=self.allow_dash,651+ )652+ return info_dict653+654 def coerce_path_result(self, rv):655 if self.type is not None and not isinstance(rv, self.type):656 if self.type is str:657 rv = rv.decode(get_filesystem_encoding())65 unmodified lines723 724 def __init__(self, types):725 self.types = [convert_type(ty) for ty in types]726 727+ def to_info_dict(self):728+ info_dict = super().to_info_dict()729+ info_dict["types"] = [t.to_info_dict() for t in self.types]730+ return info_dict731+732 @property733 def name(self):734 return f"<{' '.join(ty.name for ty in self.types)}>"735 87 unmodified linesadded:tests/test_info_dict.py+257 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_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+ """Test to_info_dict for types and parameters."""213+ out = obj.to_info_dict()214+ assert out == expect215+216+217+@pytest.mark.parametrize(218+ ("obj", "expect"),219+ [220+ pytest.param(*HELLO_COMMAND, id="Command"),221+ pytest.param(*HELLO_GROUP, id="Group"),222+ pytest.param(223+ click.Group(224+ "base",225+ [click.Command("test", params=[NAME_ARGUMENT[0]]), HELLO_GROUP[0]],226+ ),227+ {228+ "name": "base",229+ "params": [HELP_OPTION[1]],230+ "help": None,231+ "epilog": None,232+ "short_help": None,233+ "hidden": False,234+ "deprecated": False,235+ "commands": [236+ HELLO_GROUP[1],237+ {238+ "name": "test",239+ "params": [NAME_ARGUMENT[1], HELP_OPTION[1]],240+ "help": None,241+ "epilog": None,242+ "short_help": None,243+ "hidden": False,244+ "deprecated": False,245+ },246+ ],247+ "chain": False,248+ },249+ id="Nested Group",250+ ),251+ ],252+)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)256+ out = obj.to_info_dict(ctx)257+ assert out == expect