cli_function.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #!/usr/bin/env python3
  2. import argparse
  3. import bisect
  4. import collections
  5. import imp
  6. import os
  7. import sys
  8. class _Argument:
  9. def __init__(
  10. self,
  11. long_or_short_1,
  12. long_or_short_2=None,
  13. default=None,
  14. dest=None,
  15. help=None,
  16. nargs=None,
  17. **kwargs
  18. ):
  19. self.args = []
  20. # argparse is crappy and cannot tell us if arguments were given or not.
  21. # We need that information to decide if the config file should override argparse or not.
  22. # So we just use None as a sentinel.
  23. self.kwargs = {'default': None}
  24. shortname, longname, key, is_option = self.get_key(
  25. long_or_short_1,
  26. long_or_short_2,
  27. dest
  28. )
  29. if shortname is not None:
  30. self.args.append(shortname)
  31. if is_option:
  32. self.args.append(longname)
  33. else:
  34. self.args.append(key)
  35. self.kwargs['metavar'] = longname
  36. if default is not None and nargs is None:
  37. self.kwargs['nargs'] = '?'
  38. if dest is not None:
  39. self.kwargs['dest'] = dest
  40. if nargs is not None:
  41. self.kwargs['nargs'] = nargs
  42. if default is True or default is False:
  43. bool_action = 'store_true'
  44. self.is_bool = True
  45. else:
  46. self.is_bool = False
  47. if default is None and (
  48. nargs in ('*', '+')
  49. or ('action' in kwargs and kwargs['action'] == 'append')
  50. ):
  51. default = []
  52. if self.is_bool and not 'action' in kwargs:
  53. self.kwargs['action'] = bool_action
  54. if help is not None:
  55. if default is not None:
  56. if help[-1] == '\n':
  57. if '\n\n' in help[:-1]:
  58. help += '\n'
  59. elif help[-1] == ' ':
  60. pass
  61. else:
  62. help += ' '
  63. help += 'Default: {}'.format(default)
  64. self.kwargs['help'] = help
  65. self.optional = (
  66. default is not None or
  67. self.is_bool or
  68. is_option or
  69. nargs in ('?', '*', '+')
  70. )
  71. self.kwargs.update(kwargs)
  72. self.default = default
  73. self.longname = longname
  74. self.key = key
  75. self.is_option = is_option
  76. self.nargs = nargs
  77. def __str__(self):
  78. return str(self.args) + ' ' + str(self.kwargs)
  79. @staticmethod
  80. def get_key(
  81. long_or_short_1,
  82. long_or_short_2=None,
  83. dest=None,
  84. **kwargs
  85. ):
  86. if long_or_short_2 is None:
  87. shortname = None
  88. longname = long_or_short_1
  89. else:
  90. shortname = long_or_short_1
  91. longname = long_or_short_2
  92. if longname[0] == '-':
  93. key = longname.lstrip('-').replace('-', '_')
  94. is_option = True
  95. else:
  96. key = longname.replace('-', '_')
  97. is_option = False
  98. if dest is not None:
  99. key = dest
  100. return shortname, longname, key, is_option
  101. class CliFunction:
  102. '''
  103. Represent a function that can be called either from Python code, or
  104. from the command line.
  105. Features:
  106. * single argument description in format very similar to argparse
  107. * handle default arguments transparently in both cases
  108. * expose a configuration file mechanism to get default parameters from a file
  109. * fix some argparse.ArgumentParser() annoyances:
  110. ** allow dashes in positional arguments:
  111. https://stackoverflow.com/questions/12834785/having-options-in-argparse-with-a-dash
  112. ** boolean defaults automatically use store_true or store_false, and add a --no-* CLI
  113. option to invert them if set from the config
  114. * from a Python call, get the corresponding CLI string list. See get_cli.
  115. * easily determine if arguments were given on the command line
  116. https://stackoverflow.com/questions/30487767/check-if-argparse-optional-argument-is-set-or-not/30491369
  117. This somewhat duplicates: https://click.palletsprojects.com but:
  118. * that decorator API is insane
  119. * CLI + Python for single functions was wontfixed: https://github.com/pallets/click/issues/40
  120. '''
  121. def __call__(self, **kwargs):
  122. '''
  123. Python version of the function call. Not called by cli() indirectly,
  124. so can be overridden to distinguish between Python and CLI calls.
  125. :type arguments: Dict
  126. '''
  127. return self._do_main(kwargs)
  128. def _do_main(self, kwargs):
  129. return self.main(**self._get_args(kwargs))
  130. def __init__(self, config_file=None, description=None, extra_config_params=None):
  131. self._arguments = collections.OrderedDict()
  132. self._config_file = config_file
  133. self._description = description
  134. self.extra_config_params = extra_config_params
  135. if self._config_file is not None:
  136. self.add_argument(
  137. '--config-file',
  138. default=self._config_file,
  139. help='Path to the configuration file to use'
  140. )
  141. def __str__(self):
  142. return '\n'.join(str(arg[key]) for key in self._arguments)
  143. def _get_args(self, kwargs):
  144. '''
  145. Resolve default arguments from the config file and CLI param defaults.
  146. Add an extra _args_given argument which determines if an argument was given or not.
  147. Args set from the config file count as given.
  148. '''
  149. args_with_defaults = kwargs.copy()
  150. # Add missing args from config file.
  151. config_file = None
  152. if 'config_file' in args_with_defaults and args_with_defaults['config_file'] is not None:
  153. config_file = args_with_defaults['config_file']
  154. else:
  155. config_file = self._config_file
  156. args_given = {}
  157. for key in self._arguments:
  158. args_given[key] = not (
  159. not key in args_with_defaults or
  160. args_with_defaults[key] is None or
  161. self._arguments[key].nargs == '*' and args_with_defaults[key] == []
  162. )
  163. if config_file is not None and os.path.exists(config_file):
  164. config_configs = {}
  165. config = imp.load_source('config', config_file)
  166. if self.extra_config_params is None:
  167. config.set_args(config_configs)
  168. else:
  169. config.set_args(config_configs, self.extra_config_params)
  170. for key in config_configs:
  171. if key not in self._arguments:
  172. raise Exception('Unknown key in config file: ' + key)
  173. if not args_given[key]:
  174. args_with_defaults[key] = config_configs[key]
  175. args_given[key] = True
  176. # Add missing args from hard-coded defaults.
  177. for key in self._arguments:
  178. argument = self._arguments[key]
  179. if (not key in args_with_defaults) or args_with_defaults[key] is None:
  180. if argument.optional:
  181. args_with_defaults[key] = argument.default
  182. else:
  183. raise Exception('Value not given for mandatory argument: ' + key)
  184. args_with_defaults['_args_given'] = args_given
  185. if 'config_file' in args_with_defaults:
  186. del args_with_defaults['config_file']
  187. return args_with_defaults
  188. def add_argument(
  189. self,
  190. *args,
  191. **kwargs
  192. ):
  193. argument = _Argument(*args, **kwargs)
  194. self._arguments[argument.key] = argument
  195. def cli_noexit(self, cli_args=None):
  196. '''
  197. Call the function from the CLI. Parse command line arguments
  198. to get all arguments.
  199. :return: the return of main
  200. '''
  201. parser = argparse.ArgumentParser(
  202. description=self._description,
  203. formatter_class=argparse.RawTextHelpFormatter,
  204. )
  205. for key in self._arguments:
  206. argument = self._arguments[key]
  207. parser.add_argument(*argument.args, **argument.kwargs)
  208. if argument.is_bool:
  209. new_longname = '--no' + argument.longname[1:]
  210. kwargs = argument.kwargs.copy()
  211. kwargs['default'] = not argument.default
  212. if kwargs['action'] in ('store_true', 'store_false'):
  213. kwargs['action'] = 'store_false'
  214. if 'help' in kwargs:
  215. del kwargs['help']
  216. parser.add_argument(new_longname, dest=argument.key, **kwargs)
  217. args = parser.parse_args(args=cli_args)
  218. return self._do_main(vars(args))
  219. def cli(self, *args, **kwargs):
  220. '''
  221. Same as cli, but also exit the program with status equal to the return value of main.
  222. main must return an integer for this to be used.
  223. None is considered 0.
  224. '''
  225. exit_status = self.cli_noexit(*args, **kwargs)
  226. if exit_status is None:
  227. exit_status = 0
  228. sys.exit(exit_status)
  229. def get_cli(self, **kwargs):
  230. '''
  231. :rtype: List[Type(str)]
  232. :return: the canonical command line arguments arguments that would
  233. generate this Python function call.
  234. (--key, value) option pairs are grouped into tuples, and all
  235. other values are grouped in their own tuple (positional_arg,)
  236. or (--bool-arg,).
  237. Arguments with default values are not added, but arguments
  238. that are set by the config are also given.
  239. The optional arguments are sorted alphabetically, followed by
  240. positional arguments.
  241. The long option name is used if both long and short versions
  242. are given.
  243. '''
  244. options = []
  245. positional_dict = {}
  246. kwargs = self._get_args(kwargs)
  247. for key in kwargs:
  248. if not key in ('_args_given',):
  249. argument = self._arguments[key]
  250. default = argument.default
  251. value = kwargs[key]
  252. if value != default:
  253. if argument.is_option:
  254. if argument.is_bool:
  255. vals = [(argument.longname,)]
  256. elif 'action' in argument.kwargs and argument.kwargs['action'] == 'append':
  257. vals = [(argument.longname, str(val)) for val in value]
  258. else:
  259. vals = [(argument.longname, str(value))]
  260. for val in vals:
  261. bisect.insort(options, val)
  262. else:
  263. if type(value) is list:
  264. positional_dict[key] = [tuple([v]) for v in value]
  265. else:
  266. positional_dict[key] = [(str(value),)]
  267. # Python built-in data structures suck.
  268. # https://stackoverflow.com/questions/27726245/getting-the-key-index-in-a-python-ordereddict/27726534#27726534
  269. positional = []
  270. for key in self._arguments.keys():
  271. if key in positional_dict:
  272. positional.extend(positional_dict[key])
  273. return options + positional
  274. @staticmethod
  275. def get_key(*args, **kwargs):
  276. return _Argument.get_key(*args, **kwargs)
  277. def main(self, **kwargs):
  278. '''
  279. Do the main function call work.
  280. :type arguments: Dict
  281. '''
  282. raise NotImplementedError
  283. if __name__ == '__main__':
  284. class OneCliFunction(CliFunction):
  285. def __init__(self):
  286. super().__init__(
  287. config_file='cli_function_test_config.py',
  288. description = '''\
  289. Description of this
  290. amazing function!
  291. ''',
  292. )
  293. self.add_argument('-a', '--asdf', default='A', help='Help for asdf'),
  294. self.add_argument('-q', '--qwer', default='Q', help='Help for qwer'),
  295. self.add_argument('-b', '--bool-true', default=True, help='Help for bool-true'),
  296. self.add_argument('--bool-false', default=False, help='Help for bool-false'),
  297. self.add_argument('--dest', dest='custom_dest', help='Help for dest'),
  298. self.add_argument('--bool-cli', default=False, help='Help for bool'),
  299. self.add_argument('--bool-nargs', default=False, nargs='?', action='store', const='')
  300. self.add_argument('--no-default', help='Help for no-bool'),
  301. self.add_argument('--append', action='append')
  302. self.add_argument('pos-mandatory', help='Help for pos-mandatory', type=int),
  303. self.add_argument('pos-optional', default=0, help='Help for pos-optional', type=int),
  304. self.add_argument('args-star', help='Help for args-star', nargs='*'),
  305. def main(self, **kwargs):
  306. del kwargs['_args_given']
  307. return kwargs
  308. one_cli_function = OneCliFunction()
  309. # Default code call.
  310. default = one_cli_function(pos_mandatory=1)
  311. assert default == {
  312. 'asdf': 'A',
  313. 'qwer': 'Q',
  314. 'bool_true': True,
  315. 'bool_false': False,
  316. 'bool_nargs': False,
  317. 'bool_cli': True,
  318. 'custom_dest': None,
  319. 'no_default': None,
  320. 'append': [],
  321. 'pos_mandatory': 1,
  322. 'pos_optional': 0,
  323. 'args_star': []
  324. }
  325. # Default CLI call with programmatic CLI arguments.
  326. out = one_cli_function.cli_noexit(['1'])
  327. assert out == default
  328. # asdf
  329. out = one_cli_function(pos_mandatory=1, asdf='B')
  330. assert out['asdf'] == 'B'
  331. out['asdf'] = default['asdf']
  332. assert out == default
  333. # asdf and qwer
  334. out = one_cli_function(pos_mandatory=1, asdf='B', qwer='R')
  335. assert out['asdf'] == 'B'
  336. assert out['qwer'] == 'R'
  337. out['asdf'] = default['asdf']
  338. out['qwer'] = default['qwer']
  339. assert out == default
  340. if '--bool-true':
  341. out = one_cli_function(pos_mandatory=1, bool_true=False)
  342. cli_out = one_cli_function.cli_noexit(['--no-bool-true', '1'])
  343. assert out == cli_out
  344. assert out['bool_true'] == False
  345. out['bool_true'] = default['bool_true']
  346. assert out == default
  347. if '--bool-false':
  348. out = one_cli_function(pos_mandatory=1, bool_false=True)
  349. cli_out = one_cli_function.cli_noexit(['--bool-false', '1'])
  350. assert out == cli_out
  351. assert out['bool_false'] == True
  352. out['bool_false'] = default['bool_false']
  353. assert out == default
  354. if '--bool-nargs':
  355. out = one_cli_function(pos_mandatory=1, bool_nargs=True)
  356. assert out['bool_nargs'] == True
  357. out['bool_nargs'] = default['bool_nargs']
  358. assert out == default
  359. out = one_cli_function(pos_mandatory=1, bool_nargs='asdf')
  360. assert out['bool_nargs'] == 'asdf'
  361. out['bool_nargs'] = default['bool_nargs']
  362. assert out == default
  363. # --dest
  364. out = one_cli_function(pos_mandatory=1, custom_dest='a')
  365. cli_out = one_cli_function.cli_noexit(['--dest', 'a', '1'])
  366. assert out == cli_out
  367. assert out['custom_dest'] == 'a'
  368. out['custom_dest'] = default['custom_dest']
  369. assert out == default
  370. # Positional
  371. out = one_cli_function(pos_mandatory=1, pos_optional=2, args_star=['3', '4'])
  372. assert out['pos_mandatory'] == 1
  373. assert out['pos_optional'] == 2
  374. assert out['args_star'] == ['3', '4']
  375. cli_out = one_cli_function.cli_noexit(['1', '2', '3', '4'])
  376. assert out == cli_out
  377. out['pos_mandatory'] = default['pos_mandatory']
  378. out['pos_optional'] = default['pos_optional']
  379. out['args_star'] = default['args_star']
  380. assert out == default
  381. # Star
  382. out = one_cli_function(append=['1', '2'], pos_mandatory=1)
  383. cli_out = one_cli_function.cli_noexit(['--append', '1', '--append', '2', '1'])
  384. assert out == cli_out
  385. assert out['append'] == ['1', '2']
  386. out['append'] = default['append']
  387. assert out == default
  388. # Force a boolean value set on the config to be False on CLI.
  389. assert one_cli_function.cli_noexit(['--no-bool-cli', '1'])['bool_cli'] is False
  390. # Pick another config file.
  391. assert one_cli_function.cli_noexit(['--config-file', 'cli_function_test_config_2.py', '1'])['bool_cli'] is False
  392. # Extra config file for '*'.
  393. assert one_cli_function.cli_noexit(['--config-file', 'cli_function_test_config_2.py', '1', '2', '3', '4'])['args_star'] == ['3', '4']
  394. assert one_cli_function.cli_noexit(['--config-file', 'cli_function_test_config_2.py', '1', '2'])['args_star'] == ['asdf', 'qwer']
  395. # get_cli
  396. assert one_cli_function.get_cli(pos_mandatory=1, asdf='B') == [('--asdf', 'B'), ('--bool-cli',), ('1',)]
  397. assert one_cli_function.get_cli(pos_mandatory=1, asdf='B', qwer='R') == [('--asdf', 'B'), ('--bool-cli',), ('--qwer', 'R'), ('1',)]
  398. assert one_cli_function.get_cli(pos_mandatory=1, bool_true=False) == [('--bool-cli',), ('--bool-true',), ('1',)]
  399. assert one_cli_function.get_cli(pos_mandatory=1, pos_optional=2, args_star=['asdf', 'qwer']) == [('--bool-cli',), ('1',), ('2',), ('asdf',), ('qwer',)]
  400. assert one_cli_function.get_cli(pos_mandatory=1, append=['2', '3']) == [('--append', '2'), ('--append', '3',), ('--bool-cli',), ('1',)]
  401. if len(sys.argv) > 1:
  402. # CLI call with argv command line arguments.
  403. print(one_cli_function.cli())