You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.5 KiB

  1. from argparse import ArgumentParser, _SubParsersAction
  2. class GooeySubParser(_SubParsersAction):
  3. def __init__(self, *args, **kwargs):
  4. super(GooeySubParser, self).__init__(*args, **kwargs)
  5. class GooeyParser(object):
  6. def __init__(self, **kwargs):
  7. self.__dict__['parser'] = ArgumentParser(**kwargs)
  8. self.widgets = {}
  9. @property
  10. def _mutually_exclusive_groups(self):
  11. return self.parser._mutually_exclusive_groups
  12. @property
  13. def _actions(self):
  14. return self.parser._actions
  15. @property
  16. def description(self):
  17. return self.parser.description
  18. def add_argument(self, *args, **kwargs):
  19. widget = kwargs.pop('widget', None)
  20. self.parser.add_argument(*args, **kwargs)
  21. self.widgets[self.parser._actions[-1].dest] = widget
  22. def add_mutually_exclusive_group(self, **kwargs):
  23. return self.parser.add_mutually_exclusive_group(**kwargs)
  24. def add_argument_group(self, *args, **kwargs):
  25. return self.parser.add_argument_group(*args, **kwargs)
  26. def parse_args(self, args=None, namespace=None):
  27. return self.parser.parse_args(args, namespace)
  28. def add_subparsers(self, **kwargs):
  29. if self._subparsers is not None:
  30. self.error(_('cannot have multiple subparser arguments'))
  31. # add the parser class to the arguments if it's not present
  32. kwargs.setdefault('parser_class', type(self))
  33. if 'title' in kwargs or 'description' in kwargs:
  34. title = _(kwargs.pop('title', 'subcommands'))
  35. description = _(kwargs.pop('description', None))
  36. self._subparsers = self.add_argument_group(title, description)
  37. else:
  38. self._subparsers = self._positionals
  39. # prog defaults to the usage message of this parser, skipping
  40. # optional arguments and with no "usage:" prefix
  41. if kwargs.get('prog') is None:
  42. formatter = self._get_formatter()
  43. positionals = self._get_positional_actions()
  44. groups = self._mutually_exclusive_groups
  45. formatter.add_usage(self.usage, positionals, groups, '')
  46. kwargs['prog'] = formatter.format_help().strip()
  47. # create the parsers action and add it to the positionals list
  48. parsers_class = self._pop_action_class(kwargs, 'parsers')
  49. action = parsers_class(option_strings=[], **kwargs)
  50. self._subparsers._add_action(action)
  51. # return the created parsers action
  52. return action
  53. def __getattr__(self, item):
  54. return getattr(self.parser, item)
  55. def __setattr__(self, key, value):
  56. return setattr(self.parser, key, value)