exceptions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # mako/exceptions.py
  2. # Copyright (C) 2006-2012 the Mako authors and contributors <see AUTHORS file>
  3. #
  4. # This module is part of Mako and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. """exception classes"""
  7. import traceback
  8. import sys
  9. import re
  10. from mako import util, compat
  11. class MakoException(Exception):
  12. pass
  13. class RuntimeException(MakoException):
  14. pass
  15. def _format_filepos(lineno, pos, filename):
  16. if filename is None:
  17. return " at line: %d char: %d" % (lineno, pos)
  18. else:
  19. return " in file '%s' at line: %d char: %d" % (filename, lineno, pos)
  20. class CompileException(MakoException):
  21. def __init__(self, message, source, lineno, pos, filename):
  22. MakoException.__init__(self,
  23. message + _format_filepos(lineno, pos, filename))
  24. self.lineno =lineno
  25. self.pos = pos
  26. self.filename = filename
  27. self.source = source
  28. class SyntaxException(MakoException):
  29. def __init__(self, message, source, lineno, pos, filename):
  30. MakoException.__init__(self,
  31. message + _format_filepos(lineno, pos, filename))
  32. self.lineno =lineno
  33. self.pos = pos
  34. self.filename = filename
  35. self.source = source
  36. class UnsupportedError(MakoException):
  37. """raised when a retired feature is used."""
  38. class NameConflictError(MakoException):
  39. """raised when a reserved word is used inappropriately"""
  40. class TemplateLookupException(MakoException):
  41. pass
  42. class TopLevelLookupException(TemplateLookupException):
  43. pass
  44. class RichTraceback(object):
  45. """Pull the current exception from the ``sys`` traceback and extracts
  46. Mako-specific template information.
  47. See the usage examples in :ref:`handling_exceptions`.
  48. """
  49. def __init__(self, error=None, traceback=None):
  50. self.source, self.lineno = "", 0
  51. if error is None or traceback is None:
  52. t, value, tback = sys.exc_info()
  53. if error is None:
  54. error = value or t
  55. if traceback is None:
  56. traceback = tback
  57. self.error = error
  58. self.records = self._init(traceback)
  59. if isinstance(self.error, (CompileException, SyntaxException)):
  60. import mako.template
  61. self.source = self.error.source
  62. self.lineno = self.error.lineno
  63. self._has_source = True
  64. self._init_message()
  65. @property
  66. def errorname(self):
  67. return compat.exception_name(self.error)
  68. def _init_message(self):
  69. """Find a unicode representation of self.error"""
  70. try:
  71. self.message = compat.text_type(self.error)
  72. except UnicodeError:
  73. try:
  74. self.message = str(self.error)
  75. except UnicodeEncodeError:
  76. # Fallback to args as neither unicode nor
  77. # str(Exception(u'\xe6')) work in Python < 2.6
  78. self.message = self.error.args[0]
  79. if not isinstance(self.message, compat.text_type):
  80. self.message = compat.text_type(self.message, 'ascii', 'replace')
  81. def _get_reformatted_records(self, records):
  82. for rec in records:
  83. if rec[6] is not None:
  84. yield (rec[4], rec[5], rec[2], rec[6])
  85. else:
  86. yield tuple(rec[0:4])
  87. @property
  88. def traceback(self):
  89. """Return a list of 4-tuple traceback records (i.e. normal python
  90. format) with template-corresponding lines remapped to the originating
  91. template.
  92. """
  93. return list(self._get_reformatted_records(self.records))
  94. @property
  95. def reverse_records(self):
  96. return reversed(self.records)
  97. @property
  98. def reverse_traceback(self):
  99. """Return the same data as traceback, except in reverse order.
  100. """
  101. return list(self._get_reformatted_records(self.reverse_records))
  102. def _init(self, trcback):
  103. """format a traceback from sys.exc_info() into 7-item tuples,
  104. containing the regular four traceback tuple items, plus the original
  105. template filename, the line number adjusted relative to the template
  106. source, and code line from that line number of the template."""
  107. import mako.template
  108. mods = {}
  109. rawrecords = traceback.extract_tb(trcback)
  110. new_trcback = []
  111. for filename, lineno, function, line in rawrecords:
  112. if not line:
  113. line = ''
  114. try:
  115. (line_map, template_lines) = mods[filename]
  116. except KeyError:
  117. try:
  118. info = mako.template._get_module_info(filename)
  119. module_source = info.code
  120. template_source = info.source
  121. template_filename = info.template_filename or filename
  122. except KeyError:
  123. # A normal .py file (not a Template)
  124. if not compat.py3k:
  125. try:
  126. fp = open(filename, 'rb')
  127. encoding = util.parse_encoding(fp)
  128. fp.close()
  129. except IOError:
  130. encoding = None
  131. if encoding:
  132. line = line.decode(encoding)
  133. else:
  134. line = line.decode('ascii', 'replace')
  135. new_trcback.append((filename, lineno, function, line,
  136. None, None, None, None))
  137. continue
  138. template_ln = module_ln = 1
  139. line_map = {}
  140. for line in module_source.split("\n"):
  141. match = re.match(r'\s*# SOURCE LINE (\d+)', line)
  142. if match:
  143. template_ln = int(match.group(1))
  144. module_ln += 1
  145. line_map[module_ln] = template_ln
  146. template_lines = [line for line in
  147. template_source.split("\n")]
  148. mods[filename] = (line_map, template_lines)
  149. template_ln = line_map[lineno]
  150. if template_ln <= len(template_lines):
  151. template_line = template_lines[template_ln - 1]
  152. else:
  153. template_line = None
  154. new_trcback.append((filename, lineno, function,
  155. line, template_filename, template_ln,
  156. template_line, template_source))
  157. if not self.source:
  158. for l in range(len(new_trcback)-1, 0, -1):
  159. if new_trcback[l][5]:
  160. self.source = new_trcback[l][7]
  161. self.lineno = new_trcback[l][5]
  162. break
  163. else:
  164. if new_trcback:
  165. try:
  166. # A normal .py file (not a Template)
  167. fp = open(new_trcback[-1][0], 'rb')
  168. encoding = util.parse_encoding(fp)
  169. fp.seek(0)
  170. self.source = fp.read()
  171. fp.close()
  172. if encoding:
  173. self.source = self.source.decode(encoding)
  174. except IOError:
  175. self.source = ''
  176. self.lineno = new_trcback[-1][1]
  177. return new_trcback
  178. def text_error_template(lookup=None):
  179. """Provides a template that renders a stack trace in a similar format to
  180. the Python interpreter, substituting source template filenames, line
  181. numbers and code for that of the originating source template, as
  182. applicable.
  183. """
  184. import mako.template
  185. return mako.template.Template(r"""
  186. <%page args="error=None, traceback=None"/>
  187. <%!
  188. from mako.exceptions import RichTraceback
  189. %>\
  190. <%
  191. tback = RichTraceback(error=error, traceback=traceback)
  192. %>\
  193. Traceback (most recent call last):
  194. % for (filename, lineno, function, line) in tback.traceback:
  195. File "${filename}", line ${lineno}, in ${function or '?'}
  196. ${line | trim}
  197. % endfor
  198. ${tback.errorname}: ${tback.message}
  199. """)
  200. def _install_pygments():
  201. global syntax_highlight, pygments_html_formatter
  202. from mako.ext.pygmentplugin import syntax_highlight,\
  203. pygments_html_formatter
  204. def _install_fallback():
  205. global syntax_highlight, pygments_html_formatter
  206. from mako.filters import html_escape
  207. pygments_html_formatter = None
  208. def syntax_highlight(filename='', language=None):
  209. return html_escape
  210. def _install_highlighting():
  211. try:
  212. _install_pygments()
  213. except ImportError:
  214. _install_fallback()
  215. _install_highlighting()
  216. def html_error_template():
  217. """Provides a template that renders a stack trace in an HTML format,
  218. providing an excerpt of code as well as substituting source template
  219. filenames, line numbers and code for that of the originating source
  220. template, as applicable.
  221. The template's default ``encoding_errors`` value is ``'htmlentityreplace'``. The
  222. template has two options. With the ``full`` option disabled, only a section of
  223. an HTML document is returned. With the ``css`` option disabled, the default
  224. stylesheet won't be included.
  225. """
  226. import mako.template
  227. return mako.template.Template(r"""
  228. <%!
  229. from mako.exceptions import RichTraceback, syntax_highlight,\
  230. pygments_html_formatter
  231. %>
  232. <%page args="full=True, css=True, error=None, traceback=None"/>
  233. % if full:
  234. <html>
  235. <head>
  236. <title>Mako Runtime Error</title>
  237. % endif
  238. % if css:
  239. <style>
  240. body { font-family:verdana; margin:10px 30px 10px 30px;}
  241. .stacktrace { margin:5px 5px 5px 5px; }
  242. .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }
  243. .nonhighlight { padding:0px; background-color:#DFDFDF; }
  244. .sample { padding:10px; margin:10px 10px 10px 10px;
  245. font-family:monospace; }
  246. .sampleline { padding:0px 10px 0px 10px; }
  247. .sourceline { margin:5px 5px 10px 5px; font-family:monospace;}
  248. .location { font-size:80%; }
  249. .highlight { white-space:pre; }
  250. .sampleline { white-space:pre; }
  251. % if pygments_html_formatter:
  252. ${pygments_html_formatter.get_style_defs()}
  253. .linenos { min-width: 2.5em; text-align: right; }
  254. pre { margin: 0; }
  255. .syntax-highlighted { padding: 0 10px; }
  256. .syntax-highlightedtable { border-spacing: 1px; }
  257. .nonhighlight { border-top: 1px solid #DFDFDF;
  258. border-bottom: 1px solid #DFDFDF; }
  259. .stacktrace .nonhighlight { margin: 5px 15px 10px; }
  260. .sourceline { margin: 0 0; font-family:monospace; }
  261. .code { background-color: #F8F8F8; width: 100%; }
  262. .error .code { background-color: #FFBDBD; }
  263. .error .syntax-highlighted { background-color: #FFBDBD; }
  264. % endif
  265. </style>
  266. % endif
  267. % if full:
  268. </head>
  269. <body>
  270. % endif
  271. <h2>Error !</h2>
  272. <%
  273. tback = RichTraceback(error=error, traceback=traceback)
  274. src = tback.source
  275. line = tback.lineno
  276. if src:
  277. lines = src.split('\n')
  278. else:
  279. lines = None
  280. %>
  281. <h3>${tback.errorname}: ${tback.message|h}</h3>
  282. % if lines:
  283. <div class="sample">
  284. <div class="nonhighlight">
  285. % for index in range(max(0, line-4),min(len(lines), line+5)):
  286. <%
  287. if pygments_html_formatter:
  288. pygments_html_formatter.linenostart = index + 1
  289. %>
  290. % if index + 1 == line:
  291. <%
  292. if pygments_html_formatter:
  293. old_cssclass = pygments_html_formatter.cssclass
  294. pygments_html_formatter.cssclass = 'error ' + old_cssclass
  295. %>
  296. ${lines[index] | syntax_highlight(language='mako')}
  297. <%
  298. if pygments_html_formatter:
  299. pygments_html_formatter.cssclass = old_cssclass
  300. %>
  301. % else:
  302. ${lines[index] | syntax_highlight(language='mako')}
  303. % endif
  304. % endfor
  305. </div>
  306. </div>
  307. % endif
  308. <div class="stacktrace">
  309. % for (filename, lineno, function, line) in tback.reverse_traceback:
  310. <div class="location">${filename}, line ${lineno}:</div>
  311. <div class="nonhighlight">
  312. <%
  313. if pygments_html_formatter:
  314. pygments_html_formatter.linenostart = lineno
  315. %>
  316. <div class="sourceline">${line | syntax_highlight(filename)}</div>
  317. </div>
  318. % endfor
  319. </div>
  320. % if full:
  321. </body>
  322. </html>
  323. % endif
  324. """, output_encoding=sys.getdefaultencoding(),
  325. encoding_errors='htmlentityreplace')