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.

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