[svn] implemented jinja debugging system
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 56ae6e0 · Browse files · 8 files·+152 added−45 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+152 added−45 removed
- tests:+16 added−0 removed
- other:+136 added−45 removed
Provenance
- Commit
7977e5c- Tree
51878fd- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
56ae6e0
8 files changed+152 added−45 removed
modified:jinja/translators/python.py+68 added-41 removed
6 unmodified lines7 8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+import sys12 from compiler import ast13 from jinja import nodes14 from jinja.nodes import get_nodes15 from jinja.parser import Parser16 from jinja.exceptions import TemplateSyntaxError17 from jinja.translators import Translator18+from jinja.utils import translate_exception19 20 21 def _to_tuple(args):22 """9 unmodified lines32 """33 Represents a finished template.34 """35 34- def __init__(self, environment, code):36+ def __init__(self, environment, code, translated_source=None):37 self.environment = environment38 self.code = code39+ self.translated_source = translated_source40 self.generate_func = None41 42+ def source(self):43+ """The original sourcecode for this template."""44+ return self.environment.loader.get_source(self.code.co_filename)45+ source = property(source, doc=source.__doc__)46+47 def dump(self, stream=None):48 """Dump the template into python bytecode."""49 if stream is not None:50 from marshal import dump43- dump(self.code, stream)51+ dump((self.code, self.translated_source), stream)52 else:53 from marshal import dumps46- return dumps(self.code)54+ return dumps((self.code, self.translated_source))55 56 def load(environment, data):57 """Load the template from python bytecode."""58 if isinstance(data, basestring):59 from marshal import loads52- code = loads(data)60+ code, src = loads(data)61 else:62 from marshal import load55- code = load(data)56- return Template(environment, code)63+ code, src = load(data)64+ return Template(environment, code, src)65 load = staticmethod(load)66 67 def render(self, *args, **kwargs):68 """Render a template."""69 if self.generate_func is None:62- ns = {}70+ ns = {'environment': self.environment}71 exec self.code in ns72 self.generate_func = ns['generate']73 ctx = self.environment.context_class(self.environment, *args, **kwargs)74+ try:66- return u''.join(self.generate_func(ctx))75+ return u''.join(self.generate_func(ctx))76+ except:77+ exc_type, exc_value, traceback = sys.exc_info()78+ traceback = translate_exception(self, exc_type,79+ exc_value, traceback.tb_next,80+ ctx)81+ raise exc_type, exc_value, traceback82 83 84 class PythonTranslator(Translator):85 """70 unmodified lines156 157 def process(environment, node):158 translator = PythonTranslator(environment, node)159 filename = node.filename or '<template>'160+ source = translator.translate()161 return Template(environment,146- compile(translator.translate(), filename, 'exec'))162+ compile(source, filename, 'exec'),163+ source)164 process = staticmethod(process)165 166 # -- private helper methods167 2 unmodified lines170 Indent the current text.171 """172 return (' ' * (self.indention * 4)) + text173 174+ def nodeinfo(self, node):175+ """176+ Return a comment that helds the node informations.177+ """178+ return '# DEBUG(filename=%r, lineno=%s)' % (179+ node.filename,180+ node.lineno181+ )182+183 def filter(self, s, filter_nodes):184 """185 Apply a filter on an object that already is a python expression.186 Used to avoid redundant code in bitor and the filter directive.68 unmodified lines255 if node not in requirements_todo:256 requirements_todo.append(node)257 258 # load the template we inherit from and add not known blocks233- # to the block registry, make this template the new root.259 parent = self.environment.loader.parse(node.extends.template,260 node.filename)236-261+ # look up all block nodes and let them override each other262 overwrites = {}263 for n in get_nodes(nodes.Block, node):264 overwrites[n.name] = n265 for n in get_nodes(nodes.Block, parent):266 if n.name in overwrites:267 n.replace(overwrites[n.name])243-268+ # make the parent node the new node269 node = parent270 271 # look up requirements272 requirements = []5 unmodified lines278 # bootstrapping code279 lines = [280 'from __future__ import division\n'281 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n'257- 'from jinja.utils import buffereater\n\n'282+ 'from jinja.utils import buffereater\n'283+ '__name__ = %r\n\n'284 'def generate(context):\n'259- ' # BOOTSTRAPPING CODE\n'260- ' environment = context.environment\n'285+ ' assert environment is context.environment\n'286 ' get_attribute = environment.get_attribute\n'287 ' perform_test = environment.perform_test\n'288 ' apply_filters = environment.apply_filters\n'289 ' call_function = environment.call_function\n'290 ' call_function_simple = environment.call_function_simple\n'291 ' finish_var = environment.finish_var\n'292 ' ctx_push = context.push\n'268- ' ctx_pop = context.pop\n'293+ ' ctx_pop = context.pop\n' % node.filename294 ]295 296 # we have requirements? add them here.297 if requirements:273- lines.append(self.indent('# REQUIREMENTS'))298 for n in requirements:299 lines.append(self.handle_node(n))276- lines.append(self.indent('# END OF REQUIREMENTS'))300 301 # the template body302 rv = self.handle_node_list(node)303 14 unmodified lines318 def handle_template_text(self, node):319 """320 Handle data around nodes.321 """299- return self.indent('yield %r' % node.text)322+ return self.indent(self.nodeinfo(node)) + '\n' + \323+ self.indent('yield %r' % node.text)324 325 def handle_node_list(self, node):326 """327 In some situations we might have a node list. It's just328 a collection of multiple statements.329 """306- buf = []307- for n in node:308- buf.append(self.handle_node(n))309- return '\n'.join(buf)330+ buf = [self.handle_node(n) for n in node]331+ if buf:332+ return '\n'.join([self.indent(self.nodeinfo(node))] + buf)333+ return ''334 335 def handle_for_loop(self, node):336 """337 Handle a for loop. Pretty basic, just that we give the else338 clause a different behavior.339 """340 buf = []341 write = lambda x: buf.append(self.indent(x))342+ write(self.nodeinfo(node))343 write('ctx_push()')344 345 # recursive loops346 if node.recursive:12 unmodified lines359 )360 361 # handle real loop code362 self.indention += 1363+ buf.append(self.indent(self.nodeinfo(node.body)))364 buf.append(self.handle_node(node.body))365 self.indention -= 1366 367 # else part of loop368 if node.else_:369 write('if not context[\'loop\'].iterated:')370 self.indention += 1371+ buf.append(self.indent(self.nodeinfo(node.else_)))372 buf.append(self.handle_node(node.else_))373 self.indention -= 1374 375 # call recursive for loop!17 unmodified lines393 Handle an if condition node.394 """395 buf = []396 write = lambda x: buf.append(self.indent(x))397+ write(self.nodeinfo(node))398 for idx, (test, body) in enumerate(node.tests):399 write('%sif %s:' % (400 idx and 'el' or '',401 self.handle_node(test)402 ))403 self.indention += 1404+ write(self.nodeinfo(node))405 buf.append(self.handle_node(body))406 self.indention -= 1407 if node.else_ is not None:408 write('else:')409 self.indention += 1410+ write(self.nodeinfo(node))411 buf.append(self.handle_node(node.else_))412 self.indention -= 1413 return '\n'.join(buf)414 7 unmodified lines422 write = lambda x: buf.append(self.indent(x))423 424 write('if not %r in context.current:' % name)425 self.indention += 1426+ write(self.nodeinfo(node))427 if node.seq.__class__ in (ast.Tuple, ast.List):428 write('context.current[%r] = CycleContext(%s)' % (429 name,430 _to_tuple([self.handle_node(n) for n in node.seq.nodes])17 unmodified lines448 def handle_print(self, node):449 """450 Handle a print statement.451 """421- return self.indent('yield finish_var(%s)' % self.handle_node(node.variable))452+ return self.indent(self.nodeinfo(node)) + '\n' + \453+ self.indent('yield finish_var(%s)' %454+ self.handle_node(node.variable))455 456 def handle_macro(self, node):457 """458 Handle macro declarations.2 unmodified lines461 write = lambda x: buf.append(self.indent(x))462 463 write('def macro(*args):')464 self.indention += 1465+ write(self.nodeinfo(node))466 467 if node.arguments:468 write('argcount = len(args)')469 tmp = []7 unmodified lines477 write('ctx_push({%s})' % ', '.join(tmp))478 else:479 write('ctx_push()')480 481+ write(self.nodeinfo(node.body))482 buf.append(self.handle_node(node.body))483 write('ctx_pop()')484 write('if False:')485 self.indention += 16 unmodified lines492 def handle_set(self, node):493 """494 Handle variable assignments.495 """461- return self.indent('context[%r] = %s' % (496+ return self.indent(self.nodeinfo(node)) + '\n' + \497+ self.indent('context[%r] = %s' % (498 node.name,499 self.handle_node(node.expr)500 ))501 4 unmodified lines506 buf = []507 write = lambda x: buf.append(self.indent(x))508 write('def filtered():')509 self.indention += 1510+ write(self.nodeinfo(node))511 write('ctx_push()')512+ write(self.nodeinfo(node.body))513 buf.append(self.handle_node(node.body))514 write('ctx_pop()')515 write('if False:')516 self.indention += 19 unmodified lines526 else.527 """528 rv = self.handle_node(node.body)529 if not rv:492- return self.indent('# EMPTY BLOCK "%s" FROM %r, LINE %s' % (493- node.name,494- node.filename or '?',495- node.lineno496- ))530+ return531 532 buf = []533 write = lambda x: buf.append(self.indent(x))534 501- write('# BLOCK "%s" FROM %r, LINE %s' % (502- node.name,503- node.filename or '?',504- node.lineno505- ))535 write('ctx_push()')536+ write(self.nodeinfo(node.body))537 buf.append(self.handle_node(node.body))538 write('ctx_pop()')509- buf.append(self.indent('# END OF BLOCK'))539 return '\n'.join(buf)540 541 def handle_include(self, node):542 """543 Include another template at the current position.544 """516- buf = [self.indent('# INCLUDED TEMPLATE %r' % node.filename)]545 tmpl = self.environment.loader.parse(node.template,546 node.filename)519- buf.append(self.handle_node_list(tmpl))520- buf.append(self.indent('# END OF INCLUSION'))521- return '\n'.join(buf)547+ return self.handle_node_list(tmpl)548 549 def handle_trans(self, node):550 """551 Handle translations.8 unmodified lines560 ))561 replacements = '{%s}' % ', '.join(replacements)562 else:563 replacements = 'None'564+ return self.indent(self.nodeinfo(node)) + '\n' + \538- return self.indent('yield translate(%r, %r, %r, %s)' % (565+ self.indent('yield translate(%r, %r, %r, %s)' % (566 node.singular,567 node.plural,568 node.indicator,569 replacements290 unmodified linesmodified:jinja/datastructure.py+3 added-2 removed
232 unmodified lines233 234 def __call__(self, seq):235 if self.loop_function is not None:236 return self.loop_function(seq)237- raise TemplateRuntimeError('Loops are just callable if defined with '238- 'the "recursive" modifier.')237+ raise TemplateRuntimeError('In order to make loops callable you have '238+ 'to define them with the "recursive" '239+ 'modifier.')240 241 242 class CycleContext(object):243 """88 unmodified linesmodified:jinja/lexer.py+2 added-1 removed
113 unmodified lines114 returns a `TokenStream` but in some situations it can be useful115 to use this function since it can be marginally faster.116 """117 source = type(source)('\n').join(source.splitlines())118- pos = lineno = 0118+ pos = 0119+ lineno = 1120 stack = ['root']121 statetokens = self.rules['root']122 source_length = len(source)123 87 unmodified linesmodified:jinja/nodes.py+1 added-1 removed
90 unmodified lines91 92 def __init__(self, filename, body, extends):93 if body.__class__ is not NodeList:94 body = (body,)95- NodeList.__init__(self, 0, body)95+ NodeList.__init__(self, 1, body)96 self.extends = extends97 set_filename(filename, self)98 99 def get_items(self):246 unmodified linesmodified:jinja/utils.py+62 added
7 unmodified lines8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import re12+import sys13 from types import MethodType, FunctionType14 from jinja.nodes import Trans15 from jinja.datastructure import Markup16 1 unmodified line18 from collections import deque19 except ImportError:20 deque = None21 22+_debug_info_re = re.compile(r'^\s*\# DEBUG\(filename=(.*?), lineno=(.*?)\)$')23 24 _escape_pairs = {25 '&': '&',26 '<': '<',38 unmodified lines65 return u''.join(f(*args, **kwargs))66 return wrapped67 68 69+def raise_template_exception(template, exception, filename, lineno, context):70+ """71+ Raise an exception "in a template". Return a traceback72+ object.73+ """74+ offset = '\n'.join([''] * lineno)75+ code = compile(offset + 'raise __exception_to_raise__', filename, 'exec')76+ namespace = context.to_dict()77+ globals = {78+ '__name__': filename,79+ '__file__': filename,80+ '__loader__': TracebackLoader(template),81+ '__exception_to_raise__': exception82+ }83+ try:84+ exec code in globals, namespace85+ except:86+ traceback = sys.exc_info()[2]87+ return traceback88+89+90+def translate_exception(template, exc_type, exc_value, traceback, context):91+ """92+ Translate an exception and return the new traceback.93+ """94+ sourcelines = template.translated_source.splitlines()95+ startpos = traceback.tb_lineno - 196+ args = None97+ # looks like we loaded the template from string. we cannot98+ # do anything here.99+ if startpos > len(sourcelines):100+ print startpos, len(sourcelines)101+ return traceback102+103+ while startpos > 0:104+ m = _debug_info_re.search(sourcelines[startpos])105+ if m is not None:106+ args = m.groups()107+ break108+ startpos -= 1109+110+ # no traceback information found, reraise unchanged111+ if args is None:112+ return traceback113+ return raise_template_exception(template, exc_value, args[0],114+ int(args[1] or 0), context)115+116+117+class TracebackLoader(object):118+ """119+ Fake importer that just returns the source of a template.120+ """121+122+ def __init__(self, template):123+ self.template = template124+125+ def get_source(self, impname):126+ return self.template.source127+128+129 class CacheDict(object):130 """131 A dict like object that stores a limited number of items and forgets132 about the least recently used items::118 unmodified linesmodified:tests/templates/c.html+1 added
1234567{% extends 'b.html' %}{% block block2 %}from template c.html{% endblock %}{% block block3 %}from template c.html{% endblock %}{% block block7 %} nested block from b.html, overridden in c.html {{ 1 / 0 }}{% endblock %}added:tests/templates/error.html+5 added
12345<ul>{% for item in items %} {{ item + "this is some strange unicode" }}{% endfor %}</ul>added:tests/exception.py+10 added
1+from jinja import Environment, FileSystemLoader2+from colubrid.debug import DebuggedApplication3+from wsgiref.simple_server import make_server4+e = Environment(loader=FileSystemLoader('templates'))5+6+def test(*args):7+ tmpl = e.loader.load('error.html')8+ tmpl.render(items=range(10))9+10+make_server("localhost", 7000, DebuggedApplication(test)).serve_forever()