exceptions.py 12 KB

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