2
0

milc.py 24 KB

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