PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/dist/tools/yuidoc/bin/yuidoc_highlight.py

http://jplex.googlecode.com/
Python | 128 lines | 109 code | 15 blank | 4 comment | 18 complexity | d0cbe8f787a736c2b8ecfa13227440e6 MD5 | raw file
  1. #!/usr/bin/env python
  2. import os, re, string, logging, logging.config
  3. import const
  4. from htmlentitydefs import entitydefs
  5. from cStringIO import StringIO
  6. from optparse import OptionParser
  7. from pygments import highlight
  8. from pygments.lexers import JavascriptLexer
  9. from pygments.formatters import HtmlFormatter
  10. try:
  11. logging.config.fileConfig(os.path.join(sys.path[0], const.LOGCONFIG))
  12. except:
  13. pass
  14. log = logging.getLogger('yuidoc.highlight')
  15. entitydefs_inverted = {}
  16. for k,v in entitydefs.items():
  17. entitydefs_inverted[v] = k
  18. _badchars_regex = re.compile('|'.join(entitydefs.values()))
  19. _been_fixed_regex = re.compile('&\w+;|&#[0-9]+;')
  20. def html_entity_fixer(text, skipchars=[], extra_careful=0):
  21. # if extra_careful we don't attempt to do anything to
  22. # the string if it might have been converted already.
  23. if extra_careful and _been_fixed_regex.findall(text):
  24. return text
  25. if type(skipchars) == type('s'):
  26. skipchars = [skipchars]
  27. keyholder= {}
  28. for x in _badchars_regex.findall(text):
  29. if x not in skipchars:
  30. keyholder[x] = 1
  31. #text = text.replace('&','&')
  32. text = text.replace('\x80', '€')
  33. for each in keyholder.keys():
  34. if each == '&':
  35. continue
  36. better = entitydefs_inverted[each]
  37. if not better.startswith('&#'):
  38. better = '&%s;'%entitydefs_inverted[each]
  39. text = text.replace(each, better)
  40. return text
  41. class DocHighlighter(object):
  42. def __init__(self, inputdirs, outputdir, ext, newext):
  43. def _mkdir(newdir):
  44. if os.path.isdir(newdir): pass
  45. elif os.path.isfile(newdir):
  46. raise OSError("a file with the same name as the desired " \
  47. "dir, '%s', already exists." % newdir)
  48. else:
  49. head, tail = os.path.split(newdir)
  50. if head and not os.path.isdir(head): _mkdir(head)
  51. if tail: os.mkdir(newdir)
  52. def highlightString(src):
  53. try:
  54. return highlight(src, JavascriptLexer(), HtmlFormatter())
  55. except:
  56. return "File could not be highlighted"
  57. def highlightFile(path, file):
  58. f=open(os.path.join(path, file))
  59. fileStr=StringIO(f.read()).getvalue()
  60. f.close()
  61. log.info("highlighting " + file)
  62. highlighted = highlightString(fileStr)
  63. out = open(os.path.join(self.outputdir, file + self.newext), "w")
  64. out.writelines(html_entity_fixer( highlighted , ['<','>','\'','\"']))
  65. out.close()
  66. def highlightDir(path):
  67. subdirs = []
  68. dircontent = ""
  69. for i in os.listdir(path):
  70. fullname = os.path.join(path, i)
  71. if os.path.isdir(fullname):
  72. subdirs.append(fullname)
  73. elif i.lower().endswith(self.ext):
  74. highlightFile(path, i)
  75. for i in subdirs:
  76. highlightDir(i)
  77. self.inputdirs = inputdirs
  78. self.outputdir = os.path.abspath(outputdir)
  79. _mkdir(self.outputdir)
  80. self.ext = ext
  81. self.newext = newext
  82. log.info("-------------------------------------------------------")
  83. for i in inputdirs:
  84. highlightDir(os.path.abspath(i))
  85. def main():
  86. optparser = OptionParser("usage: %prog [options] inputdir1 inputdir2 etc")
  87. optparser.set_defaults(outputdir="out", ext=".js", newext=".highlighted")
  88. optparser.add_option( "-o", "--outputdir",
  89. action="store", dest="outputdir", type="string",
  90. help="Directory to write the parser results" )
  91. optparser.add_option( "-e", "--extension",
  92. action="store", dest="ext", type="string",
  93. help="The extension for the files that should be parsed" )
  94. optparser.add_option( "-n", "--newextension",
  95. action="store", dest="newext", type="string",
  96. help="The extension to append to the output file" )
  97. (opts, inputdirs) = optparser.parse_args()
  98. if len(inputdirs) > 0:
  99. docparser = DocHighlighter( inputdirs,
  100. opts.outputdir,
  101. opts.ext,
  102. opts.newext )
  103. else:
  104. optparser.error("Incorrect number of arguments")
  105. if __name__ == '__main__':
  106. main()