You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

color.py 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. Sets up the terminal color scheme.
  3. """
  4. import functools
  5. import os
  6. import sys
  7. from django.utils import termcolors
  8. def supports_color():
  9. """
  10. Return True if the running system's terminal supports color,
  11. and False otherwise.
  12. """
  13. plat = sys.platform
  14. supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
  15. # isatty is not always implemented, #6223.
  16. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
  17. return supported_platform and is_a_tty
  18. class Style:
  19. pass
  20. def make_style(config_string=''):
  21. """
  22. Create a Style object from the given config_string.
  23. If config_string is empty django.utils.termcolors.DEFAULT_PALETTE is used.
  24. """
  25. style = Style()
  26. color_settings = termcolors.parse_color_setting(config_string)
  27. # The nocolor palette has all available roles.
  28. # Use that palette as the basis for populating
  29. # the palette as defined in the environment.
  30. for role in termcolors.PALETTES[termcolors.NOCOLOR_PALETTE]:
  31. if color_settings:
  32. format = color_settings.get(role, {})
  33. style_func = termcolors.make_style(**format)
  34. else:
  35. def style_func(x):
  36. return x
  37. setattr(style, role, style_func)
  38. # For backwards compatibility,
  39. # set style for ERROR_OUTPUT == ERROR
  40. style.ERROR_OUTPUT = style.ERROR
  41. return style
  42. @functools.lru_cache(maxsize=None)
  43. def no_style():
  44. """
  45. Return a Style object with no color scheme.
  46. """
  47. return make_style('nocolor')
  48. def color_style(force_color=False):
  49. """
  50. Return a Style object from the Django color scheme.
  51. """
  52. if not force_color and not supports_color():
  53. return no_style()
  54. return make_style(os.environ.get('DJANGO_COLORS', ''))