Skip to content
Myr

[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

8 files+152 added−45 removed

modified:jinja/translators/python.py+68 added-41 removed
6 unmodified lines
78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import sys12from compiler import ast13from jinja import nodes14from jinja.nodes import get_nodes15from jinja.parser import Parser16from jinja.exceptions import TemplateSyntaxError17from jinja.translators import Translator18from jinja.utils import translate_exception192021def _to_tuple(args):22 """
9 unmodified lines
32 """33 Represents a finished template.34 """3534 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 = None4142 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__)4647 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))5556 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)6667 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, traceback828384class PythonTranslator(Translator):85 """
70 unmodified lines
156157 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)165166 # -- private helper methods167
2 unmodified lines
170 Indent the current text.171 """172 return (' ' * (self.indention * 4)) + text173174 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 )182183 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 lines
255 if node not in requirements_todo:256 requirements_todo.append(node)257258 # 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)236261 # 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])243268 # make the parent node the new node269 node = parent270271 # look up requirements272 requirements = []
5 unmodified lines
278 # 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 ]295296 # 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'))300301 # the template body302 rv = self.handle_node_list(node)303
14 unmodified lines
318 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)324325 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 ''334335 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()')344345 # recursive loops346 if node.recursive:
12 unmodified lines
359 )360361 # 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 -= 1366367 # 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 -= 1374375 # call recursive for loop!
17 unmodified lines
393 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 lines
422 write = lambda x: buf.append(self.indent(x))423424 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 lines
448 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))455456 def handle_macro(self, node):457 """458 Handle macro declarations.
2 unmodified lines
461 write = lambda x: buf.append(self.indent(x))462463 write('def macro(*args):')464 self.indention += 1465 write(self.nodeinfo(node))466467 if node.arguments:468 write('argcount = len(args)')469 tmp = []
7 unmodified lines
477 write('ctx_push({%s})' % ', '.join(tmp))478 else:479 write('ctx_push()')480481 write(self.nodeinfo(node.body))482 buf.append(self.handle_node(node.body))483 write('ctx_pop()')484 write('if False:')485 self.indention += 1
6 unmodified lines
492 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 lines
506 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 += 1
9 unmodified lines
526 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 return531532 buf = []533 write = lambda x: buf.append(self.indent(x))534501 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)540541 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)548549 def handle_trans(self, node):550 """551 Handle translations.
8 unmodified lines
560 ))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 replacements
290 unmodified lines
modified:jinja/datastructure.py+3 added-2 removed
232 unmodified lines
233234 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.')240241242class CycleContext(object):243 """
88 unmodified lines
modified:jinja/lexer.py+2 added-1 removed
113 unmodified lines
114 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 lines
modified:jinja/nodes.py+1 added-1 removed
90 unmodified lines
9192 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)9899 def get_items(self):
246 unmodified lines
modified:jinja/utils.py+62 added
7 unmodified lines
8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12import sys13from types import MethodType, FunctionType14from jinja.nodes import Trans15from jinja.datastructure import Markup16
1 unmodified line
18 from collections import deque19except ImportError:20 deque = None2122_debug_info_re = re.compile(r'^\s*\# DEBUG\(filename=(.*?), lineno=(.*?)\)$')2324_escape_pairs = {25 '&': '&amp;',26 '<': '&lt;',
38 unmodified lines
65 return u''.join(f(*args, **kwargs))66 return wrapped676869def 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 traceback888990def 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 traceback102103 while startpos > 0:104 m = _debug_info_re.search(sourcelines[startpos])105 if m is not None:106 args = m.groups()107 break108 startpos -= 1109110 # 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)115116117class TracebackLoader(object):118 """119 Fake importer that just returns the source of a template.120 """121122 def __init__(self, template):123 self.template = template124125 def get_source(self, impname):126 return self.template.source127128129class 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 lines
modified:tests/templates/c.html+1 added
added:tests/templates/error.html+5 added
added:tests/exception.py+10 added
1from jinja import Environment, FileSystemLoader2from colubrid.debug import DebuggedApplication3from wsgiref.simple_server import make_server4e = Environment(loader=FileSystemLoader('templates'))56def test(*args):7 tmpl = e.loader.load('error.html')8 tmpl.render(items=range(10))910make_server("localhost", 7000, DebuggedApplication(test)).serve_forever()