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.

245 lines
7.1 KiB

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