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.

491 lines
16 KiB

  1. """
  2. Converts argparse parser actions into json "Build Specs"
  3. """
  4. import argparse
  5. import json
  6. import os
  7. import sys
  8. from argparse import (
  9. _CountAction,
  10. _HelpAction,
  11. _StoreConstAction,
  12. _StoreFalseAction,
  13. _StoreTrueAction,
  14. _SubParsersAction)
  15. from collections import OrderedDict
  16. from functools import partial
  17. from uuid import uuid4
  18. from gooey.python_bindings.gooey_parser import GooeyParser
  19. from gooey.util.functional import merge, getin, identity, assoc
  20. VALID_WIDGETS = (
  21. 'FileChooser',
  22. 'MultiFileChooser',
  23. 'FileSaver',
  24. 'DirChooser',
  25. 'DateChooser',
  26. 'TextField',
  27. 'Dropdown',
  28. 'Counter',
  29. 'RadioGroup',
  30. 'CheckBox',
  31. 'BlockCheckbox',
  32. 'MultiDirChooser',
  33. 'Textarea',
  34. 'PasswordField',
  35. 'Listbox'
  36. )
  37. class UnknownWidgetType(Exception):
  38. pass
  39. class UnsupportedConfiguration(Exception):
  40. pass
  41. # TODO: merge the default foreground and bg colors from the
  42. # baseline build_spec
  43. item_default = {
  44. 'error_color': '#ea7878',
  45. 'label_color': '#000000',
  46. 'help_color': '#363636',
  47. 'full_width': False,
  48. 'validator': {
  49. 'type': 'local',
  50. 'test': 'lambda x: True',
  51. 'message': ''
  52. },
  53. 'external_validator': {
  54. 'cmd': '',
  55. }
  56. }
  57. def convert(parser, **kwargs):
  58. """
  59. Converts a parser into a JSON representation
  60. This is in desperate need of refactor. It wasn't build with supporting
  61. all (or any) of this configuration in mind. The use of global defaults
  62. are actively getting in the way of easily adding more configuration options.
  63. """
  64. group_defaults = {
  65. 'legacy': {
  66. 'required_cols': kwargs['num_required_cols'],
  67. 'optional_cols': kwargs['num_optional_cols']
  68. },
  69. 'columns': 2,
  70. 'padding': 10,
  71. 'show_border': False
  72. }
  73. assert_subparser_constraints(parser)
  74. x = {
  75. 'layout': 'standard',
  76. 'widgets': OrderedDict(
  77. (choose_name(name, sub_parser), {
  78. 'command': name,
  79. 'name': choose_name(name, sub_parser),
  80. 'help': get_subparser_help(sub_parser),
  81. 'description': '',
  82. 'contents': process(sub_parser,
  83. getattr(sub_parser, 'widgets', {}),
  84. getattr(sub_parser, 'options', {}),
  85. group_defaults)
  86. }) for name, sub_parser in iter_parsers(parser))
  87. }
  88. if kwargs.get('use_legacy_titles'):
  89. return apply_default_rewrites(x)
  90. return x
  91. def process(parser, widget_dict, options, group_defaults):
  92. mutex_groups = parser._mutually_exclusive_groups
  93. raw_action_groups = [extract_groups(group, group_defaults) for group in parser._action_groups
  94. if group._group_actions]
  95. corrected_action_groups = reapply_mutex_groups(mutex_groups, raw_action_groups)
  96. return categorize2(strip_empty(corrected_action_groups), widget_dict, options)
  97. def strip_empty(groups):
  98. return [group for group in groups if group['items']]
  99. def assert_subparser_constraints(parser):
  100. if has_subparsers(parser._actions):
  101. if has_required(parser._actions):
  102. raise UnsupportedConfiguration(
  103. "Gooey doesn't currently support top level required arguments "
  104. "when subparsers are present.")
  105. def iter_parsers(parser):
  106. ''' Iterate over name, parser pairs '''
  107. try:
  108. return get_subparser(parser._actions).choices.items()
  109. except:
  110. return iter([('::gooey/default', parser)])
  111. def get_subparser_help(parser):
  112. if isinstance(parser, GooeyParser):
  113. return getattr(parser.parser, 'usage', '')
  114. else:
  115. return getattr(parser, 'usage', '')
  116. def extract_groups(action_group, group_defaults):
  117. '''
  118. Recursively extract argument groups and associated actions
  119. from ParserGroup objects
  120. '''
  121. return {
  122. 'name': action_group.title,
  123. 'description': action_group.description,
  124. 'items': [action for action in action_group._group_actions
  125. if not is_help_message(action)],
  126. 'groups': [extract_groups(group, group_defaults)
  127. for group in action_group._action_groups],
  128. 'options': handle_option_merge(
  129. group_defaults,
  130. getattr(action_group, 'gooey_options', {}),
  131. action_group.title)
  132. }
  133. def handle_option_merge(group_defaults, incoming_options, title):
  134. """
  135. Merges a set of group defaults with incoming options.
  136. A bunch of ceremony here is to ensure backwards compatibility with the old
  137. num_required_cols and num_optional_cols decorator args. They are used as
  138. the seed values for the new group defaults which keeps the old behavior
  139. _mostly_ in tact.
  140. Known failure points:
  141. * Using custom groups / names. No 'positional arguments' group
  142. means no required_cols arg being honored
  143. * Non-positional args marked as required. It would take group
  144. shuffling along the lines of that required to make
  145. mutually exclusive groups show in the correct place. In short, not
  146. worth the complexity for a legacy feature that's been succeeded by
  147. a much more powerful alternative.
  148. """
  149. if title == 'positional arguments':
  150. # the argparse default 'required' bucket
  151. req_cols = getin(group_defaults, ['legacy', 'required_cols'], 2)
  152. new_defaults = assoc(group_defaults, 'columns', req_cols)
  153. return merge(new_defaults, incoming_options)
  154. else:
  155. opt_cols = getin(group_defaults, ['legacy', 'optional_cols'], 2)
  156. new_defaults = assoc(group_defaults, 'columns', opt_cols)
  157. return merge(new_defaults, incoming_options)
  158. def apply_default_rewrites(spec):
  159. top_level_subgroups = list(spec['widgets'].keys())
  160. for subgroup in top_level_subgroups:
  161. path = ['widgets', subgroup, 'contents']
  162. contents = getin(spec, path)
  163. for group in contents:
  164. if group['name'] == 'positional arguments':
  165. group['name'] = 'Required Arguments'
  166. if group['name'] == 'optional arguments':
  167. group['name'] = 'Optional Arguments'
  168. return spec
  169. def contains_actions(a, b):
  170. ''' check if any actions(a) are present in actions(b) '''
  171. return set(a).intersection(set(b))
  172. def reapply_mutex_groups(mutex_groups, action_groups):
  173. # argparse stores mutually exclusive groups independently
  174. # of all other groups. So, they must be manually re-combined
  175. # with the groups/subgroups to which they were originally declared
  176. # in order to have them appear in the correct location in the UI.
  177. #
  178. # Order is attempted to be preserved by inserting the MutexGroup
  179. # into the _actions list at the first occurrence of any item
  180. # where the two groups intersect
  181. def swap_actions(actions):
  182. for mutexgroup in mutex_groups:
  183. mutex_actions = mutexgroup._group_actions
  184. if contains_actions(mutex_actions, actions):
  185. # make a best guess as to where we should store the group
  186. targetindex = actions.index(mutexgroup._group_actions[0])
  187. # insert the _ArgumentGroup container
  188. actions[targetindex] = mutexgroup
  189. # remove the duplicated individual actions
  190. return [action for action in actions
  191. if action not in mutex_actions]
  192. return actions
  193. return [group.update({'items': swap_actions(group['items'])}) or group
  194. for group in action_groups]
  195. def categorize2(groups, widget_dict, options):
  196. defaults = {'label_color': '#000000', 'description_color': '#363636'}
  197. return [{
  198. 'name': group['name'],
  199. 'items': list(categorize(group['items'], widget_dict, options)),
  200. 'groups': categorize2(group['groups'], widget_dict, options),
  201. 'description': group['description'],
  202. 'options': merge(defaults ,group['options'])
  203. } for group in groups]
  204. def categorize(actions, widget_dict, options):
  205. _get_widget = partial(get_widget, widget_dict)
  206. for action in actions:
  207. if is_mutex(action):
  208. yield build_radio_group(action, widget_dict, options)
  209. elif is_standard(action):
  210. yield action_to_json(action, _get_widget(action, 'TextField'), options)
  211. elif is_file(action):
  212. yield action_to_json(action, _get_widget(action, 'FileSaver'), options)
  213. elif is_choice(action):
  214. yield action_to_json(action, _get_widget(action, 'Dropdown'), options)
  215. elif is_flag(action):
  216. yield action_to_json(action, _get_widget(action, 'CheckBox'), options)
  217. elif is_counter(action):
  218. _json = action_to_json(action, _get_widget(action, 'Counter'), options)
  219. # pre-fill the 'counter' dropdown
  220. _json['data']['choices'] = list(map(str, range(1, 11)))
  221. yield _json
  222. else:
  223. raise UnknownWidgetType(action)
  224. def get_widget(widgets, action, default):
  225. supplied_widget = widgets.get(action.dest, None)
  226. return supplied_widget or type_arg_widget or default
  227. def is_required(action):
  228. '''
  229. _actions possessing the `required` flag and not implicitly optional
  230. through `nargs` being '*' or '?'
  231. '''
  232. return not isinstance(action, _SubParsersAction) and (
  233. action.required == True and action.nargs not in ['*', '?'])
  234. def is_mutex(action):
  235. return isinstance(action, argparse._MutuallyExclusiveGroup)
  236. def has_required(actions):
  237. return list(filter(None, list(filter(is_required, actions))))
  238. def is_subparser(action):
  239. return isinstance(action, _SubParsersAction)
  240. def has_subparsers(actions):
  241. return list(filter(is_subparser, actions))
  242. def get_subparser(actions):
  243. return list(filter(is_subparser, actions))[0]
  244. def is_optional(action):
  245. '''
  246. _actions either not possessing the `required` flag or implicitly optional
  247. through `nargs` being '*' or '?'
  248. '''
  249. return (not action.required) or action.nargs in ['*', '?']
  250. def is_choice(action):
  251. ''' action with choices supplied '''
  252. return action.choices
  253. def is_file(action):
  254. ''' action with FileType '''
  255. return isinstance(action.type, argparse.FileType)
  256. def is_standard(action):
  257. """ actions which are general "store" instructions.
  258. e.g. anything which has an argument style like:
  259. $ script.py -f myfilename.txt
  260. """
  261. boolean_actions = (
  262. _StoreConstAction, _StoreFalseAction,
  263. _StoreTrueAction
  264. )
  265. return (not action.choices
  266. and not isinstance(action.type, argparse.FileType)
  267. and not isinstance(action, _CountAction)
  268. and not isinstance(action, _HelpAction)
  269. and type(action) not in boolean_actions)
  270. def is_flag(action):
  271. """ _actions which are either storeconst, store_bool, etc.. """
  272. action_types = [_StoreTrueAction, _StoreFalseAction, _StoreConstAction]
  273. return any(list(map(lambda Action: isinstance(action, Action), action_types)))
  274. def is_counter(action):
  275. """ _actions which are of type _CountAction """
  276. return isinstance(action, _CountAction)
  277. def is_default_progname(name, subparser):
  278. return subparser.prog == '{} {}'.format(os.path.split(sys.argv[0])[-1], name)
  279. def is_help_message(action):
  280. return isinstance(action, _HelpAction)
  281. def choose_name(name, subparser):
  282. return name if is_default_progname(name, subparser) else subparser.prog
  283. def build_radio_group(mutex_group, widget_group, options):
  284. return {
  285. 'id': str(uuid4()),
  286. 'type': 'RadioGroup',
  287. 'cli_type': 'optional',
  288. 'group_name': 'Choose Option',
  289. 'required': mutex_group.required,
  290. 'options': merge(item_default, getattr(mutex_group, 'gooey_options', {})),
  291. 'data': {
  292. 'commands': [action.option_strings for action in mutex_group._group_actions],
  293. 'widgets': list(categorize(mutex_group._group_actions, widget_group, options))
  294. }
  295. }
  296. def action_to_json(action, widget, options):
  297. dropdown_types = {'Listbox', 'Dropdown', 'Counter'}
  298. if action.required:
  299. # Text fields get a default check that user input is present
  300. # and not just spaces, dropdown types get a simplified
  301. # is-it-present style check
  302. validator = ('user_input and not user_input.isspace()'
  303. if widget not in dropdown_types
  304. else 'user_input')
  305. error_msg = 'This field is required'
  306. else:
  307. # not required; do nothing;
  308. validator = 'True'
  309. error_msg = ''
  310. base = merge(item_default, {
  311. 'validator': {
  312. 'test': validator,
  313. 'message': error_msg
  314. },
  315. })
  316. default = coerce_default(action.default, widget)
  317. return {
  318. 'id': action.option_strings[0] if action.option_strings else action.dest,
  319. 'type': widget,
  320. 'cli_type': choose_cli_type(action),
  321. 'required': action.required,
  322. 'data': {
  323. 'display_name': action.metavar or action.dest,
  324. 'help': action.help,
  325. 'required': action.required,
  326. 'nargs': action.nargs or '',
  327. 'commands': action.option_strings,
  328. 'choices': list(map(str, action.choices)) if action.choices else [],
  329. 'default': default,
  330. 'dest': action.dest,
  331. },
  332. 'options': merge(base, options.get(action.dest) or {})
  333. }
  334. def choose_cli_type(action):
  335. return 'positional' \
  336. if action.required and not action.option_strings \
  337. else 'optional'
  338. def coerce_default(default, widget):
  339. """coerce a default value to the best appropriate type for
  340. ingestion into wx"""
  341. dispatcher = {
  342. 'Listbox': clean_list_defaults,
  343. 'Dropdown': safe_string,
  344. 'Counter': safe_string
  345. }
  346. # Issue #321:
  347. # Defaults for choice types must be coerced to strings
  348. # to be able to match the stringified `choices` used by `wx.ComboBox`
  349. cleaned = clean_default(default)
  350. # dispatch to the appropriate cleaning function, or return the value
  351. # as is if no special handler is present
  352. return dispatcher.get(widget, identity)(cleaned)
  353. def clean_list_defaults(default_values):
  354. """
  355. Listbox's default's can be passed as a single value
  356. or a list of values (due to multiple selections). The list interface
  357. is standardized on for ease.
  358. """
  359. wrapped_values = ([default_values]
  360. if isinstance(default_values, str)
  361. else default_values)
  362. return [safe_string(value) for value in wrapped_values]
  363. def clean_default(default):
  364. """
  365. Attemps to safely coalesce the default value down to
  366. a valid JSON type.
  367. """
  368. try:
  369. json.dumps(default)
  370. return default
  371. except TypeError as e:
  372. # see: Issue #377
  373. # if is ins't json serializable (i.e. primitive data) there's nothing
  374. # useful for Gooey to do with it (since Gooey deals in primitive data
  375. # types). So the correct behavior is dropping them. This affects ONLY
  376. # gooey, not the client code.
  377. return None
  378. def safe_string(value):
  379. """
  380. Coerce a type to string as long as it isn't None
  381. """
  382. if value is None or isinstance(value, bool):
  383. return value
  384. else:
  385. return str(value)