Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 1d02108 · Browse files · 10 files·+98 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+98 added−28 removed
- tests:+13 added−1 removed
- other:+85 added−27 removed
Provenance
- Commit
d416a97- Tree
c673bf9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1d02108
10 files changed+98 added−28 removed
modified:examples/basic/templates/broken.html+2 added-1 removed
1233456{% from 'subbroken.html' import may_break %}<ul>{% for item in seq %} <li>{{ item / 0 }}</li> <li>{{ may_break(item) }}</li>{% endfor %}</ul>added:examples/basic/templates/subbroken.html+3 added
123{% macro may_break(item) -%} [{{ item / 0 }}]{%- endmacro %}modified:examples/basic/debugger.py+1 added-1 removed
2 unmodified lines3 4 env = Environment(loader=FileSystemLoader('templates'))5 6 tmpl = env.get_template('broken.html')7-print tmpl.render(seq=range(10))7+print tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1])modified:jinja2/debug.py+43 added-18 removed
9 unmodified lines10 :copyright: (c) 2009 by the Jinja Team.11 :license: BSD.12 """13 import sys14-from jinja2.utils import CodeType, missing14+from jinja2.utils import CodeType, missing, internal_code15 16 17+def translate_syntax_error(error, source=None):18+ """Rewrites a syntax error to please traceback systems."""19+ error.source = source20+ error.translated = True21+ exc_info = (type(error), error, None)22+ filename = error.filename23+ if filename is None:24+ filename = '<unknown>'25+ return fake_exc_info(exc_info, filename, error.lineno)26+27+28 def translate_exception(exc_info):29 """If passed an exc_info it will automatically rewrite the exceptions30 all the way down to the correct line numbers and frames.31 """32 result_tb = prev_tb = None33 initial_tb = tb = exc_info[2].tb_next34 35 while tb is not None:36+ # skip frames decorated with @internalcode. These are internal37+ # calls we can't avoid and that are useless in template debugging38+ # output.39+ if tb_set_next is not None and tb.tb_frame.f_code in internal_code:40+ tb_set_next(prev_tb, tb.tb_next)41+ tb = tb.tb_next42+ continue43+44 template = tb.tb_frame.f_globals.get('__jinja_template__')45 if template is not None:46 lineno = template.get_corresponding_lineno(tb.tb_lineno)47 tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,10 unmodified lines58 """Helper for `translate_exception`."""59 exc_type, exc_value, tb = exc_info60 61 # figure the real context out62+ if tb is not None:43- real_locals = tb.tb_frame.f_locals.copy()44- ctx = real_locals.get('context')45- if ctx:46- locals = ctx.get_all()63+ real_locals = tb.tb_frame.f_locals.copy()64+ ctx = real_locals.get('context')65+ if ctx:66+ locals = ctx.get_all()67+ else:68+ locals = {}69+ for name, value in real_locals.iteritems():70+ if name.startswith('l_') and value is not missing:71+ locals[name[2:]] = value72+73+ # if there is a local called __jinja_exception__, we get74+ # rid of it to not break the debug functionality.75+ locals.pop('__jinja_exception__', None)76 else:77 locals = {}49- for name, value in real_locals.iteritems():50- if name.startswith('l_') and value is not missing:51- locals[name[2:]] = value78 53- # if there is a local called __jinja_exception__, we get54- # rid of it to not break the debug functionality.55- locals.pop('__jinja_exception__', None)56-79 # assamble fake globals we need80 globals = {81 '__name__': filename,82 '__file__': filename,6 unmodified lines89 90 # if it's possible, change the name of the code. This won't work91 # on some python environments such as google appengine92 try:71- function = tb.tb_frame.f_code.co_name72- if function == 'root':73- location = 'top-level template code'74- elif function.startswith('block_'):75- location = 'block "%s"' % function[6:]76- else:93+ if tb is None:94 location = 'template'95+ else:96+ function = tb.tb_frame.f_code.co_name97+ if function == 'root':98+ location = 'top-level template code'99+ elif function.startswith('block_'):100+ location = 'block "%s"' % function[6:]101+ else:102+ location = 'template'103 code = CodeType(0, code.co_nlocals, code.co_stacksize,104 code.co_flags, code.co_code, code.co_consts,105 code.co_names, code.co_varnames, filename,106 location, code.co_firstlineno,92 unmodified linesmodified:jinja2/environment.py+10 added-5 removed
16 unmodified lines17 from jinja2.compiler import generate18 from jinja2.runtime import Undefined, new_context19 from jinja2.exceptions import TemplateSyntaxError20 from jinja2.utils import import_string, LRUCache, Markup, missing, \21- concat, consume21+ concat, consume, internalcode22 23 24 # for direct template usage we have up to ten living environments25 _spontaneous_environments = LRUCache(10)312 unmodified lines338 return obj[attribute]339 except (TypeError, LookupError, AttributeError):340 return self.undefined(obj=obj, name=attribute)341 342+ @internalcode343 def parse(self, source, name=None, filename=None):344 """Parse the sourcecode and return the abstract syntax tree. This345 tree of nodes is used by the compiler to convert the template into346 executable source- or bytecode. This is useful for debugging or to6 unmodified lines353 filename = filename.encode('utf-8')354 try:355 return Parser(self, source, name, filename).parse()356 except TemplateSyntaxError, e:356- e.source = source357- raise e357+ from jinja2.debug import translate_syntax_error358+ exc_type, exc_value, tb = translate_syntax_error(e, source)359+ raise exc_type, exc_value, tb360 361 def lex(self, source, name=None, filename=None):362 """Lex the given sourcecode and return a generator that yields363 tokens as tuples in the form ``(lineno, token_type, value)``.7 unmodified lines371 source = unicode(source)372 try:373 return self.lexer.tokeniter(source, name, filename)374 except TemplateSyntaxError, e:373- e.source = source374- raise e375+ from jinja2.debug import translate_syntax_error376+ exc_type, exc_value, tb = translate_syntax_error(e, source)377+ raise exc_type, exc_value, tb378 379 def preprocess(self, source, name=None, filename=None):380 """Preprocesses the source with all extensions. This is automatically381 called for all parsing and compiling methods but *not* for :meth:`lex`13 unmodified lines395 if not isinstance(stream, TokenStream):396 stream = TokenStream(stream, name, filename)397 return stream398 399+ @internalcode400 def compile(self, source, name=None, filename=None, raw=False):401 """Compile a node or template source code. The `name` parameter is402 the load name of the template after it was joined using403 :meth:`join_path` if necessary, not the filename on the file system.72 unmodified lines476 joining here.477 """478 return template479 480+ @internalcode481 def get_template(self, name, parent=None, globals=None):482 """Load a template from the loader. If a loader is configured this483 method ask the loader for the template and returns a :class:`Template`.484 If the `parent` parameter is not `None`, :meth:`join_path` is called356 unmodified linesmodified:jinja2/exceptions.py+9 added
42 unmodified lines43 self.name = name44 self.filename = filename45 self.source = None46 47+ # this is set to True if the debug.translate_syntax_error48+ # function translated the syntax error into a new traceback49+ self.translated = False50+51 def __unicode__(self):52+ # for translated errors we only return the message53+ if self.translated:54+ return self.message.encode('utf-8')55+56+ # otherwise attach some stuff57 location = 'line %d' % self.lineno58 name = self.filename or self.name59 if name:60 location = 'File "%s", %s' % (name, location)45 unmodified linesmodified:jinja2/loaders.py+2 added-1 removed
12 unmodified lines13 from hashlib import sha114 except ImportError:15 from sha import new as sha116 from jinja2.exceptions import TemplateNotFound17-from jinja2.utils import LRUCache, open_if_exists17+from jinja2.utils import LRUCache, open_if_exists, internalcode18 19 20 def split_template_path(template):21 """Split a path into segments and perform a sanity check. If it detects56 unmodified lines78 the template will be reloaded.79 """80 raise TemplateNotFound(template)81 82+ @internalcode83 def load(self, environment, name, globals=None):84 """Loads a template. This method looks up the template in the cache85 or loads one by calling :meth:`get_source`. Subclasses should not86 override this method as loaders working on collections of other224 unmodified linesmodified:jinja2/runtime.py+6 added-1 removed
9 unmodified lines10 """11 import sys12 from itertools import chain, imap13 from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \14- concat, MethodType, FunctionType14+ concat, MethodType, FunctionType, internalcode15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17 18 136 unmodified lines155 exported variables.156 """157 return dict(self.parent, **self.vars)158 159+ @internalcode160 def call(__self, __obj, *args, **kwargs):161 """Call the callable with the arguments and keyword arguments162 provided but inject the active context or environment as first163 argument if the callable is a :func:`contextfunction` or75 unmodified lines239 self.name, name='super')240 return BlockReference(self.name, self._context, self._stack,241 self._depth + 1)242 243+ @internalcode244 def __call__(self):245 rv = concat(self._stack[self._depth](self._context))246 if self._context.environment.autoescape:247 rv = Markup(rv)34 unmodified lines282 283 def __iter__(self):284 return LoopContextIterator(self)285 286+ @internalcode287 def loop(self, iterable):288 if self._recurse is None:289 raise TypeError('Tried to call non recursive loop. Maybe you '290 "forgot the 'recursive' modifier.")53 unmodified lines344 self.catch_kwargs = catch_kwargs345 self.catch_varargs = catch_varargs346 self.caller = caller347 348+ @internalcode349 def __call__(self, *args, **kwargs):350 arguments = []351 for idx, name in enumerate(self.arguments):352 try:59 unmodified lines412 self._undefined_obj = obj413 self._undefined_name = name414 self._undefined_exception = exc415 416+ @internalcode417 def _fail_with_undefined_error(self, *args, **kwargs):418 """Regular callback function for undefined objects that raises an419 `UndefinedError` on call.420 """97 unmodified linesmodified:jinja2/utils.py+9 added
33 unmodified lines34 35 # special singleton representing missing values for the runtime36 missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()37 38+# internal code39+internal_code = set()40 41+42 # concatenate a list of strings and convert them to unicode.43 # unfortunately there is a bug in python 2.4 and lower that causes44 # unicode.join trash the traceback.45 _concat = u''.join76 unmodified lines122 f.environmentfunction = True123 return f124 125 126+def internalcode(f):127+ """Marks the function as internally used"""128+ internal_code.add(f.func_code)129+ return f130+131+132 def is_undefined(obj):133 """Check if the object passed is undefined. This does nothing more than134 performing an instance check against :class:`Undefined` but looks nicer.135 This can be used for custom filters or tests that want to react to628 unmodified linesmodified:tests/test_debug.py+13 added-1 removed
29 unmodified lines30 test_syntax_error = '''31 >>> tmpl = MODULE.env.get_template('syntaxerror.html')32 Traceback (most recent call last):33 ...34-TemplateSyntaxError: unknown tag 'endif'34 File "loaderres/templates/syntaxerror.html", line 435 {% endif %}36+TemplateSyntaxError: unknown tag 'endif'37 '''38+39+40+test_regular_syntax_error = '''41+>>> from jinja2.exceptions import TemplateSyntaxError42+>>> raise TemplateSyntaxError('wtf', 42)43+Traceback (most recent call last):44+ ...45+ File "<doctest test_regular_syntax_error[1]>", line 1, in <module>46+ raise TemplateSyntaxError('wtf', 42)47+TemplateSyntaxError: wtf48+ line 4249+'''