Skip to content
Myr

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

3 files+364 added−0 removed

modified:src/click/core.py+52 added
764 unmodified lines
765 context_settings = {}766 #: an optional dictionary with defaults passed to the context.767 self.context_settings = context_settings768769 def to_info_dict(self, ctx):770 return {"name": self.name}771772 def __repr__(self):773 return f"<{self.__class__.__name__} {self.name}>"774775 def get_usage(self, ctx):
226 unmodified lines
1002 self.no_args_is_help = no_args_is_help1003 self.hidden = hidden1004 self.deprecated = deprecated10051006 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_dict10171018 def __repr__(self):1019 return f"<{self.__class__.__name__} {self.name}>"10201021 def get_usage(self, ctx):
224 unmodified lines
1246 "Multi commands in chain mode cannot have"1247 " optional arguments."1248 )12491250 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_dict12601261 def collect_usage_pieces(self, ctx):1262 rv = super().collect_usage_pieces(ctx)1263 rv.append(self.subcommand_metavar)1264 return rv
421 unmodified lines
1686 self.metavar = metavar1687 self.envvar = envvar1688 self.autocompletion = autocompletion16891690 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 }17031704 def __repr__(self):1705 return f"<{self.__class__.__name__} {self.name}>"17061707 @property
286 unmodified lines
1994 raise TypeError(1995 "Options cannot be count and flags at the same time."1996 )19971998 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_dict20092010 def _parse_decls(self, decls, expose_value):2011 opts = []2012 secondary_opts = []2013 name = None
268 unmodified lines
modified:src/click/types.py+55 added
41 unmodified lines
42 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on43 #: Windows).44 envvar_list_splitter = None4546 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}5152 def __call__(self, value, param=None, ctx=None):53 if value is not None:54 return self.convert(value, param, ctx)55
56 unmodified lines
112 def __init__(self, func):113 self.name = func.__name__114 self.func = func115116 def to_info_dict(self):117 info_dict = super().to_info_dict()118 info_dict["func"] = self.func119 return info_dict120121 def convert(self, value, param, ctx):122 try:123 return self.func(value)124 except ValueError:
61 unmodified lines
186 def __init__(self, choices, case_sensitive=True):187 self.choices = choices188 self.case_sensitive = case_sensitive189190 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_dict195196 def get_metavar(self, param):197 choices_str = "|".join(self.choices)198199 # Use curly braces to indicate a required argument.
67 unmodified lines
267268 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"]270271 def to_info_dict(self):272 info_dict = super().to_info_dict()273 info_dict["formats"] = self.formats274 return info_dict275276 def get_metavar(self, param):277 return f"[{'|'.join(self.formats)}]"278279 def _try_to_convert_date(self, value, format):
34 unmodified lines
314 self.min_open = min_open315 self.max_open = max_open316 self.clamp = clamp317318 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_dict328329 def convert(self, value, param, ctx):330 import operator331332 rv = super().convert(value, param, ctx)
191 unmodified lines
524 self.errors = errors525 self.lazy = lazy526 self.atomic = atomic527528 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_dict532533 def resolve_lazy_flag(self, value):534 if self.lazy is not None:535 return self.lazy536 if value == "-":
101 unmodified lines
638 else:639 self.name = "path"640 self.path_type = "Path"641642 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_dict653654 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 lines
723724 def __init__(self, types):725 self.types = [convert_type(ty) for ty in types]726727 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_dict731732 @property733 def name(self):734 return f"<{' '.join(ty.name for ty in self.types)}>"735
87 unmodified lines
added:tests/test_info_dict.py+257 added
1import pytest23import click.types45# Common (obj, expect) pairs used to construct multiple tests.6STRING_PARAM_TYPE = (click.STRING, {"param_type": "String", "name": "text"})7INT_PARAM_TYPE = (click.INT, {"param_type": "Int", "name": "integer"})8BOOL_PARAM_TYPE = (click.BOOL, {"param_type": "Bool", "name": "boolean"})9HELP_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)30NAME_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)45NUMBER_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)66HELLO_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)78HELLO_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)929394@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)211def test_parameter(obj, expect):212 """Test to_info_dict for types and parameters."""213 out = obj.to_info_dict()214 assert out == expect215216217@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)253def 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