summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Estabrook <jestabro@vyos.io>2023-03-03 11:29:26 -0600
committerJohn Estabrook <jestabro@vyos.io>2023-03-05 14:15:17 -0600
commit0259f194598aac79e8d96dcaab5972759213b463 (patch)
tree5c1de70d250a7aa00a933e09a568e0b279a8263f
parent493af3f3417cef5c9898f242a2b885e63e3bdeef (diff)
downloadvyos-1x-0259f194598aac79e8d96dcaab5972759213b463.tar.gz
vyos-1x-0259f194598aac79e8d96dcaab5972759213b463.zip
op-mode: T5051: add support for Literal arg types
-rw-r--r--python/vyos/opmode.py35
1 files changed, 33 insertions, 2 deletions
diff --git a/python/vyos/opmode.py b/python/vyos/opmode.py
index d02ad4de6..d7172a0b5 100644
--- a/python/vyos/opmode.py
+++ b/python/vyos/opmode.py
@@ -128,6 +128,25 @@ def _get_arg_type(t):
else:
return t
+def _is_literal_type(t):
+ if _is_optional_type(t):
+ t = _get_arg_type(t)
+
+ if typing.get_origin(t) == typing.Literal:
+ return True
+
+ return False
+
+def _get_literal_values(t):
+ """ Returns the tuple of allowed values for a Literal type
+ """
+ if not _is_literal_type(t):
+ return tuple()
+ if _is_optional_type(t):
+ t = _get_arg_type(t)
+
+ return typing.get_args(t)
+
def _normalize_field_name(name):
# Convert the name to string if it is not
# (in some cases they may be numbers)
@@ -194,9 +213,21 @@ def run(module):
subparser.add_argument(f"--{opt}", action='store_true')
else:
if _is_optional_type(th):
- subparser.add_argument(f"--{opt}", type=_get_arg_type(th), default=None)
+ if _is_literal_type(th):
+ subparser.add_argument(f"--{opt}",
+ choices=list(_get_literal_values(th)),
+ default=None)
+ else:
+ subparser.add_argument(f"--{opt}",
+ type=_get_arg_type(th), default=None)
else:
- subparser.add_argument(f"--{opt}", type=_get_arg_type(th), required=True)
+ if _is_literal_type(th):
+ subparser.add_argument(f"--{opt}",
+ choices=list(_get_literal_values(th)),
+ required=True)
+ else:
+ subparser.add_argument(f"--{opt}",
+ type=_get_arg_type(th), required=True)
# Get options as a dict rather than a namespace,
# so that we can modify it and pack for passing to functions