import os
from pygments.lexers import get_lexer_for_filename, JavascriptLexer, TextLexer, HtmlDjangoLexer
from pygments.formatters import HtmlFormatter
from pygments import highlight
from pygments.styles import get_style_by_name
from django.shortcuts import render_to_response
from django.http import HttpResponseBadRequest, Http404
from django.conf import settings
from django.template.context import RequestContext
def pygdoc(request, path):
if path.endswith('/'): path = path[:-1]
abspath = os.path.abspath(os.path.join(settings.PROJECT_ROOT, path))
if abspath.endswith('.pyc'):
abspath = abspath[:-4]
if os.path.isfile(abspath):
formatter = HtmlFormatter(linenos=True,cssclass='codehilite',style=get_style_by_name('native'))
if abspath.endswith('.json'):
lexer = JavascriptLexer()
elif abspath.endswith('.html'):
lexer = HtmlDjangoLexer()
else:
try:
lexer = get_lexer_for_filename(abspath)
except:
lexer = TextLexer()
if abspath.endswith('.db') or abspath.endswith('.jpg') or abspath.endswith('.png') or abspath.endswith('.gif') or abspath.endswith('local_settings.py') :
source = 'Un-highlightable file type'
else:
source = open(abspath).read()
return render_to_response('source.html', {
'source': highlight(source, lexer, formatter)},
context_instance = RequestContext(request))
elif os.path.isdir(abspath) and not abspath.endswith('.svn'):
contents = [os.path.join(abspath, f) for f in os.listdir(abspath) if not f.startswith('.') and not f.endswith('.pyc')]
return render_to_response('directory.html', {
'files': sorted([f[len(abspath)+1:] for f in contents if os.path.isfile(f)]),
'folders': sorted([f[len(abspath)+1:] for f in contents if os.path.isdir(f)])
}, context_instance = RequestContext(request))
else:
raise Http404