public
Created

pygmentme.py

  • Download Gist
gistfile1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#!/usr/bin/env python
import logging
import os
from pygments.util import ClassNotFound
from pygments import highlight
from pygments.lexers import guess_lexer_for_filename
from pygments.formatters import HtmlFormatter
 
 
logging.basicConfig(level=logging.DEBUG)
 
PROJECT_NAME = '%s_source' % os.path.basename(os.getcwd())
ROOT = './%s/' % PROJECT_NAME
BLACKLIST_EXT = [".pyc"]
BLACKLIST_DIR = [".git"]
 
 
def pygmentize(fpath):
try:
with open(fpath, 'r') as inFile:
source = inFile.read()
except IOError, e:
logging.critical("Exception in file read: %s" % e)
return None
try:
return highlight(source,
guess_lexer_for_filename(fpath, source),
HtmlFormatter(cssclass="source",
full=True))
except ClassNotFound:
return "<pre>%s</pre>" % source
 
 
def appendHtml(p):
return "%s.html" % p
 
 
def writePygment(fpath, source, retry=False):
try:
with open(fpath, 'w+') as ouf:
ouf.write(source)
except UnicodeEncodeError:
logging.info("Unicode file %s ignored" % fpath)
except IOError:
if retry:
logging.critical("File %s failed retry pygment" % fpath)
return
logging.info("Path %s not found, creating" % os.path.dirname(fpath))
os.mkdir(os.path.dirname(fpath))
writePygment(fpath, source, True)
 
if __name__ == '__main__':
if not os.path.exists(ROOT):
os.mkdir(ROOT)
for r, d, f in os.walk("."):
for di in d:
filepath = os.path.relpath(os.path.join(r, di))
outpath = os.path.join(ROOT, filepath)
if not os.path.exists(outpath):
logging.debug("Created path: %s" % outpath)
os.mkdir(outpath)
for fn in f:
(_, ex) = os.path.splitext(fn)
if not ex in BLACKLIST_EXT:
filepath = os.path.relpath(os.path.join(r, fn))
if not any([True for x in BLACKLIST_DIR if filepath.startswith(x)]):
outpath = os.path.join(ROOT, appendHtml(filepath))
writePygment(outpath, pygmentize(filepath))
else:
logging.debug("Blacklisted directory %s ignored" % filepath)
else:
logging.debug("Blacklisted file %s ignored" % fn)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.