improved undefined behavior
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 814f6c2 · Browse files · 10 files·+126 added−76 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+126 added−76 removed
- other:+126 added−76 removed
Provenance
- Commit
9a82205- Tree
3d4e99c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
814f6c2
10 files changed+126 added−76 removed
modified:jinja2/__init__.py+2 added-1 removed
55 unmodified lines56 :copyright: 2008 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58 """59 from jinja2.environment import Environment60-from jinja2.loaders import BaseLoader, FileSystemLoader, DictLoader60+from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \61+ DictLoader62 from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined63 from jinja2.utils import Markup, escapemodified:jinja2/compiler.py+1 added-6 removed
936 unmodified lines937 938 def uaop(operator):939 def visitor(self, node, frame):940 self.write('(' + operator)941- self.visit(node.node)941+ self.visit(node.node, frame)942 self.write(')')943 return visitor944 945 visit_Add = binop('+')30 unmodified lines976 const = node.arg.as_const()977 have_const = True978 except nodes.Impossible:979 have_const = False980- if have_const:981- if isinstance(const, (int, long, float)):982- self.visit(node.node, frame)983- self.write('[%s]' % const)984- return980 self.write('environment.subscribe(')981 self.visit(node.node, frame)982 self.write(', ')983 if have_const:69 unmodified linesmodified:jinja2/defaults.py+1 added-1 removed
7 unmodified lines8 :copyright: 2007-2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from jinja2.filters import FILTERS as DEFAULT_FILTERS12-from jinja.tests import TESTS as DEFAULT_TESTS12+from jinja2.tests import TESTS as DEFAULT_TESTS13 14 15 DEFAULT_NAMESPACE = {16 'range': xrange,5 unmodified linesmodified:jinja2/environment.py+6 added-3 removed
108 unmodified lines109 except (AttributeError, UnicodeError):110 try:111 return obj[argument]112 except (TypeError, LookupError):113- return self.undefined(obj, argument)113+ return self.undefined(obj=obj, name=argument)114 115 def parse(self, source, name=None):116 """Parse the sourcecode and return the abstract syntax tree. This tree117 of nodes is used by the compiler to convert the template into118 executable source- or bytecode.119 """120- parser = Parser(self, source, name)121- return parser.parse()120+ return Parser(self, source, name).parse()121 122 def lex(self, source, name=None):123 """Lex the given sourcecode and return a generator that yields tokens.124 The stream returned is not usable for Jinja but can be used if71 unmodified lines196 self._uptodate = uptodate197 namespace['__jinja_template__'] = self198 199 def render(self, *args, **kwargs):200+ """Render the template into a string."""201 return u''.join(self.generate(*args, **kwargs))202 203 def stream(self, *args, **kwargs):204+ """Return a `TemplateStream` that generates the template."""205 return TemplateStream(self.generate(*args, **kwargs))206 207 def generate(self, *args, **kwargs):208+ """Return a generator that generates the template."""209 # assemble the context210 context = dict(*args, **kwargs)211 212 # if the environment is using the optimizer locals may never28 unmodified lines241 if code_line <= lineno:242 return template_line243 return 1244 245+ @property246 def is_up_to_date(self):247 """Check if the template is still up to date."""248 if self._uptodate is None:249 return True54 unmodified linesmodified:jinja2/exceptions.py+12 added-9 removed
9 unmodified lines10 """11 12 13 class TemplateError(Exception):14- pass14+ """Baseclass for all template errors."""15 16 17+class UndefinedError(TemplateError):18+ """Raised if a template tries to operate on `Undefined`."""19+20+21 class TemplateNotFound(IOError, LookupError, TemplateError):18- """19- Raised if a template does not exist.20- """22+ """Raised if a template does not exist."""23 24 def __init__(self, name):25 IOError.__init__(self, name)26 self.name = name27 28 29 class TemplateSyntaxError(TemplateError):28- """29- Raised to tell the user that there is a problem with the template.30- """30+ """Raised to tell the user that there is a problem with the template."""31 32 def __init__(self, message, lineno, name):33 TEmplateError.__init__(self, '%s (line %s)' % (message, lineno))34 self.message = message1 unmodified line36 self.name = name37 38 39 class TemplateAssertionError(AssertionError, TemplateSyntaxError):40+ """Like a template syntax error, but covers cases where something in the41+ template caused an error at compile time that wasn't necessarily caused42+ by a syntax error.43+ """44 45 def __init__(self, message, lineno, name):46 AssertionError.__init__(self, message)47 TemplateSyntaxError.__init__(self, message, lineno, name)48 49 50 class TemplateRuntimeError(TemplateError):47- """48- Raised by the template engine if a tag encountered an error when51+ """Raised by the template engine if a tag encountered an error when52 rendering.53 """modified:jinja2/filters.py+3 added-6 removed
235 unmodified lines236 """Return the frist item of a sequence."""237 try:238 return iter(seq).next()239 except StopIteration:240- return environment.undefined('seq|first',241- extra='the sequence was empty')240+ return environment.undefined('No first item, sequence was empty.')241 242 243 @environmentfilter244 def do_last(environment, seq):245 """Return the last item of a sequence."""246 try:247 return iter(reversed(seq)).next()248 except StopIteration:250- return environment.undefined('seq|last',251- extra='the sequence was empty')249+ return environment.undefined('No last item, sequence was empty.')250 251 252 @environmentfilter253 def do_random(environment, seq):254 """Return a random item from the sequence."""255 try:256 return choice(seq)257 except IndexError:260- return environment.undefined('seq|random',261- extra='the sequence was empty')258+ return environment.undefined('No random item, sequence was empty.')259 260 261 def do_filesizeformat(value):262 """Format the value like a 'human-readable' file size (i.e. 13 KB,354 unmodified linesmodified:jinja2/loaders.py+44 added-18 removed
7 unmodified lines8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from os import path12-from time import time12 from jinja2.exceptions import TemplateNotFound13 from jinja2.environment import Template14 from jinja2.utils import LRUCache15 16 17+def split_template_path(template):18+ """Split a path into segments and perform a sanity check. If it detects19+ '..' in the path it will raise a `TemplateNotFound` error.20+ """21+ pieces = []22+ for piece in template.split('/'):23+ if path.sep in piece \24+ or (path.altsep and path.altsep in piece) or \25+ piece == path.pardir:26+ raise TemplateNotFound(template)27+ elif piece != '.':28+ pieces.append(piece)29+ return pieces30+31+32 class BaseLoader(object):33 """34 Baseclass for all loaders. Subclass this and override `get_source` to35 implement a custom loading mechanism.38 unmodified lines74 75 if self.cache is not None:76 template = self.cache.get(name)77 if template is not None and (not self.auto_reload or \64- template.is_up_to_date()):78+ template.is_up_to_date):79 return template80 81 source, filename, uptodate = self.get_source(environment, name)82 code = environment.compile(source, name, filename, globals)14 unmodified lines97 self.searchpath = searchpath98 self.encoding = encoding99 100 def get_source(self, environment, template):87- pieces = []88- for piece in template.split('/'):89- if piece == '..':90- raise TemplateNotFound(template)91- elif piece != '.':92- pieces.append(piece)101+ pieces = split_template_path(template)102 for searchpath in self.searchpath:103 filename = path.join(searchpath, *pieces)95- if path.isfile(filename):96- f = file(filename)97- try:98- contents = f.read().decode(self.encoding)99- finally:100- f.close()101- mtime = path.getmtime(filename)102- def uptodate():103- return path.getmtime(filename) != mtime104- return contents, filename, uptodate104+ if not path.isfile(filename):105+ continue106+ f = file(filename)107+ try:108+ contents = f.read().decode(self.encoding)109+ finally:110+ f.close()111+ old = path.getmtime(filename)112+ return contents, filename, lambda: path.getmtime(filename) != old113 raise TemplateNotFound(template)114 115 116+class PackageLoader(BaseLoader):117+ """Load templates from python eggs."""118+119+ def __init__(self, package_name, package_path, charset='utf-8',120+ cache_size=50, auto_reload=True):121+ BaseLoader.__init__(self, cache_size, auto_reload)122+ import pkg_resources123+ self._pkg = pkg_resources124+ self.package_name = package_name125+ self.package_path = package_path126+127+ def get_source(self, environment, template):128+ path = '/'.join(split_template_path(template))129+ if not self._pkg.resource_exists(self.package_name, path):130+ raise TemplateNotFound(template)131+ return self._pkg.resource_string(self.package_name, path), None, None132+133+134 class DictLoader(BaseLoader):135 """Loads a template from a python dict. Used for unittests mostly."""136 137 def __init__(self, mapping):6 unmodified linesmodified:jinja2/parser.py+1 added-1 removed
637 unmodified lines638 dyn_args = dyn_kwargs = None639 node = nodes.Test(node, name, args, kwargs, dyn_args,640 dyn_kwargs, lineno=token.lineno)641 if negated:642- node = nodes.NotExpression(node, lineno=token.lineno)642+ node = nodes.Not(node, lineno=token.lineno)643 return node644 645 def subparse(self, end_tokens=None):646 body = []44 unmodified linesmodified:jinja2/runtime.py+37 added-22 removed
11 unmodified lines12 from collections import defaultdict13 except ImportError:14 defaultdict = None15 from jinja2.utils import Markup16+from jinja2.exceptions import UndefinedError17 18 19 __all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',20 'Macro', 'IncludedTemplate', 'Markup']25 unmodified lines46 """Render a parent block."""47 try:48 func = self.blocks[block][-2]49 except LookupError:49- return self.environment.undefined('super',50- extra='there is probably no parent block with this name')50+ return self.environment.undefined('there is no parent block '51+ 'called %r.' % block)52 return SuperBlock(block, self, func)53 54 def __setitem__(self, key, value):55 """If we set items to the dict we track the variables set so9 unmodified lines65 if defaultdict is None:66 def __getitem__(self, name):67 if name in self:68 return self[name]68- return self.environment.undefined(name)69+ return self.environment.undefined(name=name)70 else:70- def __missing__(self, key):71- return self.environment.undefined(key)71+ def __missing__(self, name):72+ return self.environment.undefined(name=name)73 74 def __repr__(self):75 return '<%s %s of %r>' % (76 self.__class__.__name__,164 unmodified lines241 except KeyError:242 try:243 value = self.defaults[idx - arg_count]244 except IndexError:244- value = self._environment.undefined(name,245- extra='parameter not provided')245+ value = self._environment.undefined(246+ 'parameter %r was not provided' % name)247 arguments['l_' + name] = value248 if self.caller:249 caller = kwargs.pop('caller', None)250 if caller is None:250- caller = self._environment.undefined('caller',251- extra='The macro was called from an expression and not '252- 'a call block.')251+ caller = self._environment.undefined('No caller defined')252 arguments['l_caller'] = caller253 if self.catch_all:254 arguments['l_arguments'] = kwargs255 return self._func(**arguments)10 unmodified lines266 can be printed and iterated over, but every other access will raise a267 `NameError`. Custom undefined classes must subclass this.268 """269 271- def __init__(self, name=None, attr=None, extra=None):272- if attr is None:273- self._undefined_hint = '%r is undefined' % name274- self._error_class = NameError275- else:276- self._undefined_hint = '%r has no attribute named %r' \277- % (name, attr)278- self._error_class = AttributeError279- if extra is not None:280- self._undefined_hint += ' (' + extra + ')'270+ def __init__(self, hint=None, obj=None, name=None):271+ self._undefined_hint = hint272+ self._undefined_obj = obj273+ self._undefined_name = name274 275 def _fail_with_error(self, *args, **kwargs):283- raise self._error_class(self._undefined_hint)276+ if self._undefined_hint is None:277+ if self._undefined_obj is None:278+ hint = '%r is undefined' % self._undefined_name279+ elif not isinstance(self._undefined_name, basestring):280+ hint = '%r object has no element %r' % (281+ self._undefined_obj.__class__.__name__,282+ self._undefined_name283+ )284+ else:285+ hint = '%r object has no attribute %s' % (286+ self._undefined_obj.__class__.__name__,287+ self._undefined_name288+ )289+ else:290+ hint = self._undefined_hint291+ raise UndefinedError(hint)292 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \293 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \294 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \295 __getattr__ = __getitem__ = _fail_with_error21 unmodified lines317 class DebugUndefined(Undefined):318 """An undefined that returns the debug info when printed."""319 320 def __unicode__(self):321+ if self._undefined_hint is None:322+ if self._undefined_obj is None:313- return u'{{ %s }}' % self._undefined_hint323+ return u'{{ %s }}' % self._undefined_name324+ return '{{ no such element: %s[%r] }}' % (325+ self._undefined_obj.__class__.__name__,326+ self._undefined_name327+ )328+ return u'{{ undefined value printed: %s }}' % self._undefined_hint329 330 331 class StrictUndefined(Undefined):332 """An undefined that barks on print and iteration."""2 unmodified linesmodified:jinja2/sandbox.py+19 added-9 removed
42 unmodified lines43 def __init__(self, *args, **kwargs):44 Environment.__init__(self, *args, **kwargs)45 self.globals['range'] = safe_range46 47- def is_safe_attribute(self, obj, attr):47+ def is_safe_attribute(self, obj, attr, value):48 """The sandboxed environment will call this method to check if the49 attribute of an object is safe to access. Per default all attributes50 starting with an underscore are considered private as well as the51 special attributes of functions and methods.13 unmodified lines65 affect the `unsafe` decorator from this module.66 """67 return not getattr(obj, 'unsafe_callable', False)68 69- def subscribe(self, obj, arg):69+ def subscribe(self, obj, argument):70 """Subscribe an object from sandboxed code."""71+ is_unsafe = False72 try:73+ value = getattr(obj, str(argument))74+ except (AttributeError, UnicodeError):75+ pass76+ else:77+ if self.is_safe_attribute(obj, argument, value):78+ return value79+ is_unsafe = True80+ try:72- return obj[arg]81+ return obj[argument]82 except (TypeError, LookupError):74- if not self.is_safe_attribute(obj, arg):75- return Undefined(obj, arg, extra='attribute unsafe')76- try:77- return getattr(obj, str(arg))78- except (AttributeError, UnicodeError):79- return Undefined(obj, arg)83+ if is_unsafe:84+ return self.undefined('access to attribute %r of %r object is'85+ ' unsafe.' % (86+ argument,87+ obj.__class__.__name__88+ ))89+ return self.undefined(obj=obj, name=argument)90 91 def call(__self, __obj, *args, **kwargs):92 """Call an object from sandboxed code."""93 # the double prefixes are to avoid double keyword argument4 unmodified lines