httpie-cli/httpie/pretty.py

66 lines
2.1 KiB
Python
Raw Normal View History

import re
import os
2012-02-25 13:39:38 +01:00
import json
import pygments
from pygments import token
from pygments.util import ClassNotFound
2012-02-25 13:39:38 +01:00
from pygments.lexers import get_lexer_for_mimetype
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.formatters.terminal import TerminalFormatter
2012-02-25 13:39:38 +01:00
from pygments.lexer import RegexLexer, bygroups
from pygments.styles import get_style_by_name, STYLE_MAP
2012-02-26 16:13:12 +01:00
from . import solarized
2012-02-25 13:39:38 +01:00
DEFAULT_STYLE = 'solarized'
AVAILABLE_STYLES = [DEFAULT_STYLE] + STYLE_MAP.keys()
2012-02-25 13:39:38 +01:00
TYPE_JS = 'application/javascript'
FORMATTER = (Terminal256Formatter
if os.environ.get('TERM', None) == 'xterm-256color'
else TerminalFormatter)
2012-02-25 13:39:38 +01:00
class HTTPLexer(RegexLexer):
name = 'HTTP'
aliases = ['http']
filenames = ['*.http']
tokens = {
'root': [
(r'\s+', token.Text),
(r'(HTTP/[\d.]+\s+)(\d+)(\s+.+)', bygroups(
token.Operator, token.Number, token.String)),
(r'(.*?:)(.+)', bygroups(token.Name, token.String))
]}
class PrettyHttp(object):
2012-02-25 13:39:38 +01: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 13:39:38 +01:00
def headers(self, content):
return pygments.highlight(content, HTTPLexer(), self.formatter).strip()
2012-02-25 13:39:38 +01:00
def body(self, content, content_type):
content_type = content_type.split(';')[0]
if 'json' in content_type:
content_type = TYPE_JS
try:
# Indent JSON
content = json.dumps(json.loads(content),
sort_keys=True, indent=4)
except Exception:
pass
2012-02-25 13:39:38 +01:00
try:
lexer = get_lexer_for_mimetype(content_type)
except ClassNotFound:
return content
content = pygments.highlight(content, lexer, self.formatter)
# TODO: Make sure the leading/trailing whitespaces remain.
# Some of the Pygments styles add superfluous line breaks.
return content.strip()