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.

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