milc.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. #!/usr/bin/env python3
  2. # coding=utf-8
  3. """MILC - A CLI Framework
  4. PYTHON_ARGCOMPLETE_OK
  5. MILC is an opinionated framework for writing CLI apps. It optimizes for the
  6. most common unix tool pattern- small tools that are run from the command
  7. line but generally do not feature any user interaction while they run.
  8. For more details see the MILC documentation:
  9. <https://github.com/clueboard/milc/tree/master/docs>
  10. """
  11. from __future__ import division, print_function, unicode_literals
  12. import argparse
  13. import logging
  14. import os
  15. import re
  16. import shlex
  17. import sys
  18. from decimal import Decimal
  19. from pathlib import Path
  20. from tempfile import NamedTemporaryFile
  21. from time import sleep
  22. try:
  23. from ConfigParser import RawConfigParser
  24. except ImportError:
  25. from configparser import RawConfigParser
  26. try:
  27. import thread
  28. import threading
  29. except ImportError:
  30. thread = None
  31. import argcomplete
  32. import colorama
  33. from appdirs import user_config_dir
  34. # Disable logging until we can configure it how the user wants
  35. logging.basicConfig(stream=os.devnull)
  36. # Log Level Representations
  37. EMOJI_LOGLEVELS = {
  38. 'CRITICAL': '{bg_red}{fg_white}¬_¬{style_reset_all}',
  39. 'ERROR': '{fg_red}☒{style_reset_all}',
  40. 'WARNING': '{fg_yellow}⚠{style_reset_all}',
  41. 'INFO': '{fg_blue}ℹ{style_reset_all}',
  42. 'DEBUG': '{fg_cyan}☐{style_reset_all}',
  43. 'NOTSET': '{style_reset_all}¯\\_(o_o)_/¯'
  44. }
  45. EMOJI_LOGLEVELS['FATAL'] = EMOJI_LOGLEVELS['CRITICAL']
  46. EMOJI_LOGLEVELS['WARN'] = EMOJI_LOGLEVELS['WARNING']
  47. UNICODE_SUPPORT = sys.stdout.encoding.lower().startswith('utf')
  48. # ANSI Color setup
  49. # Regex was gratefully borrowed from kfir on stackoverflow:
  50. # https://stackoverflow.com/a/45448194
  51. ansi_regex = r'\x1b(' \
  52. r'(\[\??\d+[hl])|' \
  53. r'([=<>a-kzNM78])|' \
  54. r'([\(\)][a-b0-2])|' \
  55. r'(\[\d{0,2}[ma-dgkjqi])|' \
  56. r'(\[\d+;\d+[hfy]?)|' \
  57. r'(\[;?[hf])|' \
  58. r'(#[3-68])|' \
  59. r'([01356]n)|' \
  60. r'(O[mlnp-z]?)|' \
  61. r'(/Z)|' \
  62. r'(\d+)|' \
  63. r'(\[\?\d;\d0c)|' \
  64. r'(\d;\dR))'
  65. ansi_escape = re.compile(ansi_regex, flags=re.IGNORECASE)
  66. ansi_styles = (
  67. ('fg', colorama.ansi.AnsiFore()),
  68. ('bg', colorama.ansi.AnsiBack()),
  69. ('style', colorama.ansi.AnsiStyle()),
  70. )
  71. ansi_colors = {}
  72. for prefix, obj in ansi_styles:
  73. for color in [x for x in obj.__dict__ if not x.startswith('_')]:
  74. ansi_colors[prefix + '_' + color.lower()] = getattr(obj, color)
  75. def format_ansi(text):
  76. """Return a copy of text with certain strings replaced with ansi.
  77. """
  78. # Avoid .format() so we don't have to worry about the log content
  79. for color in ansi_colors:
  80. text = text.replace('{%s}' % color, ansi_colors[color])
  81. return text + ansi_colors['style_reset_all']
  82. class ANSIFormatter(logging.Formatter):
  83. """A log formatter that inserts ANSI color.
  84. """
  85. def format(self, record):
  86. msg = super(ANSIFormatter, self).format(record)
  87. return format_ansi(msg)
  88. class ANSIEmojiLoglevelFormatter(ANSIFormatter):
  89. """A log formatter that makes the loglevel an emoji on UTF capable terminals.
  90. """
  91. def format(self, record):
  92. if UNICODE_SUPPORT:
  93. record.levelname = EMOJI_LOGLEVELS[record.levelname].format(**ansi_colors)
  94. return super(ANSIEmojiLoglevelFormatter, self).format(record)
  95. class ANSIStrippingFormatter(ANSIFormatter):
  96. """A log formatter that strips ANSI.
  97. """
  98. def format(self, record):
  99. msg = super(ANSIStrippingFormatter, self).format(record)
  100. return ansi_escape.sub('', msg)
  101. class Configuration(object):
  102. """Represents the running configuration.
  103. This class never raises IndexError, instead it will return None if a
  104. section or option does not yet exist.
  105. """
  106. def __contains__(self, key):
  107. return self._config.__contains__(key)
  108. def __iter__(self):
  109. return self._config.__iter__()
  110. def __len__(self):
  111. return self._config.__len__()
  112. def __repr__(self):
  113. return self._config.__repr__()
  114. def keys(self):
  115. return self._config.keys()
  116. def items(self):
  117. return self._config.items()
  118. def values(self):
  119. return self._config.values()
  120. def __init__(self, *args, **kwargs):
  121. self._config = {}
  122. def __getattr__(self, key):
  123. return self.__getitem__(key)
  124. def __getitem__(self, key):
  125. """Returns a config section, creating it if it doesn't exist yet.
  126. """
  127. if key not in self._config:
  128. self.__dict__[key] = self._config[key] = ConfigurationSection(self)
  129. return self._config[key]
  130. def __setitem__(self, key, value):
  131. self.__dict__[key] = value
  132. self._config[key] = value
  133. def __delitem__(self, key):
  134. if key in self.__dict__ and key[0] != '_':
  135. del self.__dict__[key]
  136. if key in self._config:
  137. del self._config[key]
  138. class ConfigurationSection(Configuration):
  139. def __init__(self, parent, *args, **kwargs):
  140. super(ConfigurationSection, self).__init__(*args, **kwargs)
  141. self.parent = parent
  142. def __getitem__(self, key):
  143. """Returns a config value, pulling from the `user` section as a fallback.
  144. """
  145. if key in self._config:
  146. return self._config[key]
  147. elif key in self.parent.user:
  148. return self.parent.user[key]
  149. return None
  150. def handle_store_boolean(self, *args, **kwargs):
  151. """Does the add_argument for action='store_boolean'.
  152. """
  153. disabled_args = None
  154. disabled_kwargs = kwargs.copy()
  155. disabled_kwargs['action'] = 'store_false'
  156. disabled_kwargs['dest'] = self.get_argument_name(*args, **kwargs)
  157. disabled_kwargs['help'] = 'Disable ' + kwargs['help']
  158. kwargs['action'] = 'store_true'
  159. kwargs['help'] = 'Enable ' + kwargs['help']
  160. for flag in args:
  161. if flag[:2] == '--':
  162. disabled_args = ('--no-' + flag[2:],)
  163. break
  164. self.add_argument(*args, **kwargs)
  165. self.add_argument(*disabled_args, **disabled_kwargs)
  166. return (args, kwargs, disabled_args, disabled_kwargs)
  167. class SubparserWrapper(object):
  168. """Wrap subparsers so we can track what options the user passed.
  169. """
  170. def __init__(self, cli, submodule, subparser):
  171. self.cli = cli
  172. self.submodule = submodule
  173. self.subparser = subparser
  174. for attr in dir(subparser):
  175. if not hasattr(self, attr):
  176. setattr(self, attr, getattr(subparser, attr))
  177. def completer(self, completer):
  178. """Add an arpcomplete completer to this subcommand.
  179. """
  180. self.subparser.completer = completer
  181. def add_argument(self, *args, **kwargs):
  182. """Add an argument for this subcommand.
  183. This also stores the default for the argument in `self.cli.default_arguments`.
  184. """
  185. if 'action' in kwargs and kwargs['action'] == 'store_boolean':
  186. # Store boolean will call us again with the enable/disable flag arguments
  187. return handle_store_boolean(self, *args, **kwargs)
  188. self.cli.acquire_lock()
  189. self.subparser.add_argument(*args, **kwargs)
  190. if self.submodule not in self.cli.default_arguments:
  191. self.cli.default_arguments[self.submodule] = {}
  192. self.cli.default_arguments[self.submodule][self.cli.get_argument_name(*args, **kwargs)] = kwargs.get('default')
  193. self.cli.release_lock()
  194. class MILC(object):
  195. """MILC - An Opinionated Batteries Included Framework
  196. """
  197. def __init__(self):
  198. """Initialize the MILC object.
  199. version
  200. The version string to associate with your CLI program
  201. """
  202. # Setup a lock for thread safety
  203. self._lock = threading.RLock() if thread else None
  204. # Define some basic info
  205. self.acquire_lock()
  206. self._description = None
  207. self._entrypoint = None
  208. self._inside_context_manager = False
  209. self.ansi = ansi_colors
  210. self.arg_only = []
  211. self.config = None
  212. self.config_file = None
  213. self.default_arguments = {}
  214. self.version = 'unknown'
  215. self.release_lock()
  216. # Figure out our program name
  217. self.prog_name = sys.argv[0][:-3] if sys.argv[0].endswith('.py') else sys.argv[0]
  218. self.prog_name = self.prog_name.split('/')[-1]
  219. # Initialize all the things
  220. self.read_config_file()
  221. self.initialize_argparse()
  222. self.initialize_logging()
  223. @property
  224. def description(self):
  225. return self._description
  226. @description.setter
  227. def description(self, value):
  228. self._description = self._arg_parser.description = value
  229. def echo(self, text, *args, **kwargs):
  230. """Print colorized text to stdout.
  231. ANSI color strings (such as {fg-blue}) will be converted into ANSI
  232. escape sequences, and the ANSI reset sequence will be added to all
  233. strings.
  234. If *args or **kwargs are passed they will be used to %-format the strings.
  235. """
  236. if args and kwargs:
  237. raise RuntimeError('You can only specify *args or **kwargs, not both!')
  238. args = args or kwargs
  239. text = format_ansi(text)
  240. print(text % args)
  241. def initialize_argparse(self):
  242. """Prepare to process arguments from sys.argv.
  243. """
  244. kwargs = {
  245. 'fromfile_prefix_chars': '@',
  246. 'conflict_handler': 'resolve',
  247. }
  248. self.acquire_lock()
  249. self.subcommands = {}
  250. self._subparsers = None
  251. self.argwarn = argcomplete.warn
  252. self.args = None
  253. self._arg_parser = argparse.ArgumentParser(**kwargs)
  254. self.set_defaults = self._arg_parser.set_defaults
  255. self.print_usage = self._arg_parser.print_usage
  256. self.print_help = self._arg_parser.print_help
  257. self.release_lock()
  258. def completer(self, completer):
  259. """Add an argcomplete completer to this subcommand.
  260. """
  261. self._arg_parser.completer = completer
  262. def add_argument(self, *args, **kwargs):
  263. """Wrapper to add arguments and track whether they were passed on the command line.
  264. """
  265. if 'action' in kwargs and kwargs['action'] == 'store_boolean':
  266. return handle_store_boolean(self, *args, **kwargs)
  267. self.acquire_lock()
  268. self._arg_parser.add_argument(*args, **kwargs)
  269. if 'general' not in self.default_arguments:
  270. self.default_arguments['general'] = {}
  271. self.default_arguments['general'][self.get_argument_name(*args, **kwargs)] = kwargs.get('default')
  272. self.release_lock()
  273. def initialize_logging(self):
  274. """Prepare the defaults for the logging infrastructure.
  275. """
  276. self.acquire_lock()
  277. self.log_file = None
  278. self.log_file_mode = 'a'
  279. self.log_file_handler = None
  280. self.log_print = True
  281. self.log_print_to = sys.stderr
  282. self.log_print_level = logging.INFO
  283. self.log_file_level = logging.DEBUG
  284. self.log_level = logging.INFO
  285. self.log = logging.getLogger(self.__class__.__name__)
  286. self.log.setLevel(logging.DEBUG)
  287. logging.root.setLevel(logging.DEBUG)
  288. self.release_lock()
  289. self.add_argument('-V', '--version', version=self.version, action='version', help='Display the version and exit')
  290. self.add_argument('-v', '--verbose', action='store_true', help='Make the logging more verbose')
  291. self.add_argument('--datetime-fmt', default='%Y-%m-%d %H:%M:%S', help='Format string for datetimes')
  292. self.add_argument('--log-fmt', default='%(levelname)s %(message)s', help='Format string for printed log output')
  293. self.add_argument('--log-file-fmt', default='[%(levelname)s] [%(asctime)s] [file:%(pathname)s] [line:%(lineno)d] %(message)s', help='Format string for log file.')
  294. self.add_argument('--log-file', help='File to write log messages to')
  295. self.add_argument('--color', action='store_boolean', default=True, help='color in output')
  296. self.add_argument('--config-file', help='The location for the configuration file')
  297. self.arg_only.append('config_file')
  298. def add_subparsers(self, title='Sub-commands', **kwargs):
  299. if self._inside_context_manager:
  300. raise RuntimeError('You must run this before the with statement!')
  301. self.acquire_lock()
  302. self._subparsers = self._arg_parser.add_subparsers(title=title, dest='subparsers', **kwargs)
  303. self.release_lock()
  304. def acquire_lock(self):
  305. """Acquire the MILC lock for exclusive access to properties.
  306. """
  307. if self._lock:
  308. self._lock.acquire()
  309. def release_lock(self):
  310. """Release the MILC lock.
  311. """
  312. if self._lock:
  313. self._lock.release()
  314. def find_config_file(self):
  315. """Locate the config file.
  316. """
  317. if self.config_file:
  318. return self.config_file
  319. if '--config-file' in sys.argv:
  320. return Path(sys.argv[sys.argv.index('--config-file') + 1]).expanduser().resolve()
  321. filedir = user_config_dir(appname='qmk', appauthor='QMK')
  322. filename = '%s.ini' % self.prog_name
  323. return Path(filedir) / filename
  324. def get_argument_name(self, *args, **kwargs):
  325. """Takes argparse arguments and returns the dest name.
  326. """
  327. try:
  328. return self._arg_parser._get_optional_kwargs(*args, **kwargs)['dest']
  329. except ValueError:
  330. return self._arg_parser._get_positional_kwargs(*args, **kwargs)['dest']
  331. def argument(self, *args, **kwargs):
  332. """Decorator to call self.add_argument or self.<subcommand>.add_argument.
  333. """
  334. if self._inside_context_manager:
  335. raise RuntimeError('You must run this before the with statement!')
  336. def argument_function(handler):
  337. if 'arg_only' in kwargs and kwargs['arg_only']:
  338. arg_name = self.get_argument_name(*args, **kwargs)
  339. self.arg_only.append(arg_name)
  340. del kwargs['arg_only']
  341. name = handler.__name__.replace("_", "-")
  342. if handler is self._entrypoint:
  343. self.add_argument(*args, **kwargs)
  344. elif name in self.subcommands:
  345. self.subcommands[name].add_argument(*args, **kwargs)
  346. else:
  347. raise RuntimeError('Decorated function is not entrypoint or subcommand!')
  348. return handler
  349. return argument_function
  350. def arg_passed(self, arg):
  351. """Returns True if arg was passed on the command line.
  352. """
  353. return self.default_arguments.get(arg) != self.args[arg]
  354. def parse_args(self):
  355. """Parse the CLI args.
  356. """
  357. if self.args:
  358. self.log.debug('Warning: Arguments have already been parsed, ignoring duplicate attempt!')
  359. return
  360. argcomplete.autocomplete(self._arg_parser)
  361. self.acquire_lock()
  362. self.args = self._arg_parser.parse_args()
  363. if 'entrypoint' in self.args:
  364. self._entrypoint = self.args.entrypoint
  365. self.release_lock()
  366. def read_config_file(self):
  367. """Read in the configuration file and store it in self.config.
  368. """
  369. self.acquire_lock()
  370. self.config = Configuration()
  371. self.config_file = self.find_config_file()
  372. if self.config_file and self.config_file.exists():
  373. config = RawConfigParser(self.config)
  374. config.read(str(self.config_file))
  375. # Iterate over the config file options and write them into self.config
  376. for section in config.sections():
  377. for option in config.options(section):
  378. value = config.get(section, option)
  379. # Coerce values into useful datatypes
  380. if value.lower() in ['1', 'yes', 'true', 'on']:
  381. value = True
  382. elif value.lower() in ['0', 'no', 'false', 'off']:
  383. value = False
  384. elif value.lower() in ['none']:
  385. continue
  386. elif value.replace('.', '').isdigit():
  387. if '.' in value:
  388. value = Decimal(value)
  389. else:
  390. value = int(value)
  391. self.config[section][option] = value
  392. self.release_lock()
  393. def merge_args_into_config(self):
  394. """Merge CLI arguments into self.config to create the runtime configuration.
  395. """
  396. self.acquire_lock()
  397. for argument in vars(self.args):
  398. if argument in ('subparsers', 'entrypoint'):
  399. continue
  400. if argument not in self.arg_only:
  401. # Find the argument's section
  402. if self._entrypoint.__name__ in self.default_arguments and argument in self.default_arguments[self._entrypoint.__name__]:
  403. argument_found = True
  404. section = self._entrypoint.__name__
  405. if argument in self.default_arguments['general']:
  406. argument_found = True
  407. section = 'general'
  408. if not argument_found:
  409. raise RuntimeError('Could not find argument in `self.default_arguments`. This should be impossible!')
  410. exit(1)
  411. # Merge this argument into self.config
  412. if argument in self.default_arguments:
  413. arg_value = getattr(self.args, argument)
  414. if arg_value:
  415. self.config[section][argument] = arg_value
  416. else:
  417. if argument not in self.config[section]:
  418. self.config[section][argument] = getattr(self.args, argument)
  419. self.release_lock()
  420. def save_config(self):
  421. """Save the current configuration to the config file.
  422. """
  423. self.log.debug("Saving config file to '%s'", str(self.config_file))
  424. if not self.config_file:
  425. self.log.warning('%s.config_file file not set, not saving config!', self.__class__.__name__)
  426. return
  427. self.acquire_lock()
  428. # Generate a sanitized version of our running configuration
  429. config = RawConfigParser()
  430. for section_name, section in self.config._config.items():
  431. config.add_section(section_name)
  432. for option_name, value in section.items():
  433. if section_name == 'general':
  434. if option_name in ['config_file']:
  435. continue
  436. if value is not None:
  437. config.set(section_name, option_name, str(value))
  438. # Write out the config file
  439. config_dir = self.config_file.parent
  440. if not config_dir.exists():
  441. config_dir.mkdir(parents=True, exist_ok=True)
  442. with NamedTemporaryFile(mode='w', dir=str(config_dir), delete=False) as tmpfile:
  443. config.write(tmpfile)
  444. # Move the new config file into place atomically
  445. if os.path.getsize(tmpfile.name) > 0:
  446. os.rename(tmpfile.name, str(self.config_file))
  447. else:
  448. self.log.warning('Config file saving failed, not replacing %s with %s.', str(self.config_file), tmpfile.name)
  449. # Housekeeping
  450. self.release_lock()
  451. cli.log.info('Wrote configuration to %s', shlex.quote(str(self.config_file)))
  452. def __call__(self):
  453. """Execute the entrypoint function.
  454. """
  455. if not self._inside_context_manager:
  456. # If they didn't use the context manager use it ourselves
  457. with self:
  458. return self.__call__()
  459. if not self._entrypoint:
  460. raise RuntimeError('No entrypoint provided!')
  461. return self._entrypoint(self)
  462. def entrypoint(self, description):
  463. """Set the entrypoint for when no subcommand is provided.
  464. """
  465. if self._inside_context_manager:
  466. raise RuntimeError('You must run this before cli()!')
  467. self.acquire_lock()
  468. self.description = description
  469. self.release_lock()
  470. def entrypoint_func(handler):
  471. self.acquire_lock()
  472. self._entrypoint = handler
  473. self.release_lock()
  474. return handler
  475. return entrypoint_func
  476. def add_subcommand(self, handler, description, name=None, **kwargs):
  477. """Register a subcommand.
  478. If name is not provided we use `handler.__name__`.
  479. """
  480. if self._inside_context_manager:
  481. raise RuntimeError('You must run this before the with statement!')
  482. if self._subparsers is None:
  483. self.add_subparsers()
  484. if not name:
  485. name = handler.__name__.replace("_", "-")
  486. self.acquire_lock()
  487. kwargs['help'] = description
  488. self.subcommands[name] = SubparserWrapper(self, name, self._subparsers.add_parser(name, **kwargs))
  489. self.subcommands[name].set_defaults(entrypoint=handler)
  490. self.release_lock()
  491. return handler
  492. def subcommand(self, description, **kwargs):
  493. """Decorator to register a subcommand.
  494. """
  495. def subcommand_function(handler):
  496. return self.add_subcommand(handler, description, **kwargs)
  497. return subcommand_function
  498. def setup_logging(self):
  499. """Called by __enter__() to setup the logging configuration.
  500. """
  501. if len(logging.root.handlers) != 0:
  502. # MILC is the only thing that should have root log handlers
  503. logging.root.handlers = []
  504. self.acquire_lock()
  505. if self.config['general']['verbose']:
  506. self.log_print_level = logging.DEBUG
  507. self.log_file = self.config['general']['log_file'] or self.log_file
  508. self.log_file_format = self.config['general']['log_file_fmt']
  509. self.log_file_format = ANSIStrippingFormatter(self.config['general']['log_file_fmt'], self.config['general']['datetime_fmt'])
  510. self.log_format = self.config['general']['log_fmt']
  511. if self.config.general.color:
  512. self.log_format = ANSIEmojiLoglevelFormatter(self.args.log_fmt, self.config.general.datetime_fmt)
  513. else:
  514. self.log_format = ANSIStrippingFormatter(self.args.log_fmt, self.config.general.datetime_fmt)
  515. if self.log_file:
  516. self.log_file_handler = logging.FileHandler(self.log_file, self.log_file_mode)
  517. self.log_file_handler.setLevel(self.log_file_level)
  518. self.log_file_handler.setFormatter(self.log_file_format)
  519. logging.root.addHandler(self.log_file_handler)
  520. if self.log_print:
  521. self.log_print_handler = logging.StreamHandler(self.log_print_to)
  522. self.log_print_handler.setLevel(self.log_print_level)
  523. self.log_print_handler.setFormatter(self.log_format)
  524. logging.root.addHandler(self.log_print_handler)
  525. self.release_lock()
  526. def __enter__(self):
  527. if self._inside_context_manager:
  528. self.log.debug('Warning: context manager was entered again. This usually means that self.__call__() was called before the with statement. You probably do not want to do that.')
  529. return
  530. self.acquire_lock()
  531. self._inside_context_manager = True
  532. self.release_lock()
  533. colorama.init()
  534. self.parse_args()
  535. self.merge_args_into_config()
  536. self.setup_logging()
  537. return self
  538. def __exit__(self, exc_type, exc_val, exc_tb):
  539. self.acquire_lock()
  540. self._inside_context_manager = False
  541. self.release_lock()
  542. if exc_type is not None and not isinstance(SystemExit(), exc_type):
  543. print(exc_type)
  544. logging.exception(exc_val)
  545. exit(255)
  546. cli = MILC()
  547. if __name__ == '__main__':
  548. @cli.argument('-c', '--comma', help='comma in output', default=True, action='store_boolean')
  549. @cli.entrypoint('My useful CLI tool with subcommands.')
  550. def main(cli):
  551. comma = ',' if cli.config.general.comma else ''
  552. cli.log.info('{bg_green}{fg_red}Hello%s World!', comma)
  553. @cli.argument('-n', '--name', help='Name to greet', default='World')
  554. @cli.subcommand('Description of hello subcommand here.')
  555. def hello(cli):
  556. comma = ',' if cli.config.general.comma else ''
  557. cli.log.info('{fg_blue}Hello%s %s!', comma, cli.config.hello.name)
  558. def goodbye(cli):
  559. comma = ',' if cli.config.general.comma else ''
  560. cli.log.info('{bg_red}Goodbye%s %s!', comma, cli.config.goodbye.name)
  561. @cli.argument('-n', '--name', help='Name to greet', default='World')
  562. @cli.subcommand('Think a bit before greeting the user.')
  563. def thinking(cli):
  564. comma = ',' if cli.config.general.comma else ''
  565. spinner = cli.spinner(text='Just a moment...', spinner='earth')
  566. spinner.start()
  567. sleep(2)
  568. spinner.stop()
  569. with cli.spinner(text='Almost there!', spinner='moon'):
  570. sleep(2)
  571. cli.log.info('{fg_cyan}Hello%s %s!', comma, cli.config.thinking.name)
  572. @cli.subcommand('Show off our ANSI colors.')
  573. def pride(cli):
  574. cli.echo('{bg_red} ')
  575. cli.echo('{bg_lightred_ex} ')
  576. cli.echo('{bg_lightyellow_ex} ')
  577. cli.echo('{bg_green} ')
  578. cli.echo('{bg_blue} ')
  579. cli.echo('{bg_magenta} ')
  580. # You can register subcommands using decorators as seen above, or using functions like like this:
  581. cli.add_subcommand(goodbye, 'This will show up in --help output.')
  582. cli.goodbye.add_argument('-n', '--name', help='Name to bid farewell to', default='World')
  583. cli() # Automatically picks between main(), hello() and goodbye()