1
0

utils.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # -*- coding: utf-8 -*-
  2. """
  3. tasks.utils
  4. ~~~~~~~~~~~
  5. Invoke utilities
  6. """
  7. import sys
  8. try:
  9. from blessings import Terminal
  10. try:
  11. terminal = Terminal()
  12. HAS_BLESSINGS = True
  13. except Exception: # pylint: disable=broad-except
  14. # When we fail to instantiate the terminal because of curses
  15. terminal = None
  16. HAS_BLESSINGS = True
  17. except ImportError:
  18. terminal = None
  19. HAS_BLESSINGS = False
  20. def exit_invoke(exitcode, message=None, *args, **kwargs):
  21. if message is not None:
  22. if exitcode > 0:
  23. warn(message, *args, **kwargs)
  24. else:
  25. info(message, *args, **kwargs)
  26. sys.exit(exitcode)
  27. def info(message, *args, **kwargs):
  28. if not isinstance(message, str):
  29. message = str(message)
  30. message = message.format(*args, **kwargs)
  31. if terminal:
  32. message = terminal.bold(terminal.green(message))
  33. write_message(message)
  34. def warn(message, *args, **kwargs):
  35. if not isinstance(message, str):
  36. message = str(message)
  37. message = message.format(*args, **kwargs)
  38. if terminal:
  39. message = terminal.bold(terminal.yellow(message))
  40. write_message(message)
  41. def error(message, *args, **kwargs):
  42. if not isinstance(message, str):
  43. message = str(message)
  44. message = message.format(*args, **kwargs)
  45. if terminal:
  46. message = terminal.bold(terminal.red(message))
  47. write_message(message)
  48. def write_message(message):
  49. sys.stderr.write(message)
  50. if not message.endswith("\n"):
  51. sys.stderr.write("\n")
  52. sys.stderr.flush()