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.

182 lines
5.2 KiB

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