From 4902d7c5452181c96b1f3382235416181d80757a Mon Sep 17 00:00:00 2001 From: Kefu Chai Date: Sun, 27 Dec 2020 22:42:33 +0800 Subject: [PATCH] pybind/mgr/mgr_module: cast string to enum when collecting kwargs as the parameters of handlers are properly typed, they are expecting enum parameter, let's cast string parameter to enum if the callee claims that it wants an enum. Signed-off-by: Kefu Chai --- src/pybind/ceph_argparse.py | 30 ++++++++++++++++++++++++++++++ src/pybind/mgr/mgr_module.py | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/pybind/ceph_argparse.py b/src/pybind/ceph_argparse.py index ccbd4f1e8ff..0b63731815c 100644 --- a/src/pybind/ceph_argparse.py +++ b/src/pybind/ceph_argparse.py @@ -214,6 +214,36 @@ class CephArgtype(object): attrs['type'] = type(self).__name__ return ','.join(f'{k}={v}' for k, v in attrs.items()) + @staticmethod + def _cast_to_compound_type(tp, v): + orig_type = get_origin(tp) + type_args = get_args(tp) + if orig_type in (abc.Sequence, Sequence, List, list): + return [CephArgtype.cast_to(type_args[0], e) for e in v] + elif orig_type is Tuple: + return tuple(CephArgtype.cast_to(type_args[0], e) for e in v) + elif get_origin(tp) is Union: + # should be Union[t, NoneType] + assert len(type_args) == 2 and isinstance(None, type_args[1]) + return CephArgtype.cast_to(type_args[0], v) + else: + raise ValueError(f"unknown type '{tp}': '{v}'") + + @staticmethod + def cast_to(tp, v): + PYTHON_TYPES = ( + str, + int, + float, + bool + ) + if tp in PYTHON_TYPES: + return tp(v) + elif isinstance(tp, type) and issubclass(tp, enum.Enum): + return tp(v) + else: + return CephArgtype._cast_to_compound_type(tp, v) + class CephInt(CephArgtype): """ diff --git a/src/pybind/mgr/mgr_module.py b/src/pybind/mgr/mgr_module.py index 08b59f5025e..b57efed0588 100644 --- a/src/pybind/mgr/mgr_module.py +++ b/src/pybind/mgr/mgr_module.py @@ -369,7 +369,7 @@ class CLICommand(object): continue kwargs_switch, k, v = self._get_arg_value(kwargs_switch, name, raw_v) - kwargs[k] = v + kwargs[k] = CephArgtype.cast_to(tp, v) return kwargs def call(self, mgr, cmd_dict, inbuf): -- 2.39.5