termcolors.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. """
  2. termcolors.py
  3. """
  4. color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
  5. foreground = dict([(color_names[x], '3%s' % x) for x in range(8)])
  6. background = dict([(color_names[x], '4%s' % x) for x in range(8)])
  7. RESET = '0'
  8. opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}
  9. def colorize(text='', opts=(), **kwargs):
  10. """
  11. Returns your text, enclosed in ANSI graphics codes.
  12. Depends on the keyword arguments 'fg' and 'bg', and the contents of
  13. the opts tuple/list.
  14. Returns the RESET code if no parameters are given.
  15. Valid colors:
  16. 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
  17. Valid options:
  18. 'bold'
  19. 'underscore'
  20. 'blink'
  21. 'reverse'
  22. 'conceal'
  23. 'noreset' - string will not be auto-terminated with the RESET code
  24. Examples:
  25. colorize('hello', fg='red', bg='blue', opts=('blink',))
  26. colorize()
  27. colorize('goodbye', opts=('underscore',))
  28. print(colorize('first line', fg='red', opts=('noreset',)))
  29. print('this should be red too')
  30. print(colorize('and so should this'))
  31. print('this should not be red')
  32. """
  33. code_list = []
  34. if text == '' and len(opts) == 1 and opts[0] == 'reset':
  35. return '\x1b[%sm' % RESET
  36. for k, v in kwargs.iteritems():
  37. if k == 'fg':
  38. code_list.append(foreground[v])
  39. elif k == 'bg':
  40. code_list.append(background[v])
  41. for o in opts:
  42. if o in opt_dict:
  43. code_list.append(opt_dict[o])
  44. if 'noreset' not in opts:
  45. text = text + '\x1b[%sm' % RESET
  46. return ('\x1b[%sm' % ';'.join(code_list)) + text
  47. def make_style(opts=(), **kwargs):
  48. """
  49. Returns a function with default parameters for colorize()
  50. Example:
  51. bold_red = make_style(opts=('bold',), fg='red')
  52. print(bold_red('hello'))
  53. KEYWORD = make_style(fg='yellow')
  54. COMMENT = make_style(fg='blue', opts=('bold',))
  55. """
  56. return lambda text: colorize(text, opts, **kwargs)
  57. NOCOLOR_PALETTE = 'nocolor'
  58. DARK_PALETTE = 'dark'
  59. LIGHT_PALETTE = 'light'
  60. PALETTES = {
  61. NOCOLOR_PALETTE: {
  62. 'ERROR': {},
  63. 'NOTICE': {},
  64. 'SQL_FIELD': {},
  65. 'SQL_COLTYPE': {},
  66. 'SQL_KEYWORD': {},
  67. 'SQL_TABLE': {},
  68. 'HTTP_INFO': {},
  69. 'HTTP_SUCCESS': {},
  70. 'HTTP_REDIRECT': {},
  71. 'HTTP_NOT_MODIFIED': {},
  72. 'HTTP_BAD_REQUEST': {},
  73. 'HTTP_NOT_FOUND': {},
  74. 'HTTP_SERVER_ERROR': {},
  75. },
  76. DARK_PALETTE: {
  77. 'ERROR': { 'fg': 'red', 'opts': ('bold',) },
  78. 'NOTICE': { 'fg': 'red' },
  79. 'SQL_FIELD': { 'fg': 'green', 'opts': ('bold',) },
  80. 'SQL_COLTYPE': { 'fg': 'green' },
  81. 'SQL_KEYWORD': { 'fg': 'yellow' },
  82. 'SQL_TABLE': { 'opts': ('bold',) },
  83. 'HTTP_INFO': { 'opts': ('bold',) },
  84. 'HTTP_SUCCESS': { },
  85. 'HTTP_REDIRECT': { 'fg': 'green' },
  86. 'HTTP_NOT_MODIFIED': { 'fg': 'cyan' },
  87. 'HTTP_BAD_REQUEST': { 'fg': 'red', 'opts': ('bold',) },
  88. 'HTTP_NOT_FOUND': { 'fg': 'yellow' },
  89. 'HTTP_SERVER_ERROR': { 'fg': 'magenta', 'opts': ('bold',) },
  90. },
  91. LIGHT_PALETTE: {
  92. 'ERROR': { 'fg': 'red', 'opts': ('bold',) },
  93. 'NOTICE': { 'fg': 'red' },
  94. 'SQL_FIELD': { 'fg': 'green', 'opts': ('bold',) },
  95. 'SQL_COLTYPE': { 'fg': 'green' },
  96. 'SQL_KEYWORD': { 'fg': 'blue' },
  97. 'SQL_TABLE': { 'opts': ('bold',) },
  98. 'HTTP_INFO': { 'opts': ('bold',) },
  99. 'HTTP_SUCCESS': { },
  100. 'HTTP_REDIRECT': { 'fg': 'green', 'opts': ('bold',) },
  101. 'HTTP_NOT_MODIFIED': { 'fg': 'green' },
  102. 'HTTP_BAD_REQUEST': { 'fg': 'red', 'opts': ('bold',) },
  103. 'HTTP_NOT_FOUND': { 'fg': 'red' },
  104. 'HTTP_SERVER_ERROR': { 'fg': 'magenta', 'opts': ('bold',) },
  105. }
  106. }
  107. DEFAULT_PALETTE = DARK_PALETTE
  108. def parse_color_setting(config_string):
  109. """Parse a DJANGO_COLORS environment variable to produce the system palette
  110. The general form of a pallete definition is:
  111. "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option"
  112. where:
  113. palette is a named palette; one of 'light', 'dark', or 'nocolor'.
  114. role is a named style used by Django
  115. fg is a background color.
  116. bg is a background color.
  117. option is a display options.
  118. Specifying a named palette is the same as manually specifying the individual
  119. definitions for each role. Any individual definitions following the pallete
  120. definition will augment the base palette definition.
  121. Valid roles:
  122. 'error', 'notice', 'sql_field', 'sql_coltype', 'sql_keyword', 'sql_table',
  123. 'http_info', 'http_success', 'http_redirect', 'http_bad_request',
  124. 'http_not_found', 'http_server_error'
  125. Valid colors:
  126. 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
  127. Valid options:
  128. 'bold', 'underscore', 'blink', 'reverse', 'conceal'
  129. """
  130. if not config_string:
  131. return PALETTES[DEFAULT_PALETTE]
  132. # Split the color configuration into parts
  133. parts = config_string.lower().split(';')
  134. palette = PALETTES[NOCOLOR_PALETTE].copy()
  135. for part in parts:
  136. if part in PALETTES:
  137. # A default palette has been specified
  138. palette.update(PALETTES[part])
  139. elif '=' in part:
  140. # Process a palette defining string
  141. definition = {}
  142. # Break the definition into the role,
  143. # plus the list of specific instructions.
  144. # The role must be in upper case
  145. role, instructions = part.split('=')
  146. role = role.upper()
  147. styles = instructions.split(',')
  148. styles.reverse()
  149. # The first instruction can contain a slash
  150. # to break apart fg/bg.
  151. colors = styles.pop().split('/')
  152. colors.reverse()
  153. fg = colors.pop()
  154. if fg in color_names:
  155. definition['fg'] = fg
  156. if colors and colors[-1] in color_names:
  157. definition['bg'] = colors[-1]
  158. # All remaining instructions are options
  159. opts = tuple(s for s in styles if s in opt_dict.keys())
  160. if opts:
  161. definition['opts'] = opts
  162. # The nocolor palette has all available roles.
  163. # Use that palette as the basis for determining
  164. # if the role is valid.
  165. if role in PALETTES[NOCOLOR_PALETTE] and definition:
  166. palette[role] = definition
  167. # If there are no colors specified, return the empty palette.
  168. if palette == PALETTES[NOCOLOR_PALETTE]:
  169. return None
  170. return palette