2012-03-02 01:39:22 +01:00
|
|
|
import os
|
2012-07-14 16:27:11 +02:00
|
|
|
import re
|
2012-02-25 13:39:38 +01:00
|
|
|
import json
|
2012-04-26 14:48:38 +02:00
|
|
|
|
2012-02-25 13:39:38 +01:00
|
|
|
import pygments
|
2012-04-26 14:48:38 +02:00
|
|
|
|
2012-03-02 01:39:22 +01:00
|
|
|
from pygments.util import ClassNotFound
|
2012-04-28 14:18:59 +02:00
|
|
|
from pygments.styles import get_style_by_name, STYLE_MAP
|
2012-04-26 13:05:59 +02:00
|
|
|
from pygments.lexers import get_lexer_for_mimetype, HttpLexer
|
2012-04-26 14:48:38 +02:00
|
|
|
from pygments.formatters.terminal256 import Terminal256Formatter
|
2012-04-28 14:13:40 +02:00
|
|
|
from pygments.formatters.terminal import TerminalFormatter
|
2012-04-26 14:48:38 +02:00
|
|
|
|
2012-03-14 00:05:44 +01:00
|
|
|
from . import solarized
|
2012-02-25 13:39:38 +01:00
|
|
|
|
|
|
|
|
2012-03-02 01:39:22 +01:00
|
|
|
DEFAULT_STYLE = 'solarized'
|
2012-03-15 00:11:49 +01:00
|
|
|
AVAILABLE_STYLES = [DEFAULT_STYLE] + list(STYLE_MAP.keys())
|
2012-03-02 01:39:22 +01:00
|
|
|
FORMATTER = (Terminal256Formatter
|
2012-03-04 16:40:02 +01:00
|
|
|
if '256color' in os.environ.get('TERM', '')
|
2012-03-02 01:39:22 +01:00
|
|
|
else TerminalFormatter)
|
2012-02-25 13:39:38 +01:00
|
|
|
|
2012-07-14 16:27:11 +02:00
|
|
|
application_content_type_re = re.compile(r'application/(.+\+)?(json|xml)$')
|
|
|
|
|
2012-04-26 13:05:59 +02:00
|
|
|
|
2012-04-28 14:13:40 +02:00
|
|
|
class PrettyHttp(object):
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
def headers(self, content):
|
|
|
|
return pygments.highlight(content, HttpLexer(), self.formatter)
|
|
|
|
|
|
|
|
def body(self, content, content_type):
|
|
|
|
content_type = content_type.split(';')[0]
|
2012-07-14 16:27:11 +02:00
|
|
|
application_match = re.match(application_content_type_re, content_type)
|
|
|
|
if application_match:
|
|
|
|
# Strip vendor and extensions from Content-Type
|
|
|
|
vendor, extension = application_match.groups()
|
|
|
|
content_type = content_type.replace(vendor, u"")
|
|
|
|
|
2012-04-28 14:13:40 +02:00
|
|
|
try:
|
|
|
|
lexer = get_lexer_for_mimetype(content_type)
|
|
|
|
except ClassNotFound:
|
|
|
|
return content
|
2012-04-26 13:05:59 +02:00
|
|
|
|
2012-07-14 16:27:11 +02:00
|
|
|
if content_type == "application/json":
|
2012-04-28 14:13:40 +02:00
|
|
|
try:
|
|
|
|
# Indent and sort the JSON data.
|
|
|
|
content = json.dumps(json.loads(content),
|
2012-07-12 15:30:41 +02:00
|
|
|
sort_keys=True, indent=4,
|
|
|
|
ensure_ascii=False)
|
2012-04-28 14:13:40 +02:00
|
|
|
except:
|
|
|
|
pass
|
2012-04-26 13:05:59 +02:00
|
|
|
|
2012-04-28 14:13:40 +02:00
|
|
|
return pygments.highlight(content, lexer, self.formatter)
|