milc.py 27 KB

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