2021-08-03 18:54:36 +00:00
|
|
|
__all__ = ['EnumAction']
|
|
|
|
__author__ = "Jeremy Saklad"
|
|
|
|
|
2021-08-14 18:05:17 +00:00
|
|
|
import argparse
|
2021-08-03 18:54:36 +00:00
|
|
|
|
2021-08-14 18:05:17 +00:00
|
|
|
class EnumAction(argparse.Action):
|
2021-08-03 18:54:36 +00:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
# Pop off the type value
|
|
|
|
enum = kwargs.pop('type', None)
|
|
|
|
|
2021-08-13 13:27:23 +00:00
|
|
|
nargs = kwargs.get('nargs')
|
2021-08-03 18:54:36 +00:00
|
|
|
|
|
|
|
# Generate choices from the Enum
|
|
|
|
kwargs.setdefault('choices', tuple(member.name.lower() for member in enum))
|
|
|
|
|
|
|
|
super(EnumAction, self).__init__(**kwargs)
|
|
|
|
|
|
|
|
self._enum = enum
|
|
|
|
self._nargs = nargs
|
|
|
|
|
|
|
|
def __call__(self, parser, namespace, values, option_string=None):
|
2021-08-14 18:05:17 +00:00
|
|
|
# Check whether this is a single value or a list of them
|
|
|
|
if self._nargs is None or self._nargs == argparse.OPTIONAL:
|
2021-08-13 13:27:23 +00:00
|
|
|
# Convert value back into an Enum
|
|
|
|
enum = self._enum[values.upper()]
|
|
|
|
|
2021-08-03 18:54:36 +00:00
|
|
|
setattr(namespace, self.dest, enum)
|
|
|
|
else:
|
2021-08-13 13:27:23 +00:00
|
|
|
# Convert values back into Enums
|
|
|
|
enums = [self._enum[value.upper()] for value in values]
|
|
|
|
|
|
|
|
items = getattr(namespace, self.dest, list()) + enums
|
2021-08-03 18:54:36 +00:00
|
|
|
setattr(namespace, self.dest, items)
|