2012-03-02 03:39:22 +03:00
|
|
|
import os
|
2012-02-25 15:39:38 +03:00
|
|
|
import json
|
|
|
|
import pygments
|
2012-03-02 03:39:22 +03:00
|
|
|
from pygments import token
|
|
|
|
from pygments.util import ClassNotFound
|
2012-04-26 14:05:59 +03:00
|
|
|
from pygments.lexers import get_lexer_for_mimetype, HttpLexer
|
2012-02-25 15:39:38 +03:00
|
|
|
from pygments.formatters.terminal256 import Terminal256Formatter
|
2012-02-29 23:21:43 +03:00
|
|
|
from pygments.formatters.terminal import TerminalFormatter
|
2012-03-02 03:39:22 +03:00
|
|
|
from pygments.styles import get_style_by_name, STYLE_MAP
|
2012-03-14 02:05:44 +03:00
|
|
|
from . import solarized
|
2012-02-25 15:39:38 +03:00
|
|
|
|
|
|
|
|
2012-03-02 03:39:22 +03:00
|
|
|
DEFAULT_STYLE = 'solarized'
|
2012-03-15 02:11:49 +03:00
|
|
|
AVAILABLE_STYLES = [DEFAULT_STYLE] + list(STYLE_MAP.keys())
|
2012-03-02 03:39:22 +03:00
|
|
|
FORMATTER = (Terminal256Formatter
|
2012-03-04 18:40:02 +03:00
|
|
|
if '256color' in os.environ.get('TERM', '')
|
2012-03-02 03:39:22 +03:00
|
|
|
else TerminalFormatter)
|
2012-02-25 15:39:38 +03:00
|
|
|
|
2012-03-02 03:39:22 +03:00
|
|
|
class PrettyHttp(object):
|
2012-02-25 15:39:38 +03:00
|
|
|
|
2012-03-02 03:39:22 +03:00
|
|
|
def __init__(self, style_name):
|
|
|
|
if style_name == 'solarized':
|
|
|
|
style = solarized.SolarizedStyle
|
|
|
|
else:
|
|
|
|
style = get_style_by_name(style_name)
|
|
|
|
self.formatter = FORMATTER(style=style)
|
2012-02-25 15:39:38 +03:00
|
|
|
|
2012-03-02 03:39:22 +03:00
|
|
|
def headers(self, content):
|
2012-04-26 14:05:59 +03:00
|
|
|
return pygments.highlight(content, HttpLexer(), self.formatter)
|
2012-02-25 15:39:38 +03:00
|
|
|
|
2012-03-02 03:39:22 +03:00
|
|
|
def body(self, content, content_type):
|
|
|
|
content_type = content_type.split(';')[0]
|
2012-04-26 14:05:59 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
lexer = get_lexer_for_mimetype(content_type)
|
|
|
|
except ClassNotFound:
|
|
|
|
return content
|
|
|
|
|
2012-03-02 03:39:22 +03:00
|
|
|
if 'json' in content_type:
|
|
|
|
try:
|
2012-03-13 23:42:18 +03:00
|
|
|
# Indent the JSON data.
|
2012-03-02 03:39:22 +03:00
|
|
|
content = json.dumps(json.loads(content),
|
2012-04-26 14:05:59 +03:00
|
|
|
sort_keys=True, indent=4)
|
|
|
|
except:
|
2012-03-02 03:39:22 +03:00
|
|
|
pass
|
2012-04-26 14:05:59 +03:00
|
|
|
|
2012-03-13 23:42:18 +03:00
|
|
|
return pygments.highlight(content, lexer, self.formatter)
|