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.

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