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.

215 lines
6.0 KiB

  1. """
  2. Converts argparse parser actions into json "Build Specs"
  3. """
  4. import argparse
  5. import os
  6. from argparse import (
  7. _CountAction,
  8. _HelpAction,
  9. _StoreConstAction,
  10. _StoreFalseAction,
  11. _StoreTrueAction,
  12. ArgumentParser,
  13. _SubParsersAction)
  14. from collections import OrderedDict
  15. from functools import partial
  16. from itertools import chain
  17. import sys
  18. VALID_WIDGETS = (
  19. 'FileChooser',
  20. 'MultiFileChooser',
  21. 'FileSaver',
  22. 'DirChooser',
  23. 'DateChooser',
  24. 'TextField',
  25. 'Dropdown',
  26. 'Counter',
  27. 'RadioGroup',
  28. 'CheckBox',
  29. 'MultiDirChooser'
  30. )
  31. class UnknownWidgetType(Exception):
  32. pass
  33. class UnsupportedConfiguration(Exception):
  34. pass
  35. {
  36. 'siege': {
  37. 'command': 'siege',
  38. 'display_name': 'Siege',
  39. 'contents': []
  40. }
  41. }
  42. def convert(parser):
  43. widget_dict = getattr(parser, 'widgets', {})
  44. actions = parser._actions
  45. if has_subparsers(actions):
  46. if has_required(actions):
  47. raise UnsupportedConfiguration("Gooey doesn't currently support required arguments when subparsers are present.")
  48. layout_type = 'column'
  49. layout_data = OrderedDict(
  50. (choose_name(name, sub_parser), {
  51. 'command': name.lower(),
  52. 'contents': process(sub_parser, getattr(sub_parser, 'widgets', {}))
  53. }) for name, sub_parser in get_subparser(actions).choices.iteritems())
  54. else:
  55. layout_type = 'standard'
  56. layout_data = OrderedDict([
  57. ('primary', {
  58. 'command': None,
  59. 'contents': process(parser, widget_dict)
  60. })
  61. ])
  62. return {
  63. 'layout_type': layout_type,
  64. 'widgets': layout_data
  65. }
  66. def process(parser, widget_dict):
  67. mutually_exclusive_groups = [
  68. [mutex_action for mutex_action in group_actions._group_actions]
  69. for group_actions in parser._mutually_exclusive_groups]
  70. group_options = list(chain(*mutually_exclusive_groups))
  71. base_actions = [action for action in parser._actions
  72. if action not in group_options
  73. and action.dest != 'help']
  74. required_actions = filter(is_required, base_actions)
  75. optional_actions = filter(is_optional, base_actions)
  76. return list(categorize(required_actions, widget_dict, required=True)) + \
  77. list(categorize(optional_actions, widget_dict)) + \
  78. map(build_radio_group, mutually_exclusive_groups)
  79. def categorize(actions, widget_dict, required=False):
  80. _get_widget = partial(get_widget, widgets=widget_dict)
  81. for action in actions:
  82. if is_standard(action):
  83. yield as_json(action, _get_widget(action) or 'TextField', required)
  84. elif is_choice(action):
  85. yield as_json(action, _get_widget(action) or 'Dropdown', required)
  86. elif is_flag(action):
  87. yield as_json(action, _get_widget(action) or 'CheckBox', required)
  88. elif is_counter(action):
  89. _json = as_json(action, _get_widget(action) or 'Counter', required)
  90. # pre-fill the 'counter' dropdown
  91. _json['data']['choices'] = map(str, range(1, 11))
  92. yield _json
  93. else:
  94. raise UnknownWidgetType(action)
  95. def get_widget(action, widgets):
  96. supplied_widget = widgets.get(action.dest, None)
  97. type_arg_widget = 'FileChooser' if action.type == argparse.FileType else None
  98. return supplied_widget or type_arg_widget or None
  99. def is_required(action):
  100. '''_actions which are positional or possessing the `required` flag '''
  101. return not action.option_strings and not isinstance(action, _SubParsersAction) or action.required == True
  102. def has_required(actions):
  103. return filter(None, filter(is_required, actions))
  104. def is_subparser(action):
  105. return isinstance(action,_SubParsersAction)
  106. def has_subparsers(actions):
  107. return filter(is_subparser, actions)
  108. def get_subparser(actions):
  109. return filter(is_subparser, actions)[0]
  110. def is_optional(action):
  111. '''_actions not positional or possessing the `required` flag'''
  112. return action.option_strings and not action.required
  113. def is_choice(action):
  114. ''' action with choices supplied '''
  115. return action.choices
  116. def is_standard(action):
  117. """ actions which are general "store" instructions.
  118. e.g. anything which has an argument style like:
  119. $ script.py -f myfilename.txt
  120. """
  121. boolean_actions = (
  122. _StoreConstAction, _StoreFalseAction,
  123. _StoreTrueAction
  124. )
  125. return (not action.choices
  126. and not isinstance(action, _CountAction)
  127. and not isinstance(action, _HelpAction)
  128. and type(action) not in boolean_actions)
  129. def is_flag(action):
  130. """ _actions which are either storeconst, store_bool, etc.. """
  131. action_types = [_StoreTrueAction, _StoreFalseAction, _StoreConstAction]
  132. return any(map(lambda Action: isinstance(action, Action), action_types))
  133. def is_counter(action):
  134. """ _actions which are of type _CountAction """
  135. return isinstance(action, _CountAction)
  136. def is_default_progname(name, subparser):
  137. return subparser.prog == '{} {}'.format(os.path.split(sys.argv[0])[-1], name)
  138. def choose_name(name, subparser):
  139. return name if is_default_progname(name, subparser) else subparser.prog
  140. def build_radio_group(mutex_group):
  141. if not mutex_group:
  142. return []
  143. options = [
  144. {
  145. 'display_name': mutex_arg.metavar or mutex_arg.dest,
  146. 'help': mutex_arg.help,
  147. 'nargs': mutex_arg.nargs or '',
  148. 'commands': mutex_arg.option_strings,
  149. 'choices': mutex_arg.choices,
  150. } for mutex_arg in mutex_group
  151. ]
  152. return {
  153. 'type': 'RadioGroup',
  154. 'group_name': 'Choose Option',
  155. 'required': False,
  156. 'data': options
  157. }
  158. def as_json(action, widget, required):
  159. if widget not in VALID_WIDGETS:
  160. raise UnknownWidgetType('Widget Type {0} is unrecognized'.format(widget))
  161. return {
  162. 'type': widget,
  163. 'required': required,
  164. 'data': {
  165. 'display_name': action.metavar or action.dest,
  166. 'help': action.help,
  167. 'nargs': action.nargs or '',
  168. 'commands': action.option_strings,
  169. 'choices': action.choices or [],
  170. 'default': action.default
  171. }
  172. }