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.

termcolors.py 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. """
  2. termcolors.py
  3. """
  4. color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
  5. foreground = {color_names[x]: '3%s' % x for x in range(8)}
  6. background = {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. Return 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. Return 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.items():
  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 = '%s\x1b[%sm' % (text or '', RESET)
  46. return '%s%s' % (('\x1b[%sm' % ';'.join(code_list)), text or '')
  47. def make_style(opts=(), **kwargs):
  48. """
  49. Return 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. 'SUCCESS': {},
  64. 'WARNING': {},
  65. 'NOTICE': {},
  66. 'SQL_FIELD': {},
  67. 'SQL_COLTYPE': {},
  68. 'SQL_KEYWORD': {},
  69. 'SQL_TABLE': {},
  70. 'HTTP_INFO': {},
  71. 'HTTP_SUCCESS': {},
  72. 'HTTP_REDIRECT': {},
  73. 'HTTP_NOT_MODIFIED': {},
  74. 'HTTP_BAD_REQUEST': {},
  75. 'HTTP_NOT_FOUND': {},
  76. 'HTTP_SERVER_ERROR': {},
  77. 'MIGRATE_HEADING': {},
  78. 'MIGRATE_LABEL': {},
  79. },
  80. DARK_PALETTE: {
  81. 'ERROR': {'fg': 'red', 'opts': ('bold',)},
  82. 'SUCCESS': {'fg': 'green', 'opts': ('bold',)},
  83. 'WARNING': {'fg': 'yellow', 'opts': ('bold',)},
  84. 'NOTICE': {'fg': 'red'},
  85. 'SQL_FIELD': {'fg': 'green', 'opts': ('bold',)},
  86. 'SQL_COLTYPE': {'fg': 'green'},
  87. 'SQL_KEYWORD': {'fg': 'yellow'},
  88. 'SQL_TABLE': {'opts': ('bold',)},
  89. 'HTTP_INFO': {'opts': ('bold',)},
  90. 'HTTP_SUCCESS': {},
  91. 'HTTP_REDIRECT': {'fg': 'green'},
  92. 'HTTP_NOT_MODIFIED': {'fg': 'cyan'},
  93. 'HTTP_BAD_REQUEST': {'fg': 'red', 'opts': ('bold',)},
  94. 'HTTP_NOT_FOUND': {'fg': 'yellow'},
  95. 'HTTP_SERVER_ERROR': {'fg': 'magenta', 'opts': ('bold',)},
  96. 'MIGRATE_HEADING': {'fg': 'cyan', 'opts': ('bold',)},
  97. 'MIGRATE_LABEL': {'opts': ('bold',)},
  98. },
  99. LIGHT_PALETTE: {
  100. 'ERROR': {'fg': 'red', 'opts': ('bold',)},
  101. 'SUCCESS': {'fg': 'green', 'opts': ('bold',)},
  102. 'WARNING': {'fg': 'yellow', 'opts': ('bold',)},
  103. 'NOTICE': {'fg': 'red'},
  104. 'SQL_FIELD': {'fg': 'green', 'opts': ('bold',)},
  105. 'SQL_COLTYPE': {'fg': 'green'},
  106. 'SQL_KEYWORD': {'fg': 'blue'},
  107. 'SQL_TABLE': {'opts': ('bold',)},
  108. 'HTTP_INFO': {'opts': ('bold',)},
  109. 'HTTP_SUCCESS': {},
  110. 'HTTP_REDIRECT': {'fg': 'green', 'opts': ('bold',)},
  111. 'HTTP_NOT_MODIFIED': {'fg': 'green'},
  112. 'HTTP_BAD_REQUEST': {'fg': 'red', 'opts': ('bold',)},
  113. 'HTTP_NOT_FOUND': {'fg': 'red'},
  114. 'HTTP_SERVER_ERROR': {'fg': 'magenta', 'opts': ('bold',)},
  115. 'MIGRATE_HEADING': {'fg': 'cyan', 'opts': ('bold',)},
  116. 'MIGRATE_LABEL': {'opts': ('bold',)},
  117. }
  118. }
  119. DEFAULT_PALETTE = DARK_PALETTE
  120. def parse_color_setting(config_string):
  121. """Parse a DJANGO_COLORS environment variable to produce the system palette
  122. The general form of a palette definition is:
  123. "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option"
  124. where:
  125. palette is a named palette; one of 'light', 'dark', or 'nocolor'.
  126. role is a named style used by Django
  127. fg is a background color.
  128. bg is a background color.
  129. option is a display options.
  130. Specifying a named palette is the same as manually specifying the individual
  131. definitions for each role. Any individual definitions following the palette
  132. definition will augment the base palette definition.
  133. Valid roles:
  134. 'error', 'success', 'warning', 'notice', 'sql_field', 'sql_coltype',
  135. 'sql_keyword', 'sql_table', 'http_info', 'http_success',
  136. 'http_redirect', 'http_not_modified', 'http_bad_request',
  137. 'http_not_found', 'http_server_error', 'migrate_heading',
  138. 'migrate_label'
  139. Valid colors:
  140. 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
  141. Valid options:
  142. 'bold', 'underscore', 'blink', 'reverse', 'conceal', 'noreset'
  143. """
  144. if not config_string:
  145. return PALETTES[DEFAULT_PALETTE]
  146. # Split the color configuration into parts
  147. parts = config_string.lower().split(';')
  148. palette = PALETTES[NOCOLOR_PALETTE].copy()
  149. for part in parts:
  150. if part in PALETTES:
  151. # A default palette has been specified
  152. palette.update(PALETTES[part])
  153. elif '=' in part:
  154. # Process a palette defining string
  155. definition = {}
  156. # Break the definition into the role,
  157. # plus the list of specific instructions.
  158. # The role must be in upper case
  159. role, instructions = part.split('=')
  160. role = role.upper()
  161. styles = instructions.split(',')
  162. styles.reverse()
  163. # The first instruction can contain a slash
  164. # to break apart fg/bg.
  165. colors = styles.pop().split('/')
  166. colors.reverse()
  167. fg = colors.pop()
  168. if fg in color_names:
  169. definition['fg'] = fg
  170. if colors and colors[-1] in color_names:
  171. definition['bg'] = colors[-1]
  172. # All remaining instructions are options
  173. opts = tuple(s for s in styles if s in opt_dict)
  174. if opts:
  175. definition['opts'] = opts
  176. # The nocolor palette has all available roles.
  177. # Use that palette as the basis for determining
  178. # if the role is valid.
  179. if role in PALETTES[NOCOLOR_PALETTE] and definition:
  180. palette[role] = definition
  181. # If there are no colors specified, return the empty palette.
  182. if palette == PALETTES[NOCOLOR_PALETTE]:
  183. return None
  184. return palette