argparse_oe.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. #
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. import sys
  5. import argparse
  6. from collections import defaultdict, OrderedDict
  7. class ArgumentUsageError(Exception):
  8. """Exception class you can raise (and catch) in order to show the help"""
  9. def __init__(self, message, subcommand=None):
  10. self.message = message
  11. self.subcommand = subcommand
  12. class ArgumentParser(argparse.ArgumentParser):
  13. """Our own version of argparse's ArgumentParser"""
  14. def __init__(self, *args, **kwargs):
  15. kwargs.setdefault('formatter_class', OeHelpFormatter)
  16. self._subparser_groups = OrderedDict()
  17. super(ArgumentParser, self).__init__(*args, **kwargs)
  18. self._positionals.title = 'arguments'
  19. self._optionals.title = 'options'
  20. def error(self, message):
  21. """error(message: string)
  22. Prints a help message incorporating the message to stderr and
  23. exits.
  24. """
  25. self._print_message('%s: error: %s\n' % (self.prog, message), sys.stderr)
  26. self.print_help(sys.stderr)
  27. sys.exit(2)
  28. def error_subcommand(self, message, subcommand):
  29. if subcommand:
  30. action = self._get_subparser_action()
  31. try:
  32. subparser = action._name_parser_map[subcommand]
  33. except KeyError:
  34. self.error('no subparser for name "%s"' % subcommand)
  35. else:
  36. subparser.error(message)
  37. self.error(message)
  38. def add_subparsers(self, *args, **kwargs):
  39. if 'dest' not in kwargs:
  40. kwargs['dest'] = '_subparser_name'
  41. ret = super(ArgumentParser, self).add_subparsers(*args, **kwargs)
  42. # Need a way of accessing the parent parser
  43. ret._parent_parser = self
  44. # Ensure our class gets instantiated
  45. ret._parser_class = ArgumentSubParser
  46. # Hacky way of adding a method to the subparsers object
  47. ret.add_subparser_group = self.add_subparser_group
  48. return ret
  49. def add_subparser_group(self, groupname, groupdesc, order=0):
  50. self._subparser_groups[groupname] = (groupdesc, order)
  51. def parse_args(self, args=None, namespace=None):
  52. """Parse arguments, using the correct subparser to show the error."""
  53. args, argv = self.parse_known_args(args, namespace)
  54. if argv:
  55. message = 'unrecognized arguments: %s' % ' '.join(argv)
  56. if self._subparsers:
  57. subparser = self._get_subparser(args)
  58. subparser.error(message)
  59. else:
  60. self.error(message)
  61. sys.exit(2)
  62. return args
  63. def _get_subparser(self, args):
  64. action = self._get_subparser_action()
  65. if action.dest == argparse.SUPPRESS:
  66. self.error('cannot get subparser, the subparser action dest is suppressed')
  67. name = getattr(args, action.dest)
  68. try:
  69. return action._name_parser_map[name]
  70. except KeyError:
  71. self.error('no subparser for name "%s"' % name)
  72. def _get_subparser_action(self):
  73. if not self._subparsers:
  74. self.error('cannot return the subparser action, no subparsers added')
  75. for action in self._subparsers._group_actions:
  76. if isinstance(action, argparse._SubParsersAction):
  77. return action
  78. class ArgumentSubParser(ArgumentParser):
  79. def __init__(self, *args, **kwargs):
  80. if 'group' in kwargs:
  81. self._group = kwargs.pop('group')
  82. if 'order' in kwargs:
  83. self._order = kwargs.pop('order')
  84. super(ArgumentSubParser, self).__init__(*args, **kwargs)
  85. def parse_known_args(self, args=None, namespace=None):
  86. # This works around argparse not handling optional positional arguments being
  87. # intermixed with other options. A pretty horrible hack, but we're not left
  88. # with much choice given that the bug in argparse exists and it's difficult
  89. # to subclass.
  90. # Borrowed from http://stackoverflow.com/questions/20165843/argparse-how-to-handle-variable-number-of-arguments-nargs
  91. # with an extra workaround (in format_help() below) for the positional
  92. # arguments disappearing from the --help output, as well as structural tweaks.
  93. # Originally simplified from http://bugs.python.org/file30204/test_intermixed.py
  94. positionals = self._get_positional_actions()
  95. for action in positionals:
  96. # deactivate positionals
  97. action.save_nargs = action.nargs
  98. action.nargs = 0
  99. namespace, remaining_args = super(ArgumentSubParser, self).parse_known_args(args, namespace)
  100. for action in positionals:
  101. # remove the empty positional values from namespace
  102. if hasattr(namespace, action.dest):
  103. delattr(namespace, action.dest)
  104. for action in positionals:
  105. action.nargs = action.save_nargs
  106. # parse positionals
  107. namespace, extras = super(ArgumentSubParser, self).parse_known_args(remaining_args, namespace)
  108. return namespace, extras
  109. def format_help(self):
  110. # Quick, restore the positionals!
  111. positionals = self._get_positional_actions()
  112. for action in positionals:
  113. if hasattr(action, 'save_nargs'):
  114. action.nargs = action.save_nargs
  115. return super(ArgumentParser, self).format_help()
  116. class OeHelpFormatter(argparse.HelpFormatter):
  117. def _format_action(self, action):
  118. if hasattr(action, '_get_subactions'):
  119. # subcommands list
  120. groupmap = defaultdict(list)
  121. ordermap = {}
  122. subparser_groups = action._parent_parser._subparser_groups
  123. groups = sorted(subparser_groups.keys(), key=lambda item: subparser_groups[item][1], reverse=True)
  124. for subaction in self._iter_indented_subactions(action):
  125. parser = action._name_parser_map[subaction.dest]
  126. group = getattr(parser, '_group', None)
  127. groupmap[group].append(subaction)
  128. if group not in groups:
  129. groups.append(group)
  130. order = getattr(parser, '_order', 0)
  131. ordermap[subaction.dest] = order
  132. lines = []
  133. if len(groupmap) > 1:
  134. groupindent = ' '
  135. else:
  136. groupindent = ''
  137. for group in groups:
  138. subactions = groupmap[group]
  139. if not subactions:
  140. continue
  141. if groupindent:
  142. if not group:
  143. group = 'other'
  144. groupdesc = subparser_groups.get(group, (group, 0))[0]
  145. lines.append(' %s:' % groupdesc)
  146. for subaction in sorted(subactions, key=lambda item: ordermap[item.dest], reverse=True):
  147. lines.append('%s%s' % (groupindent, self._format_action(subaction).rstrip()))
  148. return '\n'.join(lines)
  149. else:
  150. return super(OeHelpFormatter, self)._format_action(action)
  151. def int_positive(value):
  152. ivalue = int(value)
  153. if ivalue <= 0:
  154. raise argparse.ArgumentTypeError(
  155. "%s is not a positive int value" % value)
  156. return ivalue