milc.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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. This is called when the attribute is accessed either via the get method or through [ ] index.
  145. """
  146. if key in self._config and self._config.get(key) is not None:
  147. return self._config[key]
  148. elif key in self.parent.user:
  149. return self.parent.user[key]
  150. return None
  151. def __getattr__(self, key):
  152. """Returns the config value from the `user` section.
  153. This is called when the attribute is accessed via dot notation but does not exists.
  154. """
  155. if key in self.parent.user:
  156. return self.parent.user[key]
  157. return None
  158. def handle_store_boolean(self, *args, **kwargs):
  159. """Does the add_argument for action='store_boolean'.
  160. """
  161. disabled_args = None
  162. disabled_kwargs = kwargs.copy()
  163. disabled_kwargs['action'] = 'store_false'
  164. disabled_kwargs['dest'] = self.get_argument_name(*args, **kwargs)
  165. disabled_kwargs['help'] = 'Disable ' + kwargs['help']
  166. kwargs['action'] = 'store_true'
  167. kwargs['help'] = 'Enable ' + kwargs['help']
  168. for flag in args:
  169. if flag[:2] == '--':
  170. disabled_args = ('--no-' + flag[2:],)
  171. break
  172. self.add_argument(*args, **kwargs)
  173. self.add_argument(*disabled_args, **disabled_kwargs)
  174. return (args, kwargs, disabled_args, disabled_kwargs)
  175. class SubparserWrapper(object):
  176. """Wrap subparsers so we can track what options the user passed.
  177. """
  178. def __init__(self, cli, submodule, subparser):
  179. self.cli = cli
  180. self.submodule = submodule
  181. self.subparser = subparser
  182. for attr in dir(subparser):
  183. if not hasattr(self, attr):
  184. setattr(self, attr, getattr(subparser, attr))
  185. def completer(self, completer):
  186. """Add an arpcomplete completer to this subcommand.
  187. """
  188. self.subparser.completer = completer
  189. def add_argument(self, *args, **kwargs):
  190. """Add an argument for this subcommand.
  191. This also stores the default for the argument in `self.cli.default_arguments`.
  192. """
  193. if kwargs.get('action') == 'store_boolean':
  194. # Store boolean will call us again with the enable/disable flag arguments
  195. return handle_store_boolean(self, *args, **kwargs)
  196. self.cli.acquire_lock()
  197. argument_name = self.cli.get_argument_name(*args, **kwargs)
  198. self.subparser.add_argument(*args, **kwargs)
  199. if kwargs.get('action') == 'store_false':
  200. self.cli._config_store_false.append(argument_name)
  201. if kwargs.get('action') == 'store_true':
  202. self.cli._config_store_true.append(argument_name)
  203. if self.submodule not in self.cli.default_arguments:
  204. self.cli.default_arguments[self.submodule] = {}
  205. self.cli.default_arguments[self.submodule][argument_name] = kwargs.get('default')
  206. self.cli.release_lock()
  207. class MILC(object):
  208. """MILC - An Opinionated Batteries Included Framework
  209. """
  210. def __init__(self):
  211. """Initialize the MILC object.
  212. version
  213. The version string to associate with your CLI program
  214. """
  215. # Setup a lock for thread safety
  216. self._lock = threading.RLock() if thread else None
  217. # Define some basic info
  218. self.acquire_lock()
  219. self._config_store_true = []
  220. self._config_store_false = []
  221. self._description = None
  222. self._entrypoint = None
  223. self._inside_context_manager = False
  224. self.ansi = ansi_colors
  225. self.arg_only = {}
  226. self.config = self.config_source = None
  227. self.config_file = None
  228. self.default_arguments = {}
  229. self.version = 'unknown'
  230. self.release_lock()
  231. # Figure out our program name
  232. self.prog_name = sys.argv[0][:-3] if sys.argv[0].endswith('.py') else sys.argv[0]
  233. self.prog_name = self.prog_name.split('/')[-1]
  234. # Initialize all the things
  235. self.read_config_file()
  236. self.initialize_argparse()
  237. self.initialize_logging()
  238. @property
  239. def description(self):
  240. return self._description
  241. @description.setter
  242. def description(self, value):
  243. self._description = self._arg_parser.description = value
  244. def echo(self, text, *args, **kwargs):
  245. """Print colorized text to stdout.
  246. ANSI color strings (such as {fg-blue}) will be converted into ANSI
  247. escape sequences, and the ANSI reset sequence will be added to all
  248. strings.
  249. If *args or **kwargs are passed they will be used to %-format the strings.
  250. """
  251. if args and kwargs:
  252. raise RuntimeError('You can only specify *args or **kwargs, not both!')
  253. args = args or kwargs
  254. text = format_ansi(text)
  255. print(text % args)
  256. def initialize_argparse(self):
  257. """Prepare to process arguments from sys.argv.
  258. """
  259. kwargs = {
  260. 'fromfile_prefix_chars': '@',
  261. 'conflict_handler': 'resolve',
  262. }
  263. self.acquire_lock()
  264. self.subcommands = {}
  265. self._subparsers = None
  266. self.argwarn = argcomplete.warn
  267. self.args = None
  268. self._arg_parser = argparse.ArgumentParser(**kwargs)
  269. self.set_defaults = self._arg_parser.set_defaults
  270. self.print_usage = self._arg_parser.print_usage
  271. self.print_help = self._arg_parser.print_help
  272. self.release_lock()
  273. def completer(self, completer):
  274. """Add an argcomplete completer to this subcommand.
  275. """
  276. self._arg_parser.completer = completer
  277. def add_argument(self, *args, **kwargs):
  278. """Wrapper to add arguments and track whether they were passed on the command line.
  279. """
  280. if 'action' in kwargs and kwargs['action'] == 'store_boolean':
  281. return handle_store_boolean(self, *args, **kwargs)
  282. self.acquire_lock()
  283. self._arg_parser.add_argument(*args, **kwargs)
  284. if 'general' not in self.default_arguments:
  285. self.default_arguments['general'] = {}
  286. self.default_arguments['general'][self.get_argument_name(*args, **kwargs)] = kwargs.get('default')
  287. self.release_lock()
  288. def initialize_logging(self):
  289. """Prepare the defaults for the logging infrastructure.
  290. """
  291. self.acquire_lock()
  292. self.log_file = None
  293. self.log_file_mode = 'a'
  294. self.log_file_handler = None
  295. self.log_print = True
  296. self.log_print_to = sys.stderr
  297. self.log_print_level = logging.INFO
  298. self.log_file_level = logging.DEBUG
  299. self.log_level = logging.INFO
  300. self.log = logging.getLogger(self.__class__.__name__)
  301. self.log.setLevel(logging.DEBUG)
  302. logging.root.setLevel(logging.DEBUG)
  303. self.release_lock()
  304. self.add_argument('-V', '--version', version=self.version, action='version', help='Display the version and exit')
  305. self.add_argument('-v', '--verbose', action='store_true', help='Make the logging more verbose')
  306. self.add_argument('--datetime-fmt', default='%Y-%m-%d %H:%M:%S', help='Format string for datetimes')
  307. self.add_argument('--log-fmt', default='%(levelname)s %(message)s', help='Format string for printed log output')
  308. 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.')
  309. self.add_argument('--log-file', help='File to write log messages to')
  310. self.add_argument('--color', action='store_boolean', default=True, help='color in output')
  311. self.add_argument('--config-file', help='The location for the configuration file')
  312. self.arg_only['config_file'] = ['general']
  313. def add_subparsers(self, title='Sub-commands', **kwargs):
  314. if self._inside_context_manager:
  315. raise RuntimeError('You must run this before the with statement!')
  316. self.acquire_lock()
  317. self._subparsers = self._arg_parser.add_subparsers(title=title, dest='subparsers', **kwargs)
  318. self.release_lock()
  319. def acquire_lock(self):
  320. """Acquire the MILC lock for exclusive access to properties.
  321. """
  322. if self._lock:
  323. self._lock.acquire()
  324. def release_lock(self):
  325. """Release the MILC lock.
  326. """
  327. if self._lock:
  328. self._lock.release()
  329. def find_config_file(self):
  330. """Locate the config file.
  331. """
  332. if self.config_file:
  333. return self.config_file
  334. if '--config-file' in sys.argv:
  335. return Path(sys.argv[sys.argv.index('--config-file') + 1]).expanduser().resolve()
  336. filedir = user_config_dir(appname='qmk', appauthor='QMK')
  337. filename = '%s.ini' % self.prog_name
  338. return Path(filedir) / filename
  339. def get_argument_name(self, *args, **kwargs):
  340. """Takes argparse arguments and returns the dest name.
  341. """
  342. try:
  343. return self._arg_parser._get_optional_kwargs(*args, **kwargs)['dest']
  344. except ValueError:
  345. return self._arg_parser._get_positional_kwargs(*args, **kwargs)['dest']
  346. def argument(self, *args, **kwargs):
  347. """Decorator to call self.add_argument or self.<subcommand>.add_argument.
  348. """
  349. if self._inside_context_manager:
  350. raise RuntimeError('You must run this before the with statement!')
  351. def argument_function(handler):
  352. subcommand_name = handler.__name__.replace("_", "-")
  353. if kwargs.get('arg_only'):
  354. arg_name = self.get_argument_name(*args, **kwargs)
  355. if arg_name not in self.arg_only:
  356. self.arg_only[arg_name] = []
  357. self.arg_only[arg_name].append(subcommand_name)
  358. del kwargs['arg_only']
  359. if handler is self._entrypoint:
  360. self.add_argument(*args, **kwargs)
  361. elif subcommand_name in self.subcommands:
  362. self.subcommands[subcommand_name].add_argument(*args, **kwargs)
  363. else:
  364. raise RuntimeError('Decorated function is not entrypoint or subcommand!')
  365. return handler
  366. return argument_function
  367. def arg_passed(self, arg):
  368. """Returns True if arg was passed on the command line.
  369. """
  370. return self.default_arguments.get(arg) != self.args[arg]
  371. def parse_args(self):
  372. """Parse the CLI args.
  373. """
  374. if self.args:
  375. self.log.debug('Warning: Arguments have already been parsed, ignoring duplicate attempt!')
  376. return
  377. argcomplete.autocomplete(self._arg_parser)
  378. self.acquire_lock()
  379. self.args = self._arg_parser.parse_args()
  380. if 'entrypoint' in self.args:
  381. self._entrypoint = self.args.entrypoint
  382. self.release_lock()
  383. def read_config_file(self):
  384. """Read in the configuration file and store it in self.config.
  385. """
  386. self.acquire_lock()
  387. self.config = Configuration()
  388. self.config_source = Configuration()
  389. self.config_file = self.find_config_file()
  390. if self.config_file and self.config_file.exists():
  391. config = RawConfigParser(self.config)
  392. config.read(str(self.config_file))
  393. # Iterate over the config file options and write them into self.config
  394. for section in config.sections():
  395. for option in config.options(section):
  396. value = config.get(section, option)
  397. # Coerce values into useful datatypes
  398. if value.lower() in ['1', 'yes', 'true', 'on']:
  399. value = True
  400. elif value.lower() in ['0', 'no', 'false', 'off']:
  401. value = False
  402. elif value.lower() in ['none']:
  403. continue
  404. elif value.replace('.', '').isdigit():
  405. if '.' in value:
  406. value = Decimal(value)
  407. else:
  408. value = int(value)
  409. self.config[section][option] = value
  410. self.config_source[section][option] = 'config_file'
  411. self.release_lock()
  412. def merge_args_into_config(self):
  413. """Merge CLI arguments into self.config to create the runtime configuration.
  414. """
  415. self.acquire_lock()
  416. for argument in vars(self.args):
  417. if argument in ('subparsers', 'entrypoint'):
  418. continue
  419. # Find the argument's section
  420. # Underscores in command's names are converted to dashes during initialization.
  421. # TODO(Erovia) Find a better solution
  422. entrypoint_name = self._entrypoint.__name__.replace("_", "-")
  423. if entrypoint_name in self.default_arguments and argument in self.default_arguments[entrypoint_name]:
  424. argument_found = True
  425. section = self._entrypoint.__name__
  426. if argument in self.default_arguments['general']:
  427. argument_found = True
  428. section = 'general'
  429. if not argument_found:
  430. raise RuntimeError('Could not find argument in `self.default_arguments`. This should be impossible!')
  431. exit(1)
  432. if argument not in self.arg_only or section not in self.arg_only[argument]:
  433. # Determine the arg value and source
  434. arg_value = getattr(self.args, argument)
  435. if argument in self._config_store_true and arg_value:
  436. passed_on_cmdline = True
  437. elif argument in self._config_store_false and not arg_value:
  438. passed_on_cmdline = True
  439. elif arg_value is not None:
  440. passed_on_cmdline = True
  441. else:
  442. passed_on_cmdline = False
  443. # Merge this argument into self.config
  444. if passed_on_cmdline and (argument in self.default_arguments['general'] or argument in self.default_arguments[entrypoint_name] or argument not in self.config[entrypoint_name]):
  445. self.config[section][argument] = arg_value
  446. self.config_source[section][argument] = 'argument'
  447. self.release_lock()
  448. def save_config(self):
  449. """Save the current configuration to the config file.
  450. """
  451. self.log.debug("Saving config file to '%s'", str(self.config_file))
  452. if not self.config_file:
  453. self.log.warning('%s.config_file file not set, not saving config!', self.__class__.__name__)
  454. return
  455. self.acquire_lock()
  456. # Generate a sanitized version of our running configuration
  457. config = RawConfigParser()
  458. for section_name, section in self.config._config.items():
  459. config.add_section(section_name)
  460. for option_name, value in section.items():
  461. if section_name == 'general':
  462. if option_name in ['config_file']:
  463. continue
  464. if value is not None:
  465. config.set(section_name, option_name, str(value))
  466. # Write out the config file
  467. config_dir = self.config_file.parent
  468. if not config_dir.exists():
  469. config_dir.mkdir(parents=True, exist_ok=True)
  470. with NamedTemporaryFile(mode='w', dir=str(config_dir), delete=False) as tmpfile:
  471. config.write(tmpfile)
  472. # Move the new config file into place atomically
  473. if os.path.getsize(tmpfile.name) > 0:
  474. os.replace(tmpfile.name, str(self.config_file))
  475. else:
  476. self.log.warning('Config file saving failed, not replacing %s with %s.', str(self.config_file), tmpfile.name)
  477. # Housekeeping
  478. self.release_lock()
  479. cli.log.info('Wrote configuration to %s', shlex.quote(str(self.config_file)))
  480. def __call__(self):
  481. """Execute the entrypoint function.
  482. """
  483. if not self._inside_context_manager:
  484. # If they didn't use the context manager use it ourselves
  485. with self:
  486. return self.__call__()
  487. if not self._entrypoint:
  488. raise RuntimeError('No entrypoint provided!')
  489. return self._entrypoint(self)
  490. def entrypoint(self, description):
  491. """Set the entrypoint for when no subcommand is provided.
  492. """
  493. if self._inside_context_manager:
  494. raise RuntimeError('You must run this before cli()!')
  495. self.acquire_lock()
  496. self.description = description
  497. self.release_lock()
  498. def entrypoint_func(handler):
  499. self.acquire_lock()
  500. self._entrypoint = handler
  501. self.release_lock()
  502. return handler
  503. return entrypoint_func
  504. def add_subcommand(self, handler, description, name=None, hidden=False, **kwargs):
  505. """Register a subcommand.
  506. If name is not provided we use `handler.__name__`.
  507. """
  508. if self._inside_context_manager:
  509. raise RuntimeError('You must run this before the with statement!')
  510. if self._subparsers is None:
  511. self.add_subparsers(metavar="")
  512. if not name:
  513. name = handler.__name__.replace("_", "-")
  514. self.acquire_lock()
  515. if not hidden:
  516. self._subparsers.metavar = "{%s,%s}" % (self._subparsers.metavar[1:-1], name) if self._subparsers.metavar else "{%s%s}" % (self._subparsers.metavar[1:-1], name)
  517. kwargs['help'] = description
  518. self.subcommands[name] = SubparserWrapper(self, name, self._subparsers.add_parser(name, **kwargs))
  519. self.subcommands[name].set_defaults(entrypoint=handler)
  520. self.release_lock()
  521. return handler
  522. def subcommand(self, description, hidden=False, **kwargs):
  523. """Decorator to register a subcommand.
  524. """
  525. def subcommand_function(handler):
  526. return self.add_subcommand(handler, description, hidden=hidden, **kwargs)
  527. return subcommand_function
  528. def setup_logging(self):
  529. """Called by __enter__() to setup the logging configuration.
  530. """
  531. if len(logging.root.handlers) != 0:
  532. # MILC is the only thing that should have root log handlers
  533. logging.root.handlers = []
  534. self.acquire_lock()
  535. if self.config['general']['verbose']:
  536. self.log_print_level = logging.DEBUG
  537. self.log_file = self.config['general']['log_file'] or self.log_file
  538. self.log_file_format = self.config['general']['log_file_fmt']
  539. self.log_file_format = ANSIStrippingFormatter(self.config['general']['log_file_fmt'], self.config['general']['datetime_fmt'])
  540. self.log_format = self.config['general']['log_fmt']
  541. if self.config.general.color:
  542. self.log_format = ANSIEmojiLoglevelFormatter(self.args.log_fmt, self.config.general.datetime_fmt)
  543. else:
  544. self.log_format = ANSIStrippingFormatter(self.args.log_fmt, self.config.general.datetime_fmt)
  545. if self.log_file:
  546. self.log_file_handler = logging.FileHandler(self.log_file, self.log_file_mode)
  547. self.log_file_handler.setLevel(self.log_file_level)
  548. self.log_file_handler.setFormatter(self.log_file_format)
  549. logging.root.addHandler(self.log_file_handler)
  550. if self.log_print:
  551. self.log_print_handler = logging.StreamHandler(self.log_print_to)
  552. self.log_print_handler.setLevel(self.log_print_level)
  553. self.log_print_handler.setFormatter(self.log_format)
  554. logging.root.addHandler(self.log_print_handler)
  555. self.release_lock()
  556. def __enter__(self):
  557. if self._inside_context_manager:
  558. 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.')
  559. return
  560. self.acquire_lock()
  561. self._inside_context_manager = True
  562. self.release_lock()
  563. colorama.init()
  564. self.parse_args()
  565. self.merge_args_into_config()
  566. self.setup_logging()
  567. return self
  568. def __exit__(self, exc_type, exc_val, exc_tb):
  569. self.acquire_lock()
  570. self._inside_context_manager = False
  571. self.release_lock()
  572. if exc_type is not None and not isinstance(SystemExit(), exc_type):
  573. print(exc_type)
  574. logging.exception(exc_val)
  575. exit(255)
  576. cli = MILC()
  577. if __name__ == '__main__':
  578. @cli.argument('-c', '--comma', help='comma in output', default=True, action='store_boolean')
  579. @cli.entrypoint('My useful CLI tool with subcommands.')
  580. def main(cli):
  581. comma = ',' if cli.config.general.comma else ''
  582. cli.log.info('{bg_green}{fg_red}Hello%s World!', comma)
  583. @cli.argument('-n', '--name', help='Name to greet', default='World')
  584. @cli.subcommand('Description of hello subcommand here.')
  585. def hello(cli):
  586. comma = ',' if cli.config.general.comma else ''
  587. cli.log.info('{fg_blue}Hello%s %s!', comma, cli.config.hello.name)
  588. def goodbye(cli):
  589. comma = ',' if cli.config.general.comma else ''
  590. cli.log.info('{bg_red}Goodbye%s %s!', comma, cli.config.goodbye.name)
  591. @cli.argument('-n', '--name', help='Name to greet', default='World')
  592. @cli.subcommand('Think a bit before greeting the user.')
  593. def thinking(cli):
  594. comma = ',' if cli.config.general.comma else ''
  595. spinner = cli.spinner(text='Just a moment...', spinner='earth')
  596. spinner.start()
  597. sleep(2)
  598. spinner.stop()
  599. with cli.spinner(text='Almost there!', spinner='moon'):
  600. sleep(2)
  601. cli.log.info('{fg_cyan}Hello%s %s!', comma, cli.config.thinking.name)
  602. @cli.subcommand('Show off our ANSI colors.')
  603. def pride(cli):
  604. cli.echo('{bg_red} ')
  605. cli.echo('{bg_lightred_ex} ')
  606. cli.echo('{bg_lightyellow_ex} ')
  607. cli.echo('{bg_green} ')
  608. cli.echo('{bg_blue} ')
  609. cli.echo('{bg_magenta} ')
  610. # You can register subcommands using decorators as seen above, or using functions like like this:
  611. cli.add_subcommand(goodbye, 'This will show up in --help output.')
  612. cli.goodbye.add_argument('-n', '--name', help='Name to bid farewell to', default='World')
  613. cli() # Automatically picks between main(), hello() and goodbye()