httpie-cli/httpie/pretty.py

63 lines
1.6 KiB
Python
Raw Normal View History

2012-02-25 13:39:38 +01:00
import json
from functools import partial
import pygments
import os
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 import token
2012-02-26 16:13:12 +01:00
from . import solarized
2012-02-25 13:39:38 +01:00
TYPE_JS = 'application/javascript'
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))
]}
if os.environ['TERM'] == 'xterm-256color':
formatter = Terminal256Formatter
else:
formatter = TerminalFormatter
2012-02-25 13:39:38 +01:00
highlight = partial(pygments.highlight,
formatter=formatter(
2012-02-26 16:13:12 +01:00
style=solarized.SolarizedStyle))
2012-02-25 13:39:38 +01:00
highlight_http = partial(highlight, lexer=HTTPLexer())
def prettify_http(headers):
2012-02-26 01:43:44 +01:00
return highlight_http(headers)
2012-02-25 13:39:38 +01:00
def prettify_body(content, content_type):
content_type = content_type.split(';')[0]
2012-02-25 13:39:38 +01:00
if 'json' in content_type:
content_type = TYPE_JS
try:
# Indent JSON
content = json.dumps(json.loads(content),
sort_keys=True, indent=4)
2012-02-25 13:39:38 +01:00
except Exception:
pass
try:
lexer = get_lexer_for_mimetype(content_type)
content = highlight(code=content, lexer=lexer)
if content:
content = content[:-1]
2012-02-25 13:39:38 +01:00
except Exception:
pass
return content
2012-02-25 13:39:38 +01:00