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.

653 lines
22 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. _StoreAction,
  15. _SubParsersAction)
  16. from collections import OrderedDict
  17. from functools import partial
  18. from uuid import uuid4
  19. from gooey.python_bindings.gooey_parser import GooeyParser
  20. from gooey.util.functional import merge, getin, identity, assoc
  21. from gooey.gui.components.options.validators import validators
  22. from gooey.gui.components.options.validators import collect_errors
  23. VALID_WIDGETS = (
  24. 'FileChooser',
  25. 'MultiFileChooser',
  26. 'FileSaver',
  27. 'DirChooser',
  28. 'DateChooser',
  29. 'TimeChooser',
  30. 'TextField',
  31. 'Dropdown',
  32. 'Counter',
  33. 'RadioGroup',
  34. 'CheckBox',
  35. 'BlockCheckbox',
  36. 'MultiDirChooser',
  37. 'Textarea',
  38. 'PasswordField',
  39. 'Listbox',
  40. 'FilterableDropdown',
  41. 'IntegerField',
  42. 'DecimalField',
  43. 'Slider'
  44. )
  45. # TODO: validate Listbox. When required, nargs must be +
  46. class UnknownWidgetType(Exception):
  47. pass
  48. class UnsupportedConfiguration(Exception):
  49. pass
  50. # TODO: merge the default foreground and bg colors from the
  51. # baseline build_spec
  52. item_default = {
  53. 'error_color': '#ea7878',
  54. 'label_color': '#000000',
  55. 'help_color': '#363636',
  56. 'full_width': False,
  57. 'validator': {
  58. 'type': 'local',
  59. 'test': 'lambda x: True',
  60. 'message': ''
  61. },
  62. 'external_validator': {
  63. 'cmd': '',
  64. }
  65. }
  66. def convert(parser, **kwargs):
  67. """
  68. Converts a parser into a JSON representation
  69. TODO:
  70. This is in desperate need of refactor. It wasn't build with supporting
  71. all (or any) of this configuration in mind. The use of global defaults
  72. are actively getting in the way of easily adding more configuration options.
  73. Pain points:
  74. - global data sprinkled throughout the calls
  75. - local data threaded through calls
  76. - totally unclear what the data structures even hold
  77. - everything is just mushed together and gross. unwinding argparse also
  78. builds validators, handles coercion, and so on...
  79. - converts to an entirely bespoke json mini-language that mirrors
  80. the internal structure of argparse.
  81. Refactor plan:
  82. - Investigate restructuring the core data representation. As is, it is ad-hoc
  83. and largely tied to argparse's goofy internal structure. May be worth moving to
  84. something "standard." Though, not sure what the options are.
  85. - standardize how these things read from the environment. No global in some local in others.
  86. - Investigate splitting the whole thing into phases (ala Ring). Current thinking is that
  87. a lot of this stuff could be modelled more like pluggable upgrades to the base structure.
  88. - I want to add a helpful validation stage to catch user errors like invalid gooey_options
  89. """
  90. group_defaults = {
  91. 'legacy': {
  92. 'required_cols': kwargs['num_required_cols'],
  93. 'optional_cols': kwargs['num_optional_cols']
  94. },
  95. 'columns': 2,
  96. 'padding': 10,
  97. 'show_border': False
  98. }
  99. assert_subparser_constraints(parser)
  100. x = {
  101. 'layout': 'standard',
  102. 'widgets': OrderedDict(
  103. (choose_name(name, sub_parser), {
  104. 'command': name,
  105. 'name': choose_name(name, sub_parser),
  106. 'help': get_subparser_help(sub_parser),
  107. 'description': '',
  108. 'contents': process(sub_parser,
  109. getattr(sub_parser, 'widgets', {}),
  110. getattr(sub_parser, 'options', {}),
  111. group_defaults)
  112. }) for name, sub_parser in iter_parsers(parser))
  113. }
  114. if kwargs.get('use_legacy_titles'):
  115. return apply_default_rewrites(x)
  116. return x
  117. def process(parser, widget_dict, options, group_defaults):
  118. mutex_groups = parser._mutually_exclusive_groups
  119. raw_action_groups = [extract_groups(group, group_defaults) for group in parser._action_groups
  120. if group._group_actions]
  121. corrected_action_groups = reapply_mutex_groups(mutex_groups, raw_action_groups)
  122. return categorize2(strip_empty(corrected_action_groups), widget_dict, options)
  123. def strip_empty(groups):
  124. return [group for group in groups if group['items']]
  125. def assert_subparser_constraints(parser):
  126. if has_subparsers(parser._actions):
  127. if has_required(parser._actions):
  128. raise UnsupportedConfiguration(
  129. "Gooey doesn't currently support top level required arguments "
  130. "when subparsers are present.")
  131. def iter_parsers(parser):
  132. ''' Iterate over name, parser pairs '''
  133. try:
  134. return get_subparser(parser._actions).choices.items()
  135. except:
  136. return iter([('::gooey/default', parser)])
  137. def get_subparser_help(parser):
  138. if isinstance(parser, GooeyParser):
  139. return getattr(parser.parser, 'usage', '')
  140. else:
  141. return getattr(parser, 'usage', '')
  142. def extract_groups(action_group, group_defaults):
  143. '''
  144. Recursively extract argument groups and associated actions
  145. from ParserGroup objects
  146. '''
  147. return {
  148. 'name': action_group.title,
  149. 'description': action_group.description,
  150. 'items': [action for action in action_group._group_actions
  151. if not is_help_message(action)],
  152. 'groups': [extract_groups(group, group_defaults)
  153. for group in action_group._action_groups],
  154. 'options': handle_option_merge(
  155. group_defaults,
  156. getattr(action_group, 'gooey_options', {}),
  157. action_group.title)
  158. }
  159. def handle_option_merge(group_defaults, incoming_options, title):
  160. """
  161. Merges a set of group defaults with incoming options.
  162. A bunch of ceremony here is to ensure backwards compatibility with the old
  163. num_required_cols and num_optional_cols decorator args. They are used as
  164. the seed values for the new group defaults which keeps the old behavior
  165. _mostly_ in tact.
  166. Known failure points:
  167. * Using custom groups / names. No 'positional arguments' group
  168. means no required_cols arg being honored
  169. * Non-positional args marked as required. It would take group
  170. shuffling along the lines of that required to make
  171. mutually exclusive groups show in the correct place. In short, not
  172. worth the complexity for a legacy feature that's been succeeded by
  173. a much more powerful alternative.
  174. """
  175. if title == 'positional arguments':
  176. # the argparse default 'required' bucket
  177. req_cols = getin(group_defaults, ['legacy', 'required_cols'], 2)
  178. new_defaults = assoc(group_defaults, 'columns', req_cols)
  179. return merge(new_defaults, incoming_options)
  180. else:
  181. opt_cols = getin(group_defaults, ['legacy', 'optional_cols'], 2)
  182. new_defaults = assoc(group_defaults, 'columns', opt_cols)
  183. return merge(new_defaults, incoming_options)
  184. def apply_default_rewrites(spec):
  185. top_level_subgroups = list(spec['widgets'].keys())
  186. for subgroup in top_level_subgroups:
  187. path = ['widgets', subgroup, 'contents']
  188. contents = getin(spec, path)
  189. for group in contents:
  190. if group['name'] == 'positional arguments':
  191. group['name'] = 'required_args_msg'
  192. if group['name'] == 'optional arguments':
  193. group['name'] = 'optional_args_msg'
  194. return spec
  195. def contains_actions(a, b):
  196. ''' check if any actions(a) are present in actions(b) '''
  197. return set(a).intersection(set(b))
  198. def reapply_mutex_groups(mutex_groups, action_groups):
  199. # argparse stores mutually exclusive groups independently
  200. # of all other groups. So, they must be manually re-combined
  201. # with the groups/subgroups to which they were originally declared
  202. # in order to have them appear in the correct location in the UI.
  203. #
  204. # Order is attempted to be preserved by inserting the MutexGroup
  205. # into the _actions list at the first occurrence of any item
  206. # where the two groups intersect
  207. def swap_actions(actions):
  208. for mutexgroup in mutex_groups:
  209. mutex_actions = mutexgroup._group_actions
  210. if contains_actions(mutex_actions, actions):
  211. # make a best guess as to where we should store the group
  212. targetindex = actions.index(mutexgroup._group_actions[0])
  213. # insert the _ArgumentGroup container
  214. actions[targetindex] = mutexgroup
  215. # remove the duplicated individual actions
  216. actions = [action for action in actions
  217. if action not in mutex_actions]
  218. return actions
  219. return [group.update({'items': swap_actions(group['items'])}) or group
  220. for group in action_groups]
  221. def categorize2(groups, widget_dict, options):
  222. defaults = {'label_color': '#000000', 'description_color': '#363636'}
  223. return [{
  224. 'name': group['name'],
  225. 'items': list(categorize(group['items'], widget_dict, options)),
  226. 'groups': categorize2(group['groups'], widget_dict, options),
  227. 'description': group['description'],
  228. 'options': merge(defaults ,group['options'])
  229. } for group in groups]
  230. def categorize(actions, widget_dict, options):
  231. _get_widget = partial(get_widget, widget_dict)
  232. for action in actions:
  233. if is_mutex(action):
  234. yield build_radio_group(action, widget_dict, options)
  235. elif is_standard(action):
  236. yield action_to_json(action, _get_widget(action, 'TextField'), options)
  237. elif is_file(action):
  238. yield action_to_json(action, _get_widget(action, 'FileSaver'), options)
  239. elif is_choice(action):
  240. yield action_to_json(action, _get_widget(action, 'Dropdown'), options)
  241. elif is_flag(action):
  242. yield action_to_json(action, _get_widget(action, 'CheckBox'), options)
  243. elif is_counter(action):
  244. _json = action_to_json(action, _get_widget(action, 'Counter'), options)
  245. # pre-fill the 'counter' dropdown
  246. _json['data']['choices'] = list(map(str, range(0, 11)))
  247. yield _json
  248. else:
  249. raise UnknownWidgetType(action)
  250. def get_widget(widgets, action, default):
  251. supplied_widget = widgets.get(action.dest, None)
  252. return supplied_widget or default
  253. def is_required(action):
  254. '''
  255. _actions possessing the `required` flag and not implicitly optional
  256. through `nargs` being '*' or '?'
  257. '''
  258. return not isinstance(action, _SubParsersAction) and (
  259. action.required == True and action.nargs not in ['*', '?'])
  260. def is_mutex(action):
  261. return isinstance(action, argparse._MutuallyExclusiveGroup)
  262. def has_required(actions):
  263. return list(filter(None, list(filter(is_required, actions))))
  264. def is_subparser(action):
  265. return isinstance(action, _SubParsersAction)
  266. def has_subparsers(actions):
  267. return list(filter(is_subparser, actions))
  268. def get_subparser(actions):
  269. return list(filter(is_subparser, actions))[0]
  270. def is_optional(action):
  271. '''
  272. _actions either not possessing the `required` flag or implicitly optional
  273. through `nargs` being '*' or '?'
  274. '''
  275. return (not action.required) or action.nargs in ['*', '?']
  276. def is_choice(action):
  277. ''' action with choices supplied '''
  278. return action.choices
  279. def is_file(action):
  280. ''' action with FileType '''
  281. return isinstance(action.type, argparse.FileType)
  282. def is_standard(action):
  283. """ actions which are general "store" instructions.
  284. e.g. anything which has an argument style like:
  285. $ script.py -f myfilename.txt
  286. """
  287. boolean_actions = (
  288. _StoreConstAction, _StoreFalseAction,
  289. _StoreTrueAction
  290. )
  291. return (not action.choices
  292. and not isinstance(action.type, argparse.FileType)
  293. and not isinstance(action, _CountAction)
  294. and not isinstance(action, _HelpAction)
  295. and type(action) not in boolean_actions)
  296. def is_flag(action):
  297. """ _actions which are either storeconst, store_bool, etc.. """
  298. action_types = [_StoreTrueAction, _StoreFalseAction, _StoreConstAction]
  299. return any(list(map(lambda Action: isinstance(action, Action), action_types)))
  300. def is_counter(action):
  301. """ _actions which are of type _CountAction """
  302. return isinstance(action, _CountAction)
  303. def is_default_progname(name, subparser):
  304. return subparser.prog == '{} {}'.format(os.path.split(sys.argv[0])[-1], name)
  305. def is_help_message(action):
  306. return isinstance(action, _HelpAction)
  307. def choose_name(name, subparser):
  308. return name if is_default_progname(name, subparser) else subparser.prog
  309. def build_radio_group(mutex_group, widget_group, options):
  310. return {
  311. 'id': str(uuid4()),
  312. 'type': 'RadioGroup',
  313. 'cli_type': 'optional',
  314. 'group_name': 'Choose Option',
  315. 'required': mutex_group.required,
  316. 'options': merge(item_default, getattr(mutex_group, 'gooey_options', {})),
  317. 'data': {
  318. 'commands': [action.option_strings for action in mutex_group._group_actions],
  319. 'widgets': list(categorize(mutex_group._group_actions, widget_group, options))
  320. }
  321. }
  322. def action_to_json(action, widget, options):
  323. dropdown_types = {'Listbox', 'Dropdown', 'Counter'}
  324. if action.required:
  325. # Text fields get a default check that user input is present
  326. # and not just spaces, dropdown types get a simplified
  327. # is-it-present style check
  328. validator = ('user_input and not user_input.isspace()'
  329. if widget not in dropdown_types
  330. else 'user_input')
  331. error_msg = 'This field is required'
  332. else:
  333. # not required; do nothing;
  334. validator = 'True'
  335. error_msg = ''
  336. base = merge(item_default, {
  337. 'validator': {
  338. 'type': 'ExpressionValidator',
  339. 'test': validator,
  340. 'message': error_msg
  341. },
  342. })
  343. default = handle_default(action, widget)
  344. if default == argparse.SUPPRESS:
  345. default = None
  346. final_options = merge(base, options.get(action.dest) or {})
  347. validate_gooey_options(action, widget, final_options)
  348. return {
  349. 'id': action.option_strings[0] if action.option_strings else action.dest,
  350. 'type': widget,
  351. 'cli_type': choose_cli_type(action),
  352. 'required': action.required,
  353. 'data': {
  354. 'display_name': action.metavar or action.dest,
  355. 'help': action.help,
  356. 'required': action.required,
  357. 'nargs': action.nargs or '',
  358. 'commands': action.option_strings,
  359. 'choices': list(map(str, action.choices)) if action.choices else [],
  360. 'default': default,
  361. 'dest': action.dest,
  362. },
  363. 'options': final_options
  364. }
  365. def validate_gooey_options(action, widget, options):
  366. """Very basic field validation / sanity checking for
  367. the time being.
  368. Future plans are to assert against the options and actions together
  369. to facilitate checking that certain options like `initial_selection` in
  370. RadioGroups map to a value which actually exists (rather than exploding
  371. at runtime with an unhelpful error)
  372. Additional problems with the current approach is that no feedback is given
  373. as to WHERE the issue took place (in terms of stacktrace). Which means we should
  374. probably explode in GooeyParser proper rather than trying to collect all the errors here.
  375. It's not super ideal in that the user will need to run multiple times to
  376. see all the issues, but, ultimately probably less annoying that trying to
  377. debug which `gooey_option` key had an issue in a large program.
  378. That said "better is the enemy of done." This is good enough for now. It'll be
  379. a TODO: better validation
  380. """
  381. errors = collect_errors(validators, options)
  382. if errors:
  383. from pprint import pformat
  384. raise ValueError(str(action.dest) + str(pformat(errors)))
  385. def choose_cli_type(action):
  386. return 'positional' \
  387. if action.required and not action.option_strings \
  388. else 'optional'
  389. def coerce_default(default, widget):
  390. """coerce a default value to the best appropriate type for
  391. ingestion into wx"""
  392. dispatcher = {
  393. 'Listbox': clean_list_defaults,
  394. 'Dropdown': safe_string,
  395. 'Counter': safe_string
  396. }
  397. # Issue #321:
  398. # Defaults for choice types must be coerced to strings
  399. # to be able to match the stringified `choices` used by `wx.ComboBox`
  400. cleaned = clean_default(default)
  401. # dispatch to the appropriate cleaning function, or return the value
  402. # as is if no special handler is present
  403. return dispatcher.get(widget, identity)(cleaned)
  404. def handle_default(action, widget):
  405. handlers = [
  406. [textinput_with_nargs_and_list_default, coerse_nargs_list],
  407. [is_widget('Listbox'), clean_list_defaults],
  408. [is_widget('Dropdown'), coerce_str],
  409. [is_widget('Counter'), safe_string]
  410. ]
  411. for matches, apply_coercion in handlers:
  412. if matches(action, widget):
  413. return apply_coercion(action.default)
  414. return clean_default(action.default)
  415. def coerse_nargs_list(default):
  416. """
  417. nargs=* and defaults which are collection types
  418. must be transformed into a CLI equivalent form. So, for
  419. instance, ['one two', 'three'] => "one two" "three"
  420. This only applies when the target widget is a text input. List
  421. based widgets such as ListBox should keep their defaults in list form
  422. Without this transformation, `add_arg('--foo', default=['a b'], nargs='*')` would show up in
  423. the UI as the literal string `['a b']` brackets and all.
  424. """
  425. return ' '.join('"{}"'.format(x) for x in default)
  426. def is_widget(name):
  427. def equals(action, widget):
  428. return widget == name
  429. return equals
  430. def textinput_with_nargs_and_list_default(action, widget):
  431. """
  432. Vanilla TextInputs which have nargs options which produce lists (i.e.
  433. nargs +, *, N, or REMAINDER) need to have their default values transformed
  434. into CLI style space-separated entries when they're supplied as a list of values
  435. on the Python side.
  436. """
  437. return (
  438. widget in {'TextField', 'Textarea', 'PasswordField'}
  439. and (isinstance(action.default, list) or isinstance(action.default, tuple))
  440. and is_list_based_nargs(action))
  441. def is_list_based_nargs(action):
  442. """ """
  443. return isinstance(action.nargs, int) or action.nargs in {'*', '+', '...'}
  444. def clean_list_defaults(default_values):
  445. """
  446. Listbox's default's can be passed as a single value
  447. or a collection of values (due to multiple selections). The list interface
  448. is standardized on for ease.
  449. """
  450. wrapped_values = ([default_values]
  451. if isinstance(default_values, str)
  452. else default_values)
  453. return [safe_string(value) for value in wrapped_values or []]
  454. def clean_default(default):
  455. """
  456. Attempts to safely coalesce the default value down to
  457. a valid JSON type.
  458. """
  459. try:
  460. json.dumps(default)
  461. return default
  462. except TypeError as e:
  463. # see: Issue #377
  464. # if is ins't json serializable (i.e. primitive data) there's nothing
  465. # useful for Gooey to do with it (since Gooey deals in primitive data
  466. # types). So the correct behavior is dropping them. This affects ONLY
  467. # gooey, not the client code.
  468. return None
  469. def safe_string(value):
  470. """
  471. Coerce a type to string as long as it isn't None or Boolean
  472. TODO: why do I have this special boolean case..?
  473. """
  474. if value is None or isinstance(value, bool):
  475. return value
  476. else:
  477. return str(value)
  478. def coerce_str(value):
  479. """
  480. Coerce the incoming type to string as long as it isn't None
  481. """
  482. return str(value) if value is not None else value
  483. def this_is_a_comment(action, widget):
  484. """
  485. TODO:
  486. - better handling of nargs.
  487. - allowing a class of "Narg'able" widget variants that allow dynamically adding options.
  488. Below are some rough notes on the current widgets and their nargs behavior (or lack of)
  489. """
  490. asdf = [
  491. # choosers are all currently treated as
  492. # singular inputs regardless of nargs status.
  493. 'FileChooser',
  494. 'MultiFileChooser',
  495. 'FileSaver',
  496. 'DirChooser',
  497. 'DateChooser',
  498. 'TimeChooser',
  499. # radiogroup requires no special logic. Delegates to internal widgets
  500. 'RadioGroup',
  501. # nargs invalid
  502. 'CheckBox',
  503. # nargs invalid
  504. 'BlockCheckbox',
  505. # currently combines everything into a single, system _sep separated string
  506. # potential nargs behavior
  507. # input: - each item gets a readonly textbox?
  508. # - each item is its own editable widget?
  509. # - problem with this idea is selected a ton of files would break the UI.
  510. # maybe a better option would be to expose what's been added as a small
  511. # list view? That way its a fixed size even if they choose 100s of files.
  512. #
  513. 'MultiDirChooser',
  514. # special case. convert default to list of strings
  515. 'Listbox',
  516. # special cases. coerce default to string
  517. 'Dropdown',
  518. 'Counter',
  519. # nargs behavior:
  520. # - convert to space separated list of strings
  521. 'TextField',
  522. 'Textarea',
  523. 'PasswordField',
  524. ]