Skip to content
Myr

Moved all six usages (ignoring testsuite) into jinja2._compat

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent cd7bf5b · Browse files · 16 files+199 added−183 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

16 files+199 added−183 removed

  • other:+199 added−183 removed

16 files+199 added−183 removed

modified:jinja2/_compat.py+52 added
10 unmodified lines
11 :copyright: Copyright 2013 by the Jinja team, see AUTHORS.12 :license: BSD, see LICENSE for details.13"""14import six15import sys1617PY3 = six.PY31819# https://bitbucket.org/gutworth/six/issue/25/add-unichr20try:21 unichr = unichr # py222except NameError:
1 unmodified line
2425range_type = six.moves.xrange26next = six.advance_iterator27imap = six.moves.map28izip = six.moves.zip29text_type = six.text_type30string_types = six.string_types3132iteritems = six.iteritems3334if six.PY3:35 from io import BytesIO, StringIO36 NativeStringIO = StringIO37else:38 from cStringIO import StringIO as BytesIO39 from StringIO import StringIO40 NativeStringIO = BytesIO4142try:43 import cPickle as pickle44except ImportError:45 import pickle4647ifilter = six.moves.filter48reraise = six.reraise49Iterator = six.Iterator50with_metaclass = six.with_metaclass5152try:53 from collections import Mapping as mapping_types54except ImportError:55 import UserDict56 mapping_types = (UserDict.UserDict, UserDict.DictMixin, dict)575859# common types. These do exist in the special types module too which however60# does not exist in IronPython out of the box. Also that way we don't have61# to deal with implementation specific stuff here62class _C(object):63 def method(self): pass64def _func():65 yield None66function_type = type(_func)67generator_type = type(_func())68method_type = type(_C().method)69code_type = type(_C.method.__code__)70try:71 raise TypeError()72except TypeError:73 _tb = sys.exc_info()[2]74 traceback_type = type(_tb)75 frame_type = type(_tb.tb_frame)76del _C, _tb, _func
modified:jinja2/bccache.py+2 added-6 removed
16 unmodified lines
17from os import path, listdir18import sys19import marshal20import tempfile21from six.moves import cPickle as pickle22from six import BytesIO21import fnmatch24try:25 from hashlib import sha122from hashlib import sha126except ImportError:27 from sha import new as sha123from jinja2.utils import open_if_exists24from jinja2._compat import BytesIO, pickle252627# marshal works better on 3.x, one hack less required28if sys.version_info[0] >= 3:
283 unmodified lines
modified:jinja2/compiler.py+14 added-16 removed
6 unmodified lines
78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import six1211from itertools import chain12from copy import deepcopy13from jinja2 import nodes14from jinja2.nodes import EvalContext15from jinja2.visitor import NodeVisitor16from jinja2.exceptions import TemplateAssertionError17from jinja2.utils import Markup, concat, escape, is_python_keyword20from jinja2._compat import range_type, next21from six.moves import cStringIO as StringIO, map18from jinja2._compat import range_type, next, text_type, string_types, \19 iteritems, NativeStringIO, imap202122operators = {23 'eq': '==',
42 unmodified lines
66 """Does the node have a safe representation?"""67 if value is None or value is NotImplemented or value is Ellipsis:68 return True69 if isinstance(value, (bool, int, float, complex, range_type,72 Markup) + six.string_types):70 Markup) + string_types):71 return True72 if isinstance(value, (tuple, list, set, frozenset)):73 for item in value:74 if not has_safe_repr(item):75 return False76 return True77 elif isinstance(value, dict):80 for key, value in six.iteritems(value):78 for key, value in iteritems(value):79 if not has_safe_repr(key):80 return False81 if not has_safe_repr(value):82 return False
281 unmodified lines
364365 def __init__(self, environment, name, filename, stream=None,366 defer_init=False):367 if stream is None:370 stream = StringIO()368 stream = NativeStringIO()369 self.environment = environment370 self.name = name371 self.filename = filename372 self.stream = stream
165 unmodified lines
538 for kwarg in node.kwargs:539 self.write(', ')540 self.visit(kwarg, frame)541 if extra_kwargs is not None:544 for key, value in six.iteritems(extra_kwargs):542 for key, value in iteritems(extra_kwargs):543 self.write(', %s=%s' % (key, value))544 if node.dyn_args:545 self.write(', *')546 self.visit(node.dyn_args, frame)
7 unmodified lines
554 self.write('%r: ' % kwarg.key)555 self.visit(kwarg.value, frame)556 self.write(', ')557 if extra_kwargs is not None:560 for key, value in six.iteritems(extra_kwargs):558 for key, value in iteritems(extra_kwargs):559 self.write('%r: %s, ' % (key, value))560 if node.dyn_kwargs is not None:561 self.write('}, **')562 self.visit(node.dyn_kwargs, frame)
58 unmodified lines
621 return aliases622623 def pop_scope(self, aliases, frame):624 """Restore all aliases and delete unused variables."""627 for name, alias in six.iteritems(aliases):625 for name, alias in iteritems(aliases):626 self.writeline('l_%s = %s' % (name, alias))627 to_delete = set()628 for name in frame.identifiers.declared_locally:629 if name not in aliases:
193 unmodified lines
823 self.writeline('yield event')824 self.outdent(2 + (not self.has_known_extends))825826 # at this point we now have the blocks collected and can visit them too.829 for name, block in six.iteritems(self.blocks):827 for name, block in iteritems(self.blocks):828 block_frame = Frame(eval_ctx)829 block_frame.inspect(block.body)830 block_frame.block = name831 self.writeline('def block_%s(context%s):' % (name, envenv),
95 unmodified lines
927 self.indent()928929 func_name = 'get_or_select_template'930 if isinstance(node.template, nodes.Const):933 if isinstance(node.template.value, six.string_types):931 if isinstance(node.template.value, string_types):932 func_name = 'get_template'933 elif isinstance(node.template.value, (tuple, list)):934 func_name = 'select_template'935 elif isinstance(node.template, (nodes.Tuple, nodes.List)):
100 unmodified lines
1036 self.writeline('context.exported_vars.discard(%r)' %1037 discarded_names[0])1038 else:1039 self.writeline('context.exported_vars.difference_'1042 'update((%s))' % ', '.join(map(repr, discarded_names)))1040 'update((%s))' % ', '.join(imap(repr, discarded_names)))10411042 def visit_For(self, node, frame):1043 # when calculating the nodes for the inner frame we have to exclude1044 # the iterator contents from it
176 unmodified lines
1221 if self.has_known_extends and frame.require_output_check:1222 return12231224 if self.environment.finalize:1227 finalize = lambda x: six.text_type(self.environment.finalize(x))1225 finalize = lambda x: text_type(self.environment.finalize(x))1226 else:1229 finalize = six.text_type1227 finalize = text_type12281229 # if we are inside a frame that requires output checking, we do so1230 outdent_later = False1231 if frame.require_output_check:
140 unmodified lines
1372 self.writeline('context.exported_vars.add(%r)' %1373 public_names[0])1374 else:1375 self.writeline('context.exported_vars.update((%s))' %1378 ', '.join(map(repr, public_names)))1376 ', '.join(imap(repr, public_names)))13771378 # -- Expression Visitors13791380 def visit_Name(self, node, frame):
266 unmodified lines
modified:jinja2/debug.py+9 added-9 removed
11 unmodified lines
12"""13import sys14import traceback15from types import TracebackType16from jinja2.utils import CodeType, missing, internal_code16from jinja2.utils import missing, internal_code17from jinja2.exceptions import TemplateSyntaxError18import six18from jinja2._compat import iteritems, reraise, code_type1920# on pypy we can take advantage of transparent proxies21try:22 from __pypy__ import tproxy
166 unmodified lines
189 # if we don't have any exceptions in the frames left, we have to190 # reraise it unchanged.191 # XXX: can we backup here? when could this happen?192 if not frames:193 six.reraise(exc_info[0], exc_info[1], exc_info[2])193 reraise(exc_info[0], exc_info[1], exc_info[2])194195 return ProcessedTraceback(exc_info[0], exc_info[1], frames)196197
8 unmodified lines
206 if ctx:207 locals = ctx.get_all()208 else:209 locals = {}210 for name, value in six.iteritems(real_locals):210 for name, value in iteritems(real_locals):211 if name.startswith('l_') and value is not missing:212 locals[name[2:]] = value213214 # if there is a local called __jinja_exception__, we get
29 unmodified lines
244 elif function.startswith('block_'):245 location = 'block "%s"' % function[6:]246 else:247 location = 'template'248 code = CodeType(0, code.co_nlocals, code.co_stacksize,249 code.co_flags, code.co_code, code.co_consts,250 code.co_names, code.co_varnames, filename,251 location, code.co_firstlineno,252 code.co_lnotab, (), ())248 code = code_type(0, code.co_nlocals, code.co_stacksize,249 code.co_flags, code.co_code, code.co_consts,250 code.co_names, code.co_varnames, filename,251 location, code.co_firstlineno,252 code.co_lnotab, (), ())253 except:254 pass255256 # execute the code and catch the new traceback
81 unmodified lines
modified:jinja2/environment.py+19 added-19 removed
25 unmodified lines
26from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \27 TemplatesNotFound, TemplateRuntimeError28from jinja2.utils import import_string, LRUCache, Markup, missing, \29 concat, consume, internalcode, _encode_filename30import six30from jinja2._compat import imap, ifilter, string_types, iteritems, \31 text_type, reraise, PY3, Iterator, next32from functools import reduce32from six.moves import filter, map333435# for direct template usage we have up to ten living environments36_spontaneous_environments = LRUCache(10)
42 unmodified lines
79 Returns a dict of instantiated environments.80 """81 result = {}82 for extension in extensions:83 if isinstance(extension, six.string_types):83 if isinstance(extension, string_types):84 extension = import_string(extension)85 result[extension.identifier] = extension(environment)86 return result87
226 unmodified lines
314 """Add the items to the instance of the environment if they do not exist315 yet. This is used by :ref:`extensions <writing-extensions>` to register316 callbacks and configuration values without breaking inheritance.317 """318 for key, value in six.iteritems(attributes):318 for key, value in iteritems(attributes):319 if not hasattr(self, key):320 setattr(self, key, value)321322 def overlay(self, block_start_string=missing, block_end_string=missing,
23 unmodified lines
346 rv.__dict__.update(self.__dict__)347 rv.overlayed = True348 rv.linked_to = self349350 for key, value in six.iteritems(args):350 for key, value in iteritems(args):351 if value is not missing:352 setattr(rv, key, value)353354 if cache_size is not missing:
1 unmodified line
356 else:357 rv.cache = copy_cache(self.cache)358359 rv.extensions = {}360 for key, value in six.iteritems(self.extensions):360 for key, value in iteritems(self.extensions):361 rv.extensions[key] = value.bind(rv)362 if extensions is not missing:363 rv.extensions.update(load_extensions(rv, extensions))364
10 unmodified lines
375 """Get an item or attribute of an object but prefer the item."""376 try:377 return obj[argument]378 except (TypeError, LookupError):379 if isinstance(argument, six.string_types):379 if isinstance(argument, string_types):380 try:381 attr = str(argument)382 except Exception:383 pass
82 unmodified lines
466 This does not perform preprocessing. If you want the preprocessing467 of the extensions to be applied you have to filter source through468 the :meth:`preprocess` method.469 """470 source = six.text_type(source)470 source = text_type(source)471 try:472 return self.lexer.tokeniter(source, name, filename)473 except TemplateSyntaxError:474 exc_info = sys.exc_info()
4 unmodified lines
479 called for all parsing and compiling methods but *not* for :meth:`lex`480 because there you usually only want the actual source tokenized.481 """482 return reduce(lambda s, e: e.preprocess(s, name, filename),483 self.iter_extensions(), six.text_type(source))483 self.iter_extensions(), text_type(source))484485 def _tokenize(self, source, name, filename=None, state=None):486 """Called by the parser to do the preprocessing and filtering487 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
45 unmodified lines
533 `defer_init` parameter added.534 """535 source_hint = None536 try:537 if isinstance(source, six.string_types):537 if isinstance(source, string_types):538 source_hint = source539 source = self._parse(source, name, filename)540 if self.optimized:541 source = optimize(source, self)
165 unmodified lines
707 'can be passed, but not both')708 filter_func = lambda x: '.' in x and \709 x.rsplit('.', 1)[1] in extensions710 if filter_func is not None:711 x = filter(filter_func, x)711 x = ifilter(filter_func, x)712 return x713714 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):715 """Exception handling helper. This is used internally to either raise
14 unmodified lines
730 return self.exception_formatter(traceback)731 if self.exception_handler is not None:732 self.exception_handler(traceback)733 exc_type, exc_value, tb = traceback.standard_exc_info734 six.reraise(exc_type, exc_value, tb)734 reraise(exc_type, exc_value, tb)735736 def join_path(self, template, parent):737 """Join a template with the parent. By default all the lookups are738 relative to the loader root so this method returns the `template`
78 unmodified lines
817 :meth:`get_template`.818819 .. versionadded:: 2.3820 """821 if isinstance(template_name_or_list, six.string_types):821 if isinstance(template_name_or_list, string_types):822 return self.get_template(template_name_or_list, parent, globals)823 elif isinstance(template_name_or_list, Template):824 return template_name_or_list825 return self.select_template(template_name_or_list, parent, globals)
213 unmodified lines
10391040 @property1041 def debug_info(self):1042 """The debug info mapping."""1043 return [tuple(map(int, x.split('='))) for x in1043 return [tuple(imap(int, x.split('='))) for x in1044 self._debug_info.split('&')]10451046 def __repr__(self):1047 if self.name is None:
18 unmodified lines
1066 return Markup(concat(self._body_stream))10671068 def __str__(self):1069 s = self.__unicode__()1070 return s if six.PY3 else s.encode('utf-8')1070 return s if PY3 else s.encode('utf-8')10711072 def __unicode__(self):1073 return concat(self._body_stream)1074
23 unmodified lines
1098 rv = None1099 return rv110011011102class TemplateStream(six.Iterator):1102class TemplateStream(Iterator):1103 """A template stream works pretty much like an ordinary python generator1104 but it can buffer multiple items to reduce the number of total iterations.1105 Per default the output is unbuffered which means that for every unbuffered1106 instruction in the template one unicode string is yielded.
16 unmodified lines
11231124 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1125 """1126 close = False1127 if isinstance(fp, six.string_types):1127 if isinstance(fp, string_types):1128 fp = open(fp, encoding is None and 'w' or 'wb')1129 close = True1130 try:1131 if encoding is not None:
10 unmodified lines
1142 fp.close()11431144 def disable_buffering(self):1145 """Disable the output buffering."""1146 self._next = lambda: six.next(self._gen)1146 self._next = lambda: next(self._gen)1147 self.buffered = False11481149 def enable_buffering(self, size=5):1150 """Enable buffering. Buffer `size` items before yielding them."""
19 unmodified lines
1170 del buf[:]1171 c_size = 011721173 self.buffered = True1174 self._next = lambda: six.next(generator(lambda: six.next(self._gen)))1174 self._next = lambda: next(generator(lambda: next(self._gen)))11751176 def __iter__(self):1177 return self1178
7 unmodified lines
modified:jinja2/exceptions.py+10 added-8 removed
7 unmodified lines
8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import sys12import six13from six.moves import map12from jinja2._compat import imap, text_type, PY3131415class TemplateError(Exception):16 """Baseclass for all template errors."""1718 if sys.version_info[0] < 3:19 def __init__(self, message=None):20 if message is not None:22 message = six.text_type(message).encode('utf-8')21 message = text_type(message).encode('utf-8')22 Exception.__init__(self, message)2324 @property25 def message(self):
47 unmodified lines
7374 def __init__(self, names=(), message=None):75 if message is None:76 message = u'none of the templates given were found: ' + \78 u', '.join(map(six.text_type, names))77 u', '.join(imap(text_type, names))78 TemplateNotFound.__init__(self, names and names[-1] or None, message)79 self.templates = list(names)8081
10 unmodified lines
92 # this is set to True if the debug.translate_syntax_error93 # function translated the syntax error into a new traceback94 self.translated = False9597 def __str__(self):98 s = self.__unicode__()99 return s if six.PY3 else s.encode('utf-8')10096 def __unicode__(self):97 # for translated errors we only return the message98 if self.translated:99 return self.message
15 unmodified lines
115 lines.append(' ' + line.strip())116117 return u'\n'.join(lines)118119 if PY3:120 __str__ = __unicode__121 del __unicode__122 else:123 def __str__(self):124 return self.__unicode__().encode('utf-8')125126127class TemplateAssertionError(TemplateSyntaxError):128 """Like a template syntax error, but covers cases where something in the129 template caused an error at compile time that wasn't necessarily caused130 by a syntax error. However it's a direct subclass of
24 unmodified lines
modified:jinja2/ext.py+5 added-6 removed
18 unmodified lines
19from jinja2.environment import Environment20from jinja2.runtime import concat21from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError22from jinja2.utils import contextfunction, import_string, Markup23from jinja2._compat import next24import six23from jinja2._compat import next, with_metaclass, string_types, iteritems242526# the only real useful gettext functions for a Jinja template. Note27# that ugettext must be assigned to gettext as Jinja doesn't support
9 unmodified lines
37 rv.identifier = rv.__module__ + '.' + rv.__name__38 return rv394042class Extension(six.with_metaclass(ExtensionRegistry, object)):41class Extension(with_metaclass(ExtensionRegistry, object)):42 """Extensions can be used to add extra functionality to the Jinja template43 system at the parser level. Custom extensions are bound to an environment44 but may not store environment specific data on `self`. The reason for45 this is that an extension can be bound to another environment (for
162 unmodified lines
208 for key in 'gettext', 'ngettext':209 self.environment.globals.pop(key, None)210211 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):213 if isinstance(source, six.string_types):212 if isinstance(source, string_types):213 source = self.environment.parse(source)214 return extract_from_ast(source, gettext_functions)215216 def parse(self, parser):
150 unmodified lines
367 # in case newstyle gettext is used, the method is powerful368 # enough to handle the variable expansion and autoescape369 # handling itself370 if self.environment.newstyle_gettext:372 for key, value in six.iteritems(variables):371 for key, value in iteritems(variables):372 # the function adds that later anyways in case num was373 # called num, so just skip it.374 if num_called_num and key == 'num':375 continue
113 unmodified lines
489490 strings = []491 for arg in node.args:492 if isinstance(arg, nodes.Const) and \494 isinstance(arg.value, six.string_types):493 isinstance(arg.value, string_types):494 strings.append(arg.value)495 else:496 strings.append(None)497
140 unmodified lines
modified:jinja2/filters.py+19 added-21 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12import math13import six1314from random import choice15from operator import itemgetter16from itertools import groupby17from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \18 unicode_urlencode19from jinja2.runtime import Undefined20from jinja2.exceptions import FilterArgumentError22from jinja2._compat import next23from six.moves import map21from jinja2._compat import next, imap, string_types, text_type, iteritems222324_word_re = re.compile(r'\w+(?u)')25
29 unmodified lines
55 """Returns a callable that looks up the given attribute from a56 passed object with the rules of the environment. Dots are allowed57 to access attributes of attributes.58 """61 if not isinstance(attribute, six.string_types) or '.' not in attribute:59 if not isinstance(attribute, string_types) or '.' not in attribute:60 return lambda x: environment.getitem(x, attribute)61 attribute = attribute.split('.')62 def attrgetter(item):63 for part in attribute:
5 unmodified lines
69def do_forceescape(value):70 """Enforce HTML escaping. This will probably double escape variables."""71 if hasattr(value, '__html__'):72 value = value.__html__()75 return escape(six.text_type(value))73 return escape(text_type(value))747576def do_urlencode(value):77 """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
2 unmodified lines
80 .. versionadded:: 2.781 """82 itemiter = None83 if isinstance(value, dict):86 itemiter = six.iteritems(value)87 elif not isinstance(value, six.string_types):84 itemiter = iteritems(value)85 elif not isinstance(value, string_types):86 try:87 itemiter = iter(value)88 except TypeError:89 pass
21 unmodified lines
111 """112 if count is None:113 count = -1114 if not eval_ctx.autoescape:117 return six.text_type(s).replace(six.text_type(old), six.text_type(new), count)115 return text_type(s).replace(text_type(old), text_type(new), count)116 if hasattr(old, '__html__') or hasattr(new, '__html__') and \117 not hasattr(s, '__html__'):118 s = escape(s)119 else:
36 unmodified lines
156 if the filter returned something unless the second parameter is false.157 """158 rv = u' '.join(159 u'%s="%s"' % (escape(key), escape(value))162 for key, value in six.iteritems(d)160 for key, value in iteritems(d)161 if value is not None and not isinstance(value, Undefined)162 )163 if autospace and rv:164 rv = u' ' + rv
46 unmodified lines
211 raise FilterArgumentError('You can only sort by either '212 '"key" or "value"')213 def sort_func(item):214 value = item[pos]217 if isinstance(value, six.string_types) and not case_sensitive:215 if isinstance(value, string_types) and not case_sensitive:216 value = value.lower()217 return value218219 return sorted(value.items(), key=sort_func)
28 unmodified lines
248 The `attribute` parameter was added.249 """250 if not case_sensitive:251 def sort_func(item):254 if isinstance(item, six.string_types):252 if isinstance(item, string_types):253 item = item.lower()254 return item255 else:256 sort_func = None
49 unmodified lines
306 .. versionadded:: 2.6307 The `attribute` parameter was added.308 """309 if attribute is not None:312 value = map(make_attrgetter(eval_ctx.environment, attribute), value)310 value = imap(make_attrgetter(eval_ctx.environment, attribute), value)311312 # no automatic escaping? joining is a lot eaiser then313 if not eval_ctx.autoescape:316 return six.text_type(d).join(map(six.text_type, value))314 return text_type(d).join(imap(text_type, value))315316 # if the delimiter doesn't have an html representation we check317 # if any of the items has. If yes we do a coercion to Markup318 if not hasattr(d, '__html__'):
2 unmodified lines
321 for idx, item in enumerate(value):322 if hasattr(item, '__html__'):323 do_escape = True324 else:327 value[idx] = six.text_type(item)325 value[idx] = text_type(item)326 if do_escape:327 d = escape(d)328 else:331 d = six.text_type(d)329 d = text_type(d)330 return d.join(value)331332 # no html involved, to normal joining335 return soft_unicode(d).join(map(soft_unicode, value))333 return soft_unicode(d).join(imap(soft_unicode, value))334335336def do_center(value, width=80):337 """Centers the value in a field of a given width."""340 return six.text_type(value).center(width)338 return text_type(value).center(width)339340341@environmentfilter342def do_first(environment, seq):
206 unmodified lines
549 """Strip SGML/XML tags and replace adjacent whitespace by one space.550 """551 if hasattr(value, '__html__'):552 value = value.__html__()555 return Markup(six.text_type(value)).striptags()553 return Markup(text_type(value)).striptags()554555556def do_slice(value, slices, fill_with=None):557 """Slice an iterator and return a list of lists containing
166 unmodified lines
724 The `attribute` parameter was added to allow suming up over725 attributes. Also the `start` parameter was moved on to the right.726 """727 if attribute is not None:730 iterable = map(make_attrgetter(environment, attribute), iterable)728 iterable = imap(make_attrgetter(environment, attribute), iterable)729 return sum(iterable, start)730731732def do_list(value):
11 unmodified lines
744745746def do_mark_unsafe(value):747 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""750 return six.text_type(value)748 return text_type(value)749750751def do_reverse(value):752 """Reverse the object or return an iterator the iterates over it the other753 way round.754 """757 if isinstance(value, six.string_types):755 if isinstance(value, string_types):756 return value[::-1]757 try:758 return reversed(value)759 except TypeError:
224 unmodified lines
modified:jinja2/lexer.py+7 added-8 removed
13 unmodified lines
14 :copyright: (c) 2010 by the Jinja Team.15 :license: BSD, see LICENSE for more details.16"""17import re18import six1819from operator import itemgetter20from collections import deque21from jinja2.exceptions import TemplateSyntaxError22from jinja2.utils import LRUCache24from jinja2._compat import next23from jinja2._compat import next, iteritems, Iterator, text_type242526# cache for the lexers. Exists in order to be able to have multiple27# environments with the same lexer
105 unmodified lines
133 ',': TOKEN_COMMA,134 ';': TOKEN_SEMICOLON135}136138reverse_operators = dict([(v, k) for k, v in six.iteritems(operators)])137reverse_operators = dict([(v, k) for k, v in iteritems(operators)])138assert len(operators) == len(reverse_operators), 'operators dropped'139operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in140 sorted(operators, key=lambda x: -len(x))))141
127 unmodified lines
269 self.value270 )271272274class TokenStreamIterator(six.Iterator):273class TokenStreamIterator(Iterator):274 """The iterator for tokenstreams. Iterate over the stream275 until the eof token is reached.276 """277
11 unmodified lines
289 next(self.stream)290 return token291292294class TokenStream(six.Iterator):293class TokenStream(Iterator):294 """A token stream is an iterable that yields :class:`Token`\s. The295 parser however does not iterate over it but calls :meth:`next` to go296 one token ahead. The current active token is stored as :attr:`current`.297 """
298 unmodified lines
596 def tokeniter(self, source, name, filename=None, state=None):597 """This method tokenizes the text and returns the tokens in a598 generator. Use this method if you just want to tokenize a template.599 """601 source = six.text_type(source)600 source = text_type(source)601 lines = source.splitlines()602 if self.keep_trailing_newline and source:603 for newline in ('\r\n', '\r', '\n'):604 if source.endswith(newline):
39 unmodified lines
644 # bygroup is a bit more complex, in that case we645 # yield for the current token the first named646 # group that matched647 elif token == '#bygroup':649 for key, value in six.iteritems(m.groupdict()):648 for key, value in iteritems(m.groupdict()):649 if value is not None:650 yield lineno, key, value651 lineno += value.count('\n')652 break
48 unmodified lines
701 if new_state == '#pop':702 stack.pop()703 # resolve the new state by group checking704 elif new_state == '#bygroup':706 for key, value in six.iteritems(m.groupdict()):705 for key, value in iteritems(m.groupdict()):706 if value is not None:707 stack.append(key)708 break709 else:
27 unmodified lines
modified:jinja2/loaders.py+6 added-9 removed
11 unmodified lines
12import sys13import weakref14from types import ModuleType15from os import path16import six17try:18 from hashlib import sha116from hashlib import sha119except ImportError:20 from sha import new as sha117from jinja2.exceptions import TemplateNotFound18from jinja2.utils import open_if_exists, internalcode19from jinja2._compat import string_types, iteritems202122def split_template_path(template):23 """Split a path into segments and perform a sanity check. If it detects
126 unmodified lines
150 by setting the `encoding` parameter to something else.151 """152153 def __init__(self, searchpath, encoding='utf-8'):157 if isinstance(searchpath, six.string_types):154 if isinstance(searchpath, string_types):155 searchpath = [searchpath]156 self.searchpath = list(searchpath)157 self.encoding = encoding158
144 unmodified lines
303 def get_source(self, environment, template):304 rv = self.load_func(template)305 if rv is None:306 raise TemplateNotFound(template)310 elif isinstance(rv, six.string_types):307 elif isinstance(rv, string_types):308 return rv, None, None309 return rv310311
44 unmodified lines
356 raise TemplateNotFound(name)357358 def list_templates(self):359 result = []363 for prefix, loader in six.iteritems(self.mapping):360 for prefix, loader in iteritems(self.mapping):361 for template in loader.list_templates():362 result.append(prefix + self.delimiter + template)363 return result364
63 unmodified lines
428429 # create a fake module that looks for the templates in the430 # path given.431 mod = _TemplateModule(package_name)435 if isinstance(path, six.string_types):432 if isinstance(path, string_types):433 path = [path]434 else:435 path = list(path)436 mod.__path__ = path
35 unmodified lines
modified:jinja2/meta.py+5 added-4 removed
9 unmodified lines
10 :license: BSD, see LICENSE for more details.11"""12from jinja2 import nodes13from jinja2.compiler import CodeGenerator14import six14from jinja2._compat import string_types151617class TrackingCodeGenerator(CodeGenerator):18 """We abuse the code generator for introspection."""1920 def __init__(self, environment):
56 unmodified lines
77 for template_name in node.template.items:78 # something const, only yield the strings and ignore79 # non-string consts that really just make no sense80 if isinstance(template_name, nodes.Const):80 if isinstance(template_name.value, six.string_types):81 if isinstance(template_name.value, string_types):82 yield template_name.value83 # something dynamic in there84 else:85 yield None
1 unmodified line
87 else:88 yield None89 continue90 # constant is a basestring, direct template name90 if isinstance(node.template.value, six.string_types):91 if isinstance(node.template.value, string_types):92 yield node.template.value93 # a tuple or list (latter *should* not happen) made of consts,94 # yield the consts that are strings. We could warn here for95 # non string values96 elif isinstance(node, nodes.Include) and \97 isinstance(node.template.value, (tuple, list)):98 for template_name in node.template.value:98 if isinstance(template_name, six.string_types):99 if isinstance(template_name, string_types):100 yield template_name101 # something else we don't care about, we could warn here102 else:103 yield None
modified:jinja2/nodes.py+7 added-8 removed
10 unmodified lines
1112 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD, see LICENSE for more details.14"""15import six15import operator1617from collections import deque19from jinja2.utils import Markup, MethodType, FunctionType20from jinja2._compat import next21from six.moves import zip18from jinja2.utils import Markup19from jinja2._compat import next, izip, with_metaclass, text_type, \20 method_type, function_type212223#: the types we support for context functions25_context_function_types = (FunctionType, MethodType)24_context_function_types = (function_type, method_type)252627_binop_to_func = {28 '*': operator.mul,
74 unmodified lines
103 return EvalContext(node.environment)104 return ctx105106108class Node(six.with_metaclass(NodeType, object)):107class Node(with_metaclass(NodeType, object)):108 """Baseclass for all Jinja2 nodes. There are a number of nodes available109 of different types. There are four major types:110111 - :class:`Stmt`: statements
25 unmodified lines
137 self.__class__.__name__,138 len(self.fields),139 len(self.fields) != 1 and 's' or ''140 ))142 for name, arg in zip(self.fields, fields):141 for name, arg in izip(self.fields, fields):142 setattr(self, name, arg)143 for attr in self.attributes:144 setattr(self, attr, attributes.pop(attr, None))145 if attributes:
542 unmodified lines
688 fields = ('nodes',)689690 def as_const(self, eval_ctx=None):691 eval_ctx = get_eval_context(self, eval_ctx)693 return ''.join(six.text_type(x.as_const(eval_ctx)) for x in self.nodes)692 return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)693694695class Compare(Expr):696 """Compares an expression with some other expressions. `ops` must be a
216 unmodified lines
modified:jinja2/runtime.py+24 added-19 removed
12 unmodified lines
13from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \14 internalcode, object_type_repr15from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17from jinja2._compat import next18import six19from six.moves import map17from jinja2._compat import next, imap, text_type, iteritems, Iterator, \18 string_types, PY3192021# these variables are exported to the template runtime22__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
17 unmodified lines
4041def markup_join(seq):42 """Concatenation that escapes if necessary and converts to unicode."""43 buf = []45 iterator = map(soft_unicode, seq)44 iterator = imap(soft_unicode, seq)45 for arg in iterator:46 buf.append(arg)47 if hasattr(arg, '__html__'):48 return Markup(u'').join(chain(buf, iterator))
1 unmodified line
505152def unicode_join(seq):53 """Simple args to unicode conversion and concatenation."""55 return concat(map(six.text_type, seq))54 return concat(imap(text_type, seq))555657def new_context(environment, template_name, blocks, vars=None,58 shared=None, globals=None, locals=None):
8 unmodified lines
67 # if the parent is shared a copy should be created because68 # we don't want to modify the dict passed69 if shared:70 parent = dict(parent)72 for key, value in six.iteritems(locals):71 for key, value in iteritems(locals):72 if key[:2] == 'l_' and value is not missing:73 parent[key[2:]] = value74 return Context(environment, parent, template_name, blocks)75
47 unmodified lines
123124 # create the initial mapping of blocks. Whenever template inheritance125 # takes place the runtime will update this mapping with the new blocks126 # from the template.128 self.blocks = dict((k, [v]) for k, v in six.iteritems(blocks))127 self.blocks = dict((k, [v]) for k, v in iteritems(blocks))128129 def super(self, name, current):130 """Render a parent block."""131 try:
74 unmodified lines
206 context = new_context(self.environment, self.name, {},207 self.parent, True, None, locals)208 context.vars.update(self.vars)209 context.eval_ctx = self.eval_ctx211 context.blocks.update((k, list(v)) for k, v in six.iteritems(self.blocks))210 context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))211 return context212213 def _all(meth):214 proxy = lambda self: getattr(self.get_all(), meth)()
140 unmodified lines
355 self.length356 )357358360class LoopContextIterator(six.Iterator):359class LoopContextIterator(Iterator):360 """The iterator for a loop context."""361 __slots__ = ('context',)362363 def __init__(self, context):
106 unmodified lines
470 """471 if self._undefined_hint is None:472 if self._undefined_obj is missing:473 hint = '%r is undefined' % self._undefined_name475 elif not isinstance(self._undefined_name, six.string_types):474 elif not isinstance(self._undefined_name, string_types):475 hint = '%s has no element %r' % (476 object_type_repr(self._undefined_obj),477 self._undefined_name478 )
18 unmodified lines
497 __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \498 __float__ = __complex__ = __pow__ = __rpow__ = \499 _fail_with_undefined_error500502 def __str__(self):503 s = self.__unicode__()504 return s if six.PY3 else s.encode('utf-8')505501 def __unicode__(self):502 return u''503504 if PY3:505 __str__ = __unicode__506 del __unicode__507 else:508 def __str__(self):509 return self.__unicode__().encode('utf-8')510511 def __len__(self):512 return 0513514 def __iter__(self):
21 unmodified lines
536 UndefinedError: 'foo' is undefined537 """538 __slots__ = ()539538 def __str__(self):539 s = self.__unicode__()540 return s if six.PY3 else s.encode('utf-8')541540 def __unicode__(self):541 if self._undefined_hint is None:542 if self._undefined_obj is missing:543 return u'{{ %s }}' % self._undefined_name
2 unmodified lines
546 self._undefined_name547 )548 return u'{{ undefined value printed: %s }}' % self._undefined_hint549550 if PY3:551 __str__ = __unicode__552 del __unicode__553554555class StrictUndefined(Undefined):556 """An undefined that barks on print and iteration as well as boolean557 tests and all kinds of comparisons. In other words: you can do nothing558 with it except checking if it's defined using the `defined` test.
12 unmodified lines
571 ...572 UndefinedError: 'foo' is undefined573 """574 __slots__ = ()573 __iter__ = __unicode__ = __str__ = __len__ = __nonzero__ = __eq__ = \575 __iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \576 __ne__ = __bool__ = Undefined._fail_with_undefined_error577578 if not PY3:579 __unicode__ = Undefined._fail_with_undefined_error580581582# remove remaining slots attributes, after the metaclass did the magic they583# are unneeded and irritating as they contain wrong data for the subclasses.584del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__
modified:jinja2/sandbox.py+7 added-8 removed
11 unmodified lines
12 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD.14"""15import operator16import six16from jinja2.environment import Environment17from jinja2.exceptions import SecurityError19from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \20 FrameType, GeneratorType18from jinja2._compat import string_types, function_type, method_type, \19 traceback_type, code_type, frame_type, generator_type202122#: maximum number of items a range may produce23MAX_RANGE = 100000
99 unmodified lines
123 True124 >>> is_internal_attribute(str, "upper")125 False126 """128 if isinstance(obj, FunctionType):127 if isinstance(obj, function_type):128 if attr in UNSAFE_FUNCTION_ATTRIBUTES:129 return True131 elif isinstance(obj, MethodType):130 elif isinstance(obj, method_type):131 if attr in UNSAFE_FUNCTION_ATTRIBUTES or \132 attr in UNSAFE_METHOD_ATTRIBUTES:133 return True134 elif isinstance(obj, type):135 if attr == 'mro':136 return True138 elif isinstance(obj, (CodeType, TracebackType, FrameType)):137 elif isinstance(obj, (code_type, traceback_type, frame_type)):138 return True140 elif isinstance(obj, GeneratorType):139 elif isinstance(obj, generator_type):140 if attr == 'gi_frame':141 return True142 return attr.startswith('__')143
154 unmodified lines
298 """Subscribe an object from sandboxed code."""299 try:300 return obj[argument]301 except (TypeError, LookupError):303 if isinstance(argument, six.string_types):302 if isinstance(argument, string_types):303 try:304 attr = str(argument)305 except Exception:306 pass
55 unmodified lines
modified:jinja2/tests.py+5 added-14 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12from jinja2.runtime import Undefined13import six13from jinja2._compat import text_type, string_types, mapping_types1415try:16 from collections import Mapping as MappingType17except ImportError:18 import UserDict19 MappingType = (UserDict.UserDict, UserDict.DictMixin, dict)1521# nose, nothing here to test22__test__ = False232416number_re = re.compile(r'^-?\d+(\.\d+)?$')17regex_type = type(number_re)1819
47 unmodified lines
676869def test_lower(value):70 """Return true if the variable is lowercased."""80 return six.text_type(value).islower()71 return text_type(value).islower()727374def test_upper(value):75 """Return true if the variable is uppercased."""85 return six.text_type(value).isupper()76 return text_type(value).isupper()777879def test_string(value):80 """Return true if the object is a string."""90 return isinstance(value, six.string_types)81 return isinstance(value, string_types)828384def test_mapping(value):85 """Return true if the object is a mapping (dict etc.).8687 .. versionadded:: 2.688 """98 return isinstance(value, MappingType)89 return isinstance(value, mapping_types)909192def test_number(value):93 """Return true if the variable is a number."""
60 unmodified lines
modified:jinja2/utils.py+8 added-28 removed
9 unmodified lines
10"""11import re12import sys13import errno14import six15from six.moves import map14try:15 from urllib.parse import quote_from_bytes as url_quote16except ImportError:17 from urllib import quote as url_quote
4 unmodified lines
22 from _thread import allocate_lock # py 323 except ImportError:24 from dummy_thread import allocate_lock25from collections import deque26from jinja2._compat import text_type, string_types, Iterator272829_word_split_re = re.compile(r'(\s+)')30_punctuation_re = re.compile(31 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (32 '|'.join(map(re.escape, ('(', '<', '&lt;'))),
33 unmodified lines
6667from keyword import iskeyword as is_python_keyword686970# common types. These do exist in the special types module too which however71# does not exist in IronPython out of the box. Also that way we don't have72# to deal with implementation specific stuff here73class _C(object):74 def method(self): pass75def _func():76 yield None77FunctionType = type(_func)78GeneratorType = type(_func())79MethodType = type(_C().method)80CodeType = type(_C.method.__code__)81try:82 raise TypeError()83except TypeError:84 _tb = sys.exc_info()[2]85 TracebackType = type(_tb)86 FrameType = type(_tb.tb_frame)87del _C, _tb, _func888970def contextfunction(f):71 """This decorator can be used to mark a function or method context callable.72 A context callable is passed the active :class:`Context` as first argument when73 called from the template. This is useful if a function wants to get access
152 unmodified lines
226 """227 trim_url = lambda x, limit=trim_url_limit: limit is not None \228 and (x[:limit] + (len(x) >=limit and '...'229 or '')) or x250 words = _word_split_re.split(six.text_type(escape(text)))230 words = _word_split_re.split(text_type(escape(text)))231 nofollow_attr = nofollow and ' rel="nofollow"' or ''232 for i, word in enumerate(words):233 match = _punctuation_re.match(word)234 if match:
78 unmodified lines
313314 If non strings are provided they are converted to their unicode315 representation first.316 """337 if not isinstance(obj, six.string_types):338 obj = six.text_type(obj)339 if isinstance(obj, six.text_type):317 if not isinstance(obj, string_types):318 obj = text_type(obj)319 if isinstance(obj, text_type):320 obj = obj.encode(charset)341 return six.text_type(url_quote(obj))321 return text_type(url_quote(obj))322323324class LRUCache(object):325 """A simple LRU Cache implementation."""
179 unmodified lines
505except ImportError:506 pass507508529class Cycler(six.Iterator):509class Cycler(Iterator):510 """A cycle helper for templates."""511512 def __init__(self, *items):513 if not items:
36 unmodified lines