]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
pybind/mgr/mgr_module: cast string to enum when collecting kwargs
authorKefu Chai <kchai@redhat.com>
Sun, 27 Dec 2020 14:42:33 +0000 (22:42 +0800)
committerKefu Chai <kchai@redhat.com>
Fri, 15 Jan 2021 01:50:53 +0000 (09:50 +0800)
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 <kchai@redhat.com>
src/pybind/ceph_argparse.py
src/pybind/mgr/mgr_module.py

index ccbd4f1e8ff03e99873d0b5d92c89096398a1c33..0b63731815c726c1302c1dc82ea1ce66af0fb167 100644 (file)
@@ -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):
     """
index 08b59f5025e892525d1814514ce36d4516b77181..b57efed0588812f78a6c062da219d20fb9d40077 100644 (file)
@@ -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):