milc.py 25 KB

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