Skip to content
Myr

python 3 port: manual fixes, remove 2to3 from setup.py, remove fixers

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

authored by Thomas Waldmann · committed by Thomas Waldmann · parent e000355 · Browse files · 28 files+235 added−269 removed
This commit

State

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

Diff stats

28 files+235 added−269 removed

  • other:+235 added−269 removed

28 files+235 added−269 removed

deleted:custom_fixers/__init__.py
deleted:custom_fixers/fix_alt_unicode.py-13 removed
1from lib2to3 import fixer_base2from lib2to3.fixer_util import Name, BlankLine345class FixAltUnicode(fixer_base.BaseFix):6 PATTERN = """7 func=funcdef< 'def' name='__unicode__'8 parameters< '(' NAME ')' > any+ >9 """1011 def transform(self, node, results):12 name = results['name']13 name.replace(Name('__str__', prefix=name.prefix))
deleted:custom_fixers/fix_broken_reraising.py-21 removed
1from lib2to3 import fixer_base, pytree2from lib2to3.fixer_util import Name, BlankLine, Name, Attr, ArgList345class FixBrokenReraising(fixer_base.BaseFix):6 PATTERN = """7 raise_stmt< 'raise' any ',' val=any ',' tb=any >8 """910 # run before the broken 2to3 checker with the same goal11 # tries to rewrite it with a rule that does not work out for jinja12 run_order = 11314 def transform(self, node, results):15 tb = results['tb'].clone()16 tb.prefix = ''17 with_tb = Attr(results['val'].clone(), Name('with_traceback')) + \18 [ArgList([tb])]19 new = pytree.Node(self.syms.simple_stmt, [Name("raise")] + with_tb)20 new.prefix = node.prefix21 return new
deleted:custom_fixers/fix_xrange2.py-11 removed
1from lib2to3 import fixer_base2from lib2to3.fixer_util import Name, BlankLine345# whyever this is necessary..67class FixXrange2(fixer_base.BaseFix):8 PATTERN = "'xrange'"910 def transform(self, node, results):11 node.replace(Name('range', prefix=node.prefix))
modified:jinja2/_markupsafe/__init__.py+26 added-24 removed
7 unmodified lines
8 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from itertools import imap12import six13from six.moves import map14from six.moves import zip15try:16 unichr = unichr # py217except NameError:18 unichr = chr # py3191720__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']212223_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')24_entity_re = re.compile(r'&([^;]+);')252625class Markup(unicode):27class Markup(six.text_type):28 r"""Marks a string as being safe for inclusion in HTML/XML output without29 needing to be escaped. This implements the `__html__` interface a couple30 of frameworks and web applications use. :class:`Markup` is a direct31 subclass of `unicode` and provides all the methods of `unicode` just that
40 unmodified lines
72 def __new__(cls, base=u'', encoding=None, errors='strict'):73 if hasattr(base, '__html__'):74 base = base.__html__()75 if encoding is None:74 return unicode.__new__(cls, base)75 return unicode.__new__(cls, base, encoding, errors)76 return six.text_type.__new__(cls, base)77 return six.text_type.__new__(cls, base, encoding, errors)7879 def __html__(self):80 return self8182 def __add__(self, other):81 if hasattr(other, '__html__') or isinstance(other, basestring):83 if hasattr(other, '__html__') or isinstance(other, six.string_types):84 return self.__class__(six.text_type(self) + six.text_type(escape(other)))85 return NotImplemented8687 def __radd__(self, other):86 if hasattr(other, '__html__') or isinstance(other, basestring):88 if hasattr(other, '__html__') or isinstance(other, six.string_types):89 return self.__class__(six.text_type(escape(other)) + six.text_type(self))90 return NotImplemented9192 def __mul__(self, num):93 if isinstance(num, (int, long)):92 return self.__class__(unicode.__mul__(self, num))94 return self.__class__(six.text_type.__mul__(self, num))95 return NotImplemented96 __rmul__ = __mul__9798 def __mod__(self, arg):99 if isinstance(arg, tuple):98 arg = tuple(imap(_MarkupEscapeHelper, arg))100 arg = tuple(map(_MarkupEscapeHelper, arg))101 else:102 arg = _MarkupEscapeHelper(arg)101 return self.__class__(unicode.__mod__(self, arg))103 return self.__class__(six.text_type.__mod__(self, arg))104105 def __repr__(self):106 return '%s(%s)' % (107 self.__class__.__name__,106 unicode.__repr__(self)108 six.text_type.__repr__(self)109 )110111 def join(self, seq):110 return self.__class__(unicode.join(self, imap(escape, seq)))111 join.__doc__ = unicode.join.__doc__112 return self.__class__(six.text_type.join(self, map(escape, seq)))113 join.__doc__ = six.text_type.join.__doc__114115 def split(self, *args, **kwargs):114 return map(self.__class__, unicode.split(self, *args, **kwargs))115 split.__doc__ = unicode.split.__doc__116 return map(self.__class__, six.text_type.split(self, *args, **kwargs))117 split.__doc__ = six.text_type.split.__doc__118119 def rsplit(self, *args, **kwargs):118 return map(self.__class__, unicode.rsplit(self, *args, **kwargs))119 rsplit.__doc__ = unicode.rsplit.__doc__120 return map(self.__class__, six.text_type.rsplit(self, *args, **kwargs))121 rsplit.__doc__ = six.text_type.rsplit.__doc__122123 def splitlines(self, *args, **kwargs):122 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))123 splitlines.__doc__ = unicode.splitlines.__doc__124 return map(self.__class__, six.text_type.splitlines(self, *args, **kwargs))125 splitlines.__doc__ = six.text_type.splitlines.__doc__126127 def unescape(self):128 r"""Unescape markup again into an unicode string. This also resolves129 known HTML4 and XHTML entities:
38 unmodified lines
168 return cls(rv)169 return rv170171 def make_wrapper(name):170 orig = getattr(unicode, name)172 orig = getattr(six.text_type, name)173 def func(self, *args, **kwargs):174 args = _escape_argspec(list(args), enumerate(args))175 _escape_argspec(kwargs, six.iteritems(kwargs))176 return self.__class__(orig(self, *args, **kwargs))
7 unmodified lines
184 'translate', 'expandtabs', 'swapcase', 'zfill':185 locals()[method] = make_wrapper(method)186187 # new in python 2.5186 if hasattr(unicode, 'partition'):188 if hasattr(six.text_type, 'partition'):189 partition = make_wrapper('partition'),190 rpartition = make_wrapper('rpartition')191192 # new in python 2.6191 if hasattr(unicode, 'format'):193 if hasattr(six.text_type, 'format'):194 format = make_wrapper('format')195196 # not in python 3195 if hasattr(unicode, '__getslice__'):197 if hasattr(six.text_type, '__getslice__'):198 __getslice__ = make_wrapper('__getslice__')199200 del method, make_wrapper201202203def _escape_argspec(obj, iterable):204 """Helper for various string-wrapped functions."""205 for key, value in iterable:204 if hasattr(value, '__html__') or isinstance(value, basestring):206 if hasattr(value, '__html__') or isinstance(value, six.string_types):207 obj[key] = escape(value)208 return obj209210
20 unmodified lines
modified:jinja2/_markupsafe/_native.py+1 added-1 removed
39 unmodified lines
40def soft_unicode(s):41 """Make a string unicode if it isn't already. That way a markup42 string is not converted back to unicode.43 """44 if not isinstance(s, unicode):44 if not isinstance(s, six.text_type):45 s = six.text_type(s)46 return s
modified:jinja2/testsuite/ext.py+3 added-10 removed
15 unmodified lines
16from jinja2 import Environment, DictLoader, contextfunction, nodes17from jinja2.exceptions import TemplateAssertionError18from jinja2.ext import Extension19from jinja2.lexer import Token, count_newlines20from jinja2.utils import next20import six21from six import BytesIO2223# 2.x / 3.x24try:25 from io import BytesIO26except ImportError:27 from StringIO import StringIO as BytesIO282923importable_object = 232425_gettext_re = re.compile(r'_\((.*?)\)(?s)')26
81 unmodified lines
108 nodes.EnvironmentAttribute('sandboxed'),109 self.attr('ext_attr'),110 nodes.ImportedName(__name__ + '.importable_object'),111 nodes.ContextReference()119 ])]).set_lineno(next(parser.stream).lineno)112 ])]).set_lineno(six.advance_iterator(parser.stream).lineno)113114 def _dump(self, sandboxed, ext_attr, imported_object, context):115 return '%s|%s|%s|%s' % (116 sandboxed,
308 unmodified lines
425 {{ '<testing>' }}426 '''427 tmpl = env.from_string(tmplsource)428 assert tmpl.render(val=True).split()[0] == 'Markup'436 assert tmpl.render(val=False).split()[0] == unicode.__name__429 assert tmpl.render(val=False).split()[0] == six.text_type.__name__430431 # looking at the source we should see <testing> there in raw432 # (and then escaped as well)433 env = Environment(extensions=['jinja2.ext.autoescape'])
16 unmodified lines
modified:jinja2/testsuite/filters.py+2 added-2 removed
11 unmodified lines
12from jinja2.testsuite import JinjaTestCase1314from jinja2 import Markup, Environment15import six16from six.moves import map17from six.moves import zip16from six.moves import map, zip1718env = Environment()1920
278 unmodified lines
299 def __init__(self, value):300 self.value = value301 def __unicode__(self):302 return six.text_type(self.value)303 __str__ = __unicode__304 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')305 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'306307 def test_groupby(self):
92 unmodified lines
modified:jinja2/testsuite/lexnparse.py+26 added
13 unmodified lines
14from jinja2.testsuite import JinjaTestCase1516from jinja2 import Environment, Template, TemplateSyntaxError, \17 UndefinedError, nodes18from jinja2.lexer import Token, TokenStream, TOKEN_EOF, TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END19import six2021env = Environment()22
5 unmodified lines
28else:29 jinja_string_repr = repr303132class TokenStreamTestCase(JinjaTestCase):33 test_tokens = [Token(1, TOKEN_BLOCK_BEGIN, ''),34 Token(2, TOKEN_BLOCK_END, ''),35 ]3637 def test_simple(self):38 ts = TokenStream(self.test_tokens, "foo", "bar")39 assert ts.current.type is TOKEN_BLOCK_BEGIN40 assert bool(ts)41 assert not bool(ts.eos)42 six.advance_iterator(ts)43 assert ts.current.type is TOKEN_BLOCK_END44 assert bool(ts)45 assert not bool(ts.eos)46 six.advance_iterator(ts)47 assert ts.current.type is TOKEN_EOF48 assert not bool(ts)49 assert bool(ts.eos)5051 def test_iter(self):52 token_types = [t.type for t in TokenStream(self.test_tokens, "foo", "bar")]53 assert token_types == ['block_begin', 'block_end', ]545556class LexerTestCase(JinjaTestCase):5758 def test_raw1(self):59 tmpl = env.from_string('{% raw %}foo{% endraw %}|'
346 unmodified lines
406407408def suite():409 suite = unittest.TestSuite()410 suite.addTest(unittest.makeSuite(TokenStreamTestCase))411 suite.addTest(unittest.makeSuite(LexerTestCase))412 suite.addTest(unittest.makeSuite(ParserTestCase))413 suite.addTest(unittest.makeSuite(SyntaxTestCase))414 return suite
modified:jinja2/testsuite/regression.py+2 added-1 removed
12 unmodified lines
13from jinja2.testsuite import JinjaTestCase1415from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \16 TemplateNotFound, PrefixLoader17import six18from six.moves import map19from six.moves import zip2021env = Environment()
98 unmodified lines
120 {% endfor %}121122 ''')123123 assert tmpl.render().split() == map(unicode, list(range(1, 11))) * 5124 assert tmpl.render().split() == [six.text_type(x) for x in range(1, 11)] * 5125126 def test_weird_inline_comment(self):127 env = Environment(line_statement_prefix='%')128 self.assert_raises(TemplateSyntaxError, env.from_string,
130 unmodified lines
modified:jinja2/bccache.py+1 added-1 removed
16 unmodified lines
17from os import path, listdir18import sys19import marshal20import tempfile21import cPickle as pickle21from six.moves import cPickle as pickle22import fnmatch23try:24 from hashlib import sha125except ImportError:
276 unmodified lines
modified:jinja2/compiler.py+11 added-9 removed
6 unmodified lines
78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11from cStringIO import StringIO11from itertools import chain12from copy import deepcopy13from jinja2 import nodes14from jinja2.nodes import EvalContext15from jinja2.visitor import NodeVisitor16from jinja2.exceptions import TemplateAssertionError18from jinja2.utils import Markup, concat, escape, is_python_keyword, next17from jinja2.utils import Markup, concat, escape, is_python_keyword18import six20from six.moves import map21from six.moves import zip19from six.moves import cStringIO as StringIO20from six.moves import map, zip212223operators = {24 'eq': '==',
45 unmodified lines
70def has_safe_repr(value):71 """Does the node have a safe representation?"""72 if value is None or value is NotImplemented or value is Ellipsis:73 return True75 if isinstance(value, (bool, int, long, float, complex, basestring,76 xrange, Markup)):74 try:75 range_type = xrange76 except NameError:77 range_type = range78 if isinstance(value, (bool, int, float, complex, range_type, Markup) + six.string_types):79 return True80 if isinstance(value, (tuple, list, set, frozenset)):81 for item in value:82 if not has_safe_repr(item):
851 unmodified lines
934 self.indent()935936 func_name = 'get_or_select_template'937 if isinstance(node.template, nodes.Const):936 if isinstance(node.template.value, basestring):938 if isinstance(node.template.value, six.string_types):939 func_name = 'get_template'940 elif isinstance(node.template.value, (tuple, list)):941 func_name = 'select_template'942 elif isinstance(node.template, (nodes.Tuple, nodes.List)):
279 unmodified lines
12221223 if self.environment.finalize:1224 finalize = lambda x: six.text_type(self.environment.finalize(x))1225 else:1224 finalize = unicode1226 finalize = six.text_type12271228 # if we are inside a frame that requires output checking, we do so1229 outdent_later = False1230 if frame.require_output_check:
125 unmodified lines
1356 if frame.toplevel:1357 public_names = [x for x in assignment_frame.toplevel_assignments1358 if not x.startswith('_')]1359 if len(assignment_frame.toplevel_assignments) == 1:1358 name = next(iter(assignment_frame.toplevel_assignments))1360 name = six.advance_iterator(iter(assignment_frame.toplevel_assignments))1361 self.writeline('context.vars[%r] = l_%s' % (name, name))1362 else:1363 self.writeline('context.vars.update({')1364 for idx, name in enumerate(assignment_frame.toplevel_assignments):
290 unmodified lines
modified:jinja2/debug.py+1 added-1 removed
188 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 raise exc_info[0], exc_info[1], exc_info[2]193 six.reraise(exc_info[0], exc_info[1], exc_info[2])194195 return ProcessedTraceback(exc_info[0], exc_info[1], frames)196197
143 unmodified lines
modified:jinja2/defaults.py+1 added
6 unmodified lines
78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11from six.moves import xrange12from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner131415# defaults for the parser / lexer
26 unmodified lines
modified:jinja2/environment.py+13 added-18 removed
21 unmodified lines
22from jinja2.utils import import_string, LRUCache, Markup, missing, \23 concat, consume, internalcode, _encode_filename24import six25from functools import reduce26from six.moves import filter27from six.moves import map28from six.moves import zip26from six.moves import filter, map, zip272829# for direct template usage we have up to ten living environments30_spontaneous_environments = LRUCache(10)
42 unmodified lines
73 Returns a dict of instantiated environments.74 """75 result = {}76 for extension in extensions:79 if isinstance(extension, basestring):77 if isinstance(extension, six.string_types):78 extension = import_string(extension)79 result[extension.identifier] = extension(environment)80 return result81
272 unmodified lines
354 """Get an item or attribute of an object but prefer the item."""355 try:356 return obj[argument]357 except (TypeError, LookupError):360 if isinstance(argument, basestring):358 if isinstance(argument, six.string_types):359 try:360 attr = str(argument)361 except Exception:362 pass
113 unmodified lines
476 `defer_init` parameter added.477 """478 source_hint = None479 try:482 if isinstance(source, basestring):480 if isinstance(source, six.string_types):481 source_hint = source482 source = self._parse(source, name, filename)483 if self.optimized:484 source = optimize(source, self)
188 unmodified lines
673 return self.exception_formatter(traceback)674 if self.exception_handler is not None:675 self.exception_handler(traceback)676 exc_type, exc_value, tb = traceback.standard_exc_info679 raise exc_type, exc_value, tb677 six.reraise(exc_type, exc_value, tb)678679 def join_path(self, template, parent):680 """Join a template with the parent. By default all the lookups are681 relative to the loader root so this method returns the `template`
78 unmodified lines
760 :meth:`get_template`.761762 .. versionadded:: 2.3763 """766 if isinstance(template_name_or_list, basestring):764 if isinstance(template_name_or_list, six.string_types):765 return self.get_template(template_name_or_list, parent, globals)766 elif isinstance(template_name_or_list, Template):767 return template_name_or_list768 return self.select_template(template_name_or_list, parent, globals)
236 unmodified lines
1005 def __html__(self):1006 return Markup(concat(self._body_stream))10071008 def __str__(self):1009 s = self.__unicode__()1011 return six.text_type(self).encode('utf-8')1010 return s if six.PY3 else s.encode('utf-8')10111013 # unicode goes after __str__ because we configured 2to3 to rename1014 # __unicode__ to __str__. because the 2to3 tree is not designed to1015 # remove nodes from it, we leave the above __str__ around and let1016 # it override at runtime.1012 def __unicode__(self):1013 return concat(self._body_stream)10141015 def __repr__(self):
22 unmodified lines
1038 rv = None1039 return rv104010411047class TemplateStream(object):1042class TemplateStream(six.Iterator):1043 """A template stream works pretty much like an ordinary python generator1044 but it can buffer multiple items to reduce the number of total iterations.1045 Per default the output is unbuffered which means that for every unbuffered1046 instruction in the template one unicode string is yielded.
16 unmodified lines
10631064 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1065 """1066 close = False1072 if isinstance(fp, basestring):1067 if isinstance(fp, six.string_types):1068 fp = file(fp, 'w')1069 close = True1070 try:1071 if encoding is not None:
10 unmodified lines
1082 fp.close()10831084 def disable_buffering(self):1085 """Disable the output buffering."""1091 self._next = self._gen.next1086 self._next = lambda: six.next(self._gen)1087 self.buffered = False10881089 def enable_buffering(self, size=5):1090 """Enable buffering. Buffer `size` items before yielding them."""
19 unmodified lines
1110 del buf[:]1111 c_size = 011121113 self.buffered = True1119 self._next = generator(self._gen.next).next1114 self._next = lambda: six.next(generator(lambda: six.next(self._gen)))11151116 def __iter__(self):1117 return self11181124 def next(self):1119 def __next__(self):1120 return self._next()112111221123# hook in default template class. if anyone reads this comment: ignore that
2 unmodified lines
modified:jinja2/exceptions.py+4 added-8 removed
7 unmodified lines
8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import six12from six.moves import map13from six.moves import zip12from six.moves import map, zip131415class TemplateError(Exception):16 """Baseclass for all template errors."""
47 unmodified lines
6465 def __init__(self, names=(), message=None):66 if message is None:67 message = u'none of the templates given were found: ' + \69 u', '.join(map(unicode, names))68 u', '.join(map(six.text_type, names))69 TemplateNotFound.__init__(self, names and names[-1] or None, message)70 self.templates = list(names)7172
11 unmodified lines
84 # function translated the syntax error into a new traceback85 self.translated = False8687 def __str__(self):88 s = self.__unicode__()89 return six.text_type(self).encode('utf-8')89 return s if six.PY3 else s.encode('utf-8')9091 # unicode goes after __str__ because we configured 2to3 to rename92 # __unicode__ to __str__. because the 2to3 tree is not designed to93 # remove nodes from it, we leave the above __str__ around and let94 # it override at runtime.91 def __unicode__(self):92 # for translated errors we only return the message93 if self.translated:94 return self.message
48 unmodified lines
modified:jinja2/ext.py+16 added-16 removed
14 unmodified lines
15from jinja2.defaults import *16from jinja2.environment import Environment17from jinja2.runtime import Undefined, concat18from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError19from jinja2.utils import contextfunction, import_string, Markup, next19from jinja2.utils import contextfunction, import_string, Markup20import six212223# the only real useful gettext functions for a Jinja template. Note
10 unmodified lines
34 rv.identifier = rv.__module__ + '.' + rv.__name__35 return rv363738class Extension(object):38class Extension(six.with_metaclass(ExtensionRegistry, object)):39 """Extensions can be used to add extra functionality to the Jinja template40 system at the parser level. Custom extensions are bound to an environment41 but may not store environment specific data on `self`. The reason for42 this is that an extension can be bound to another environment (for
162 unmodified lines
205 for key in 'gettext', 'ngettext':206 self.environment.globals.pop(key, None)207208 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):209 if isinstance(source, basestring):209 if isinstance(source, six.string_types):210 source = self.environment.parse(source)211 return extract_from_ast(source, gettext_functions)212213 def parse(self, parser):214 """Parse a translatable tag."""215 lineno = next(parser.stream).lineno215 lineno = six.advance_iterator(parser.stream).lineno216 num_called_num = False217218 # find all the variables referenced. Additionally a variable can be219 # defined in the body of the trans block too, but this is checked at
15 unmodified lines
235 exc=TemplateAssertionError)236237 # expressions238 if parser.stream.current.type == 'assign':239 next(parser.stream)239 six.advance_iterator(parser.stream)240 variables[name.value] = var = parser.parse_expression()241 else:242 variables[name.value] = var = nodes.Name(name.value, 'load')243
17 unmodified lines
261262 # if we have a pluralize block, we parse that too263 if parser.stream.current.test('name:pluralize'):264 have_plural = True265 next(parser.stream)265 six.advance_iterator(parser.stream)266 if parser.stream.current.type != 'block_end':267 name = parser.stream.expect('name')268 if name.value not in variables:269 parser.fail('unknown variable %r for pluralization' %
2 unmodified lines
272 plural_expr = variables[name.value]273 num_called_num = name.value == 'num'274 parser.stream.expect('block_end')275 plural_names, plural = self._parse_block(parser, False)276 next(parser.stream)276 six.advance_iterator(parser.stream)277 referenced.update(plural_names)278 else:279 next(parser.stream)279 six.advance_iterator(parser.stream)280281 # register free names as simple name expressions282 for var in referenced:283 if var not in variables:
16 unmodified lines
300 buf = []301 while 1:302 if parser.stream.current.type == 'data':303 buf.append(parser.stream.current.value.replace('%', '%%'))304 next(parser.stream)304 six.advance_iterator(parser.stream)305 elif parser.stream.current.type == 'variable_begin':306 next(parser.stream)306 six.advance_iterator(parser.stream)307 name = parser.stream.expect('name').value308 referenced.append(name)309 buf.append('%%(%s)s' % name)310 parser.stream.expect('variable_end')311 elif parser.stream.current.type == 'block_begin':312 next(parser.stream)312 six.advance_iterator(parser.stream)313 if parser.stream.current.test('name:endtrans'):314 break315 elif parser.stream.current.test('name:pluralize'):316 if allow_pluralize:
64 unmodified lines
381 """382 tags = set(['do'])383384 def parse(self, parser):385 node = nodes.ExprStmt(lineno=next(parser.stream).lineno)385 node = nodes.ExprStmt(lineno=six.advance_iterator(parser.stream).lineno)386 node.node = parser.parse_tuple()387 return node388389
1 unmodified line
391 """Adds break and continue to the template engine."""392 tags = set(['break', 'continue'])393394 def parse(self, parser):395 token = next(parser.stream)395 token = six.advance_iterator(parser.stream)396 if token.value == 'break':397 return nodes.Break(lineno=token.lineno)398 return nodes.Continue(lineno=token.lineno)399
2 unmodified lines
402 """Adds support for a django-like with block."""403 tags = set(['with'])404405 def parse(self, parser):406 node = nodes.Scope(lineno=next(parser.stream).lineno)406 node = nodes.Scope(lineno=six.advance_iterator(parser.stream).lineno)407 assignments = []408 while parser.stream.current.type != 'block_end':409 lineno = parser.stream.current.lineno410 if assignments:
12 unmodified lines
423 """Changes auto escape rules for a scope."""424 tags = set(['autoescape'])425426 def parse(self, parser):427 node = nodes.ScopedEvalContextModifier(lineno=next(parser.stream).lineno)427 node = nodes.ScopedEvalContextModifier(lineno=six.advance_iterator(parser.stream).lineno)428 node.options = [429 nodes.Keyword('autoescape', parser.parse_expression())430 ]431 node.body = parser.parse_statements(('name:endautoescape',),
44 unmodified lines
476477 strings = []478 for arg in node.args:479 if isinstance(arg, nodes.Const) and \480 isinstance(arg.value, basestring):480 isinstance(arg.value, six.string_types):481 strings.append(arg.value)482 else:483 strings.append(None)484
137 unmodified lines
modified:jinja2/filters.py+11 added-12 removed
10 unmodified lines
11import re12import math13from random import choice14from operator import itemgetter15from itertools import imap, groupby15from itertools import groupby16from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \17 unicode_urlencode18from jinja2.runtime import Undefined19from jinja2.exceptions import FilterArgumentError20import six21from six.moves import map22from six.moves import zip21from six.moves import map, zip222324_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 """60 if not isinstance(attribute, basestring) or '.' not in attribute:59 if not isinstance(attribute, six.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:
17 unmodified lines
81 """82 itemiter = None83 if isinstance(value, dict):84 itemiter = six.iteritems(value)86 elif not isinstance(value, basestring):85 elif not isinstance(value, six.string_types):86 try:87 itemiter = iter(value)88 except TypeError:89 pass
121 unmodified lines
211 raise FilterArgumentError('You can only sort by either '212 '"key" or "value"')213 def sort_func(item):214 value = item[pos]216 if isinstance(value, basestring) and not case_sensitive:215 if isinstance(value, six.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):253 if isinstance(item, basestring):252 if isinstance(item, six.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:311 value = imap(make_attrgetter(eval_ctx.environment, attribute), value)310 value = map(make_attrgetter(eval_ctx.environment, attribute), value)311312 # no automatic escaping? joining is a lot eaiser then313 if not eval_ctx.autoescape:315 return six.text_type(d).join(imap(unicode, value))314 return six.text_type(d).join(map(six.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__'):
10 unmodified lines
329 d = six.text_type(d)330 return d.join(value)331332 # no html involved, to normal joining334 return soft_unicode(d).join(imap(soft_unicode, value))333 return soft_unicode(d).join(map(soft_unicode, value))334335336def do_center(value, width=80):337 """Centers the value in a field of a given width."""
377 unmodified lines
715 The `attribute` parameter was added to allow suming up over716 attributes. Also the `start` parameter was moved on to the right.717 """718 if attribute is not None:720 iterable = imap(make_attrgetter(environment, attribute), iterable)719 iterable = map(make_attrgetter(environment, attribute), iterable)720 return sum(iterable, start)721722723def do_list(value):
18 unmodified lines
742def do_reverse(value):743 """Reverse the object or return an iterator the iterates over it the other744 way round.745 """747 if isinstance(value, basestring):746 if isinstance(value, six.string_types):747 return value[::-1]748 try:749 return reversed(value)750 except TypeError:
81 unmodified lines
modified:jinja2/lexer.py+22 added-15 removed
16 unmodified lines
17import re18from operator import itemgetter19from collections import deque20from jinja2.exceptions import TemplateSyntaxError21from jinja2.utils import LRUCache, next21from jinja2.utils import LRUCache22import six232425# cache for the lexers. Exists in order to be able to have multiple
19 unmodified lines
4546float_re = re.compile(r'(?<!\.)\d+\.\d+')47newline_re = re.compile(r'(\r\n|\r|\n)')4849try:50 intern = intern # py251except NameError:52 import sys53 intern = sys.intern # py35455# internal the tokens and keep references to them56TOKEN_ADD = intern('add')57TOKEN_ASSIGN = intern('assign')58TOKEN_COLON = intern('colon')
209 unmodified lines
268 self.value269 )270271266class TokenStreamIterator(object):272class TokenStreamIterator(six.Iterator):273 """The iterator for tokenstreams. Iterate over the stream274 until the eof token is reached.275 """276
2 unmodified lines
279280 def __iter__(self):281 return self282277 def next(self):283 def __next__(self):284 token = self.stream.current285 if token.type is TOKEN_EOF:286 self.stream.close()287 raise StopIteration()282 next(self.stream)288 six.advance_iterator(self.stream)289 return token290291286class TokenStream(object):292class TokenStream(six.Iterator):293 """A token stream is an iterable that yields :class:`Token`\s. The294 parser however does not iterate over it but calls :meth:`next` to go295 one token ahead. The current active token is stored as :attr:`current`.296 """297298 def __init__(self, generator, name, filename):293 self._next = iter(generator).next299 self._iter = iter(generator)300 self._pushed = deque()301 self.name = name302 self.filename = filename303 self.closed = False304 self.current = Token(1, TOKEN_INITIAL, '')299 next(self)305 six.advance_iterator(self)306307 def __iter__(self):308 return TokenStreamIterator(self)309304 def __nonzero__(self):310 def __bool__(self):311 return bool(self._pushed) or self.current.type is not TOKEN_EOF312 __nonzero__ = __bool__ # py2313314 eos = property(lambda x: not x, doc="Are we at the end of the stream?")315316 def push(self, token):
1 unmodified line
318 self._pushed.append(token)319320 def look(self):321 """Look at the next token."""315 old_token = next(self)322 old_token = six.advance_iterator(self)323 result = self.current324 self.push(result)325 self.current = old_token326 return result327328 def skip(self, n=1):329 """Got n tokens ahead."""330 for x in range(n):324 next(self)331 six.advance_iterator(self)332333 def next_if(self, expr):334 """Perform the token test and return the token if it matched.335 Otherwise the return value is `None`.336 """337 if self.current.test(expr):331 return next(self)338 return six.advance_iterator(self)339340 def skip_if(self, expr):341 """Like :meth:`next_if` but only returns `True` or `False`."""342 return self.next_if(expr) is not None343337 def next(self):344 def __next__(self):345 """Go one token ahead and return the old one"""346 rv = self.current347 if self._pushed:348 self.current = self._pushed.popleft()349 elif self.current.type is not TOKEN_EOF:350 try:344 self.current = self._next()351 self.current = six.advance_iterator(self._iter)352 except StopIteration:353 self.close()354 return rv355356 def close(self):357 """Close the stream."""358 self.current = Token(self.current.lineno, TOKEN_EOF, '')352 self._next = None359 self._iter = None360 self.closed = True361362 def expect(self, expr):363 """Expect a given token type and return it. This accepts the same
12 unmodified lines
376 self.name, self.filename)377 try:378 return self.current379 finally:373 next(self)380 six.advance_iterator(self)381382383def get_lexer(environment):384 """Return a lexer which is probably cached."""
305 unmodified lines
modified:jinja2/loaders.py+3 added-3 removed
152 unmodified lines
153 by setting the `encoding` parameter to something else.154 """155156 def __init__(self, searchpath, encoding='utf-8'):157 if isinstance(searchpath, basestring):157 if isinstance(searchpath, six.string_types):158 searchpath = [searchpath]159 self.searchpath = list(searchpath)160 self.encoding = encoding161
144 unmodified lines
306 def get_source(self, environment, template):307 rv = self.load_func(template)308 if rv is None:309 raise TemplateNotFound(template)310 elif isinstance(rv, basestring):310 elif isinstance(rv, six.string_types):311 return rv, None, None312 return rv313314
116 unmodified lines
431432 # create a fake module that looks for the templates in the433 # path given.434 mod = _TemplateModule(package_name)435 if isinstance(path, basestring):435 if isinstance(path, six.string_types):436 path = [path]437 else:438 path = list(path)439 mod.__path__ = path
35 unmodified lines
modified:jinja2/meta.py+4 added-4 removed
9 unmodified lines
10 :license: BSD, see LICENSE for more details.11"""12from jinja2 import nodes13from jinja2.compiler import CodeGenerator14import six151516class TrackingCodeGenerator(CodeGenerator):17 """We abuse the code generator for introspection."""1819 def __init__(self, environment):
56 unmodified lines
76 for template_name in node.template.items:77 # something const, only yield the strings and ignore78 # non-string consts that really just make no sense79 if isinstance(template_name, nodes.Const):80 if isinstance(template_name.value, basestring):80 if isinstance(template_name.value, six.string_types):81 yield template_name.value82 # something dynamic in there83 else:84 yield None
1 unmodified line
86 else:87 yield None88 continue89 # constant is a basestring, direct template name90 if isinstance(node.template.value, basestring):90 if isinstance(node.template.value, six.string_types):91 yield node.template.value92 # a tuple or list (latter *should* not happen) made of consts,93 # yield the consts that are strings. We could warn here for94 # non string values95 elif isinstance(node, nodes.Include) and \96 isinstance(node.template.value, (tuple, list)):97 for template_name in node.template.value:98 if isinstance(template_name, basestring):98 if isinstance(template_name, six.string_types):99 yield template_name100 # something else we don't care about, we could warn here101 else:102 yield None
modified:jinja2/nodes.py+3 added-3 removed
11 unmodified lines
12 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD, see LICENSE for more details.14"""15import operator16from itertools import chain, izip16from collections import deque17from jinja2.utils import Markup, MethodType, FunctionType18import six19from six.moves import zip202122#: the types we support for context functions23_context_function_types = (FunctionType, MethodType)
78 unmodified lines
102 return EvalContext(node.environment)103 return ctx104105106class Node(object):106class Node(six.with_metaclass(NodeType, object)):107 """Baseclass for all Jinja2 nodes. There are a number of nodes available108 of different types. There are three major types:109110 - :class:`Stmt`: statements
25 unmodified lines
136 self.__class__.__name__,137 len(self.fields),138 len(self.fields) != 1 and 's' or ''139 ))140 for name, arg in izip(self.fields, fields):140 for name, arg in zip(self.fields, fields):141 setattr(self, name, arg)142 for attr in self.attributes:143 setattr(self, attr, attributes.pop(attr, None))144 if attributes:
767 unmodified lines
modified:jinja2/parser.py+49 added-50 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja2 import nodes12from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError13from jinja2.utils import next13from jinja2.lexer import describe_token, describe_token_expr15from six.moves import map16from six.moves import zip14import six15from six.moves import map, zip161718#: statements that callinto 19_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',
142 unmodified lines
162 if self.stream.current.type == 'eof':163 self.fail_eof(end_tokens)164165 if drop_needle:167 next(self.stream)166 six.advance_iterator(self.stream)167 return result168169 def parse_set(self):170 """Parse an assign statement."""172 lineno = next(self.stream).lineno171 lineno = six.advance_iterator(self.stream).lineno172 target = self.parse_assign_target()173 self.stream.expect('assign')174 expr = self.parse_tuple()175 return nodes.Assign(target, expr, lineno=lineno)
9 unmodified lines
185 if self.stream.skip_if('name:if'):186 test = self.parse_expression()187 recursive = self.stream.skip_if('name:recursive')188 body = self.parse_statements(('name:endfor', 'name:else'))190 if next(self.stream).value == 'endfor':189 if six.advance_iterator(self.stream).value == 'endfor':190 else_ = []191 else:192 else_ = self.parse_statements(('name:endfor',), drop_needle=True)193 return nodes.For(target, iter, body, else_, test,
5 unmodified lines
199 while 1:200 node.test = self.parse_tuple(with_condexpr=False)201 node.body = self.parse_statements(('name:elif', 'name:else',202 'name:endif'))204 token = next(self.stream)203 token = six.advance_iterator(self.stream)204 if token.test('name:elif'):205 new_node = nodes.If(lineno=self.stream.current.lineno)206 node.else_ = [new_node]207 node = new_node
6 unmodified lines
214 break215 return result216217 def parse_block(self):219 node = nodes.Block(lineno=next(self.stream).lineno)218 node = nodes.Block(lineno=six.advance_iterator(self.stream).lineno)219 node.name = self.stream.expect('name').value220 node.scoped = self.stream.skip_if('name:scoped')221222 # common problem people encounter when switching from django
8 unmodified lines
231 self.stream.skip_if('name:' + node.name)232 return node233234 def parse_extends(self):236 node = nodes.Extends(lineno=next(self.stream).lineno)235 node = nodes.Extends(lineno=six.advance_iterator(self.stream).lineno)236 node.template = self.parse_expression()237 return node238239 def parse_import_context(self, node, default):240 if self.stream.current.test_any('name:with', 'name:without') and \241 self.stream.look().test('name:context'):243 node.with_context = next(self.stream).value == 'with'242 node.with_context = six.advance_iterator(self.stream).value == 'with'243 self.stream.skip()244 else:245 node.with_context = default246 return node247248 def parse_include(self):250 node = nodes.Include(lineno=next(self.stream).lineno)249 node = nodes.Include(lineno=six.advance_iterator(self.stream).lineno)250 node.template = self.parse_expression()251 if self.stream.current.test('name:ignore') and \252 self.stream.look().test('name:missing'):253 node.ignore_missing = True
2 unmodified lines
256 node.ignore_missing = False257 return self.parse_import_context(node, True)258259 def parse_import(self):261 node = nodes.Import(lineno=next(self.stream).lineno)260 node = nodes.Import(lineno=six.advance_iterator(self.stream).lineno)261 node.template = self.parse_expression()262 self.stream.expect('name:as')263 node.target = self.parse_assign_target(name_only=True).name264 return self.parse_import_context(node, False)265266 def parse_from(self):268 node = nodes.FromImport(lineno=next(self.stream).lineno)267 node = nodes.FromImport(lineno=six.advance_iterator(self.stream).lineno)268 node.template = self.parse_expression()269 self.stream.expect('name:import')270 node.names = []271272 def parse_context():273 if self.stream.current.value in ('with', 'without') and \274 self.stream.look().test('name:context'):276 node.with_context = next(self.stream).value == 'with'275 node.with_context = six.advance_iterator(self.stream).value == 'with'276 self.stream.skip()277 return True278 return False279
36 unmodified lines
316 args.append(arg)317 self.stream.expect('rparen')318319 def parse_call_block(self):321 node = nodes.CallBlock(lineno=next(self.stream).lineno)320 node = nodes.CallBlock(lineno=six.advance_iterator(self.stream).lineno)321 if self.stream.current.type == 'lparen':322 self.parse_signature(node)323 else:324 node.args = []
5 unmodified lines
330 node.body = self.parse_statements(('name:endcall',), drop_needle=True)331 return node332333 def parse_filter_block(self):335 node = nodes.FilterBlock(lineno=next(self.stream).lineno)334 node = nodes.FilterBlock(lineno=six.advance_iterator(self.stream).lineno)335 node.filter = self.parse_filter(None, start_inline=True)336 node.body = self.parse_statements(('name:endfilter',),337 drop_needle=True)338 return node339340 def parse_macro(self):342 node = nodes.Macro(lineno=next(self.stream).lineno)341 node = nodes.Macro(lineno=six.advance_iterator(self.stream).lineno)342 node.name = self.parse_assign_target(name_only=True).name343 self.parse_signature(node)344 node.body = self.parse_statements(('name:endmacro',),345 drop_needle=True)346 return node347348 def parse_print(self):350 node = nodes.Output(lineno=next(self.stream).lineno)349 node = nodes.Output(lineno=six.advance_iterator(self.stream).lineno)350 node.nodes = []351 while self.stream.current.type != 'block_end':352 if node.nodes:353 self.stream.expect('comma')
65 unmodified lines
419 return left420421 def parse_not(self):422 if self.stream.current.test('name:not'):424 lineno = next(self.stream).lineno423 lineno = six.advance_iterator(self.stream).lineno424 return nodes.Not(self.parse_not(), lineno=lineno)425 return self.parse_compare()426427 def parse_compare(self):
2 unmodified lines
430 ops = []431 while 1:432 token_type = self.stream.current.type433 if token_type in _compare_operators:435 next(self.stream)434 six.advance_iterator(self.stream)435 ops.append(nodes.Operand(token_type, self.parse_add()))436 elif self.stream.skip_if('name:in'):437 ops.append(nodes.Operand('in', self.parse_add()))438 elif self.stream.current.test('name:not') and \
10 unmodified lines
449 def parse_add(self):450 lineno = self.stream.current.lineno451 left = self.parse_sub()452 while self.stream.current.type == 'add':454 next(self.stream)453 six.advance_iterator(self.stream)454 right = self.parse_sub()455 left = nodes.Add(left, right, lineno=lineno)456 lineno = self.stream.current.lineno457 return left
1 unmodified line
459 def parse_sub(self):460 lineno = self.stream.current.lineno461 left = self.parse_concat()462 while self.stream.current.type == 'sub':464 next(self.stream)463 six.advance_iterator(self.stream)464 right = self.parse_concat()465 left = nodes.Sub(left, right, lineno=lineno)466 lineno = self.stream.current.lineno467 return left
1 unmodified line
469 def parse_concat(self):470 lineno = self.stream.current.lineno471 args = [self.parse_mul()]472 while self.stream.current.type == 'tilde':474 next(self.stream)473 six.advance_iterator(self.stream)474 args.append(self.parse_mul())475 if len(args) == 1:476 return args[0]477 return nodes.Concat(args, lineno=lineno)
1 unmodified line
479 def parse_mul(self):480 lineno = self.stream.current.lineno481 left = self.parse_div()482 while self.stream.current.type == 'mul':484 next(self.stream)483 six.advance_iterator(self.stream)484 right = self.parse_div()485 left = nodes.Mul(left, right, lineno=lineno)486 lineno = self.stream.current.lineno487 return left
1 unmodified line
489 def parse_div(self):490 lineno = self.stream.current.lineno491 left = self.parse_floordiv()492 while self.stream.current.type == 'div':494 next(self.stream)493 six.advance_iterator(self.stream)494 right = self.parse_floordiv()495 left = nodes.Div(left, right, lineno=lineno)496 lineno = self.stream.current.lineno497 return left
1 unmodified line
499 def parse_floordiv(self):500 lineno = self.stream.current.lineno501 left = self.parse_mod()502 while self.stream.current.type == 'floordiv':504 next(self.stream)503 six.advance_iterator(self.stream)504 right = self.parse_mod()505 left = nodes.FloorDiv(left, right, lineno=lineno)506 lineno = self.stream.current.lineno507 return left
1 unmodified line
509 def parse_mod(self):510 lineno = self.stream.current.lineno511 left = self.parse_pow()512 while self.stream.current.type == 'mod':514 next(self.stream)513 six.advance_iterator(self.stream)514 right = self.parse_pow()515 left = nodes.Mod(left, right, lineno=lineno)516 lineno = self.stream.current.lineno517 return left
1 unmodified line
519 def parse_pow(self):520 lineno = self.stream.current.lineno521 left = self.parse_unary()522 while self.stream.current.type == 'pow':524 next(self.stream)523 six.advance_iterator(self.stream)524 right = self.parse_unary()525 left = nodes.Pow(left, right, lineno=lineno)526 lineno = self.stream.current.lineno527 return left
1 unmodified line
529 def parse_unary(self, with_filter=True):530 token_type = self.stream.current.type531 lineno = self.stream.current.lineno532 if token_type == 'sub':534 next(self.stream)533 six.advance_iterator(self.stream)534 node = nodes.Neg(self.parse_unary(False), lineno=lineno)535 elif token_type == 'add':537 next(self.stream)536 six.advance_iterator(self.stream)537 node = nodes.Pos(self.parse_unary(False), lineno=lineno)538 else:539 node = self.parse_primary()540 node = self.parse_postfix(node)
10 unmodified lines
551 elif token.value in ('none', 'None'):552 node = nodes.Const(None, lineno=token.lineno)553 else:554 node = nodes.Name(token.value, 'load', lineno=token.lineno)556 next(self.stream)555 six.advance_iterator(self.stream)556 elif token.type == 'string':558 next(self.stream)557 six.advance_iterator(self.stream)558 buf = [token.value]559 lineno = token.lineno560 while self.stream.current.type == 'string':561 buf.append(self.stream.current.value)563 next(self.stream)562 six.advance_iterator(self.stream)563 node = nodes.Const(''.join(buf), lineno=lineno)564 elif token.type in ('integer', 'float'):566 next(self.stream)565 six.advance_iterator(self.stream)566 node = nodes.Const(token.value, lineno=token.lineno)567 elif token.type == 'lparen':569 next(self.stream)568 six.advance_iterator(self.stream)569 node = self.parse_tuple(explicit_parentheses=True)570 self.stream.expect('rparen')571 elif token.type == 'lbracket':572 node = self.parse_list()
113 unmodified lines
686 break687 return node688689 def parse_subscript(self, node):691 token = next(self.stream)690 token = six.advance_iterator(self.stream)691 if token.type == 'dot':692 attr_token = self.stream.current694 next(self.stream)693 six.advance_iterator(self.stream)694 if attr_token.type == 'name':695 return nodes.Getattr(node, attr_token.value, 'load',696 lineno=token.lineno)697 elif attr_token.type != 'integer':
17 unmodified lines
715 def parse_subscribed(self):716 lineno = self.stream.current.lineno717718 if self.stream.current.type == 'colon':720 next(self.stream)719 six.advance_iterator(self.stream)720 args = [None]721 else:722 node = self.parse_expression()723 if self.stream.current.type != 'colon':724 return node726 next(self.stream)725 six.advance_iterator(self.stream)726 args = [node]727728 if self.stream.current.type == 'colon':729 args.append(None)
2 unmodified lines
732 else:733 args.append(None)734735 if self.stream.current.type == 'colon':737 next(self.stream)736 six.advance_iterator(self.stream)737 if self.stream.current.type not in ('rbracket', 'comma'):738 args.append(self.parse_expression())739 else:740 args.append(None)
21 unmodified lines
762 if self.stream.current.type == 'rparen':763 break764 if self.stream.current.type == 'mul':765 ensure(dyn_args is None and dyn_kwargs is None)767 next(self.stream)766 six.advance_iterator(self.stream)767 dyn_args = self.parse_expression()768 elif self.stream.current.type == 'pow':769 ensure(dyn_kwargs is None)771 next(self.stream)770 six.advance_iterator(self.stream)771 dyn_kwargs = self.parse_expression()772 else:773 ensure(dyn_args is None and dyn_kwargs is None)774 if self.stream.current.type == 'name' and \
17 unmodified lines
792793 def parse_filter(self, node, start_inline=False):794 while self.stream.current.type == 'pipe' or start_inline:795 if not start_inline:797 next(self.stream)796 six.advance_iterator(self.stream)797 token = self.stream.expect('name')798 name = token.value799 while self.stream.current.type == 'dot':801 next(self.stream)800 six.advance_iterator(self.stream)801 name += '.' + self.stream.expect('name').value802 if self.stream.current.type == 'lparen':803 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)804 else:
5 unmodified lines
810 start_inline = False811 return node812813 def parse_test(self, node):815 token = next(self.stream)814 token = six.advance_iterator(self.stream)815 if self.stream.current.test('name:not'):817 next(self.stream)816 six.advance_iterator(self.stream)817 negated = True818 else:819 negated = False820 name = self.stream.expect('name').value821 while self.stream.current.type == 'dot':823 next(self.stream)822 six.advance_iterator(self.stream)823 name += '.' + self.stream.expect('name').value824 dyn_args = dyn_kwargs = None825 kwargs = []826 if self.stream.current.type == 'lparen':
34 unmodified lines
861 if token.type == 'data':862 if token.value:863 add_data(nodes.TemplateData(token.value,864 lineno=token.lineno))866 next(self.stream)865 six.advance_iterator(self.stream)866 elif token.type == 'variable_begin':868 next(self.stream)867 six.advance_iterator(self.stream)868 add_data(self.parse_tuple(with_condexpr=True))869 self.stream.expect('variable_end')870 elif token.type == 'block_begin':871 flush_data()873 next(self.stream)872 six.advance_iterator(self.stream)873 if end_tokens is not None and \874 self.stream.current.test_any(*end_tokens):875 return body876 rv = self.parse_statement()
20 unmodified lines
modified:jinja2/runtime.py+19 added-14 removed
6 unmodified lines
78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD.10"""11from itertools import chain, imap11from itertools import chain12from jinja2.nodes import EvalContext, _context_function_types13from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \14 concat, internalcode, next, object_type_repr14 concat, internalcode, object_type_repr15from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17import six18from six.moves import map192021# these variables are exported to the template runtime22__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
3 unmodified lines
2627#: the name of the function that is used to convert something into28#: a string. 2to3 will adopt that automatically and the generated29#: code can take advantage of it.30try:29to_string = unicode31 to_string = unicode32except NameError:33 to_string = str3435#: the identity function. Useful for certain things in the environment36identity = lambda x: x37
2 unmodified lines
4041def markup_join(seq):42 """Concatenation that escapes if necessary and converts to unicode."""43 buf = []40 iterator = imap(soft_unicode, seq)44 iterator = map(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."""50 return concat(imap(unicode, seq))54 return concat(map(six.text_type, seq))555657def new_context(environment, template_name, blocks, vars=None,58 shared=None, globals=None, locals=None):
249 unmodified lines
308 return LoopContextIterator(self)309310 def _safe_next(self):311 try:308 return next(self._iterator)312 return six.advance_iterator(self._iterator)313 except StopIteration:314 return _last_iteration315316 @internalcode
27 unmodified lines
344 self.length345 )346347344class LoopContextIterator(object):348class LoopContextIterator(six.Iterator):349 """The iterator for a loop context."""350 __slots__ = ('context',)351352 def __init__(self, context):
1 unmodified line
354355 def __iter__(self):356 return self357354 def next(self):358 def __next__(self):359 ctx = self.context360 ctx.index0 += 1361 if ctx._after is _last_iteration:362 raise StopIteration()
96 unmodified lines
459 """460 if self._undefined_hint is None:461 if self._undefined_obj is missing:462 hint = '%r is undefined' % self._undefined_name459 elif not isinstance(self._undefined_name, basestring):463 elif not isinstance(self._undefined_name, six.string_types):464 hint = '%s has no element %r' % (465 object_type_repr(self._undefined_obj),466 self._undefined_name467 )
19 unmodified lines
487 __float__ = __complex__ = __pow__ = __rpow__ = \488 _fail_with_undefined_error489490 def __str__(self):491 s = self.__unicode__()487 return six.text_type(self).encode('utf-8')492 return s if six.PY3 else s.encode('utf-8')493489 # unicode goes after __str__ because we configured 2to3 to rename490 # __unicode__ to __str__. because the 2to3 tree is not designed to491 # remove nodes from it, we leave the above __str__ around and let492 # it override at runtime.494 def __unicode__(self):495 return u''496497 def __len__(self):
24 unmodified lines
522 UndefinedError: 'foo' is undefined523 """524 __slots__ = ()525526 def __str__(self):527 s = self.__unicode__()528 return s if six.PY3 else s.encode('utf-8')529530 def __unicode__(self):531 if self._undefined_hint is None:532 if self._undefined_obj is missing:533 return u'{{ %s }}' % self._undefined_name
34 unmodified lines
modified:jinja2/sandbox.py+2 added-1 removed
11 unmodified lines
12 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD.14"""15import operator16import six17from jinja2.environment import Environment18from jinja2.exceptions import SecurityError19from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \20 FrameType, GeneratorType
278 unmodified lines
299 """Subscribe an object from sandboxed code."""300 try:301 return obj[argument]302 except (TypeError, LookupError):302 if isinstance(argument, basestring):303 if isinstance(argument, six.string_types):304 try:305 attr = str(argument)306 except Exception:307 pass
55 unmodified lines
modified:jinja2/tests.py+2 added-2 removed
85 unmodified lines
868788def test_string(value):89 """Return true if the object is a string."""90 return isinstance(value, basestring)90 return isinstance(value, six.string_types)919293def test_mapping(value):94 """Return true if the object is a mapping (dict etc.).
4 unmodified lines
99100101def test_number(value):102 """Return true if the variable is a number."""103 return isinstance(value, (int, long, float, complex))103 return isinstance(value, (int, float, complex))104105106def test_sequence(value):107 """Return true if the variable is a sequence. Sequences are variables
55 unmodified lines
modified:jinja2/utils.py+12 added-19 removed
10 unmodified lines
11import re12import sys13import errno14import six15from six.moves import map16try:17 from urllib.parse import quote_from_bytes as url_quote18except ImportError:19 from urllib import quote as url_quote20try:21 from thread import allocate_lock22except ImportError:23 try:24 from _thread import allocate_lock # py 325 except ImportError:22 from dummy_thread import allocate_lock26 from dummy_thread import allocate_lock27from collections import deque24from itertools import imap282629_word_split_re = re.compile(r'(\s+)')30_punctuation_re = re.compile(31 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (30 '|'.join(imap(re.escape, ('(', '<', '&lt;'))),31 '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '&gt;')))32 '|'.join(map(re.escape, ('(', '<', '&lt;'))),33 '|'.join(map(re.escape, ('.', ',', ')', '>', '\n', '&gt;')))34 )35)36_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')37_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
25 unmodified lines
63 except Exception:64 # this hack is needed so that the current frame65 # does not show up in the traceback.66 exc_type, exc_value, tb = sys.exc_info()65 raise exc_type, exc_value, tb.tb_next67 six.reraise(exc_type, exc_value, tb.tb_next)68 else:69 concat = _concat70 del _test_gen_bug, _error717271# for python 2.x we create ourselves a next() function that does the72# basics without exception catching.73try:74 next = next75except NameError:76 def next(x):77 return six.advance_iterator(x)787973# if this python version is unable to deal with unicode filenames74# when passed to encode we let this function encode it properly.75# This is used in a couple of places. As far as Jinja is concerned76# filenames are unicode *or* bytestrings in 2.x and unicode only in
278 unmodified lines
355356 If non strings are provided they are converted to their unicode357 representation first.358 """366 if not isinstance(obj, basestring):359 if not isinstance(obj, six.string_types):360 obj = six.text_type(obj)368 if isinstance(obj, unicode):361 if isinstance(obj, six.text_type):362 obj = obj.encode(charset)363 return six.text_type(url_quote(obj))364365
189 unmodified lines
555except ImportError:556 pass557558566class Cycler(object):559class Cycler(six.Iterator):560 """A cycle helper for templates."""561562 def __init__(self, *items):563 if not items:
9 unmodified lines
573 def current(self):574 """Returns the current item."""575 return self.items[self.pos]576584 def next(self):577 def __next__(self):578 """Goes one item ahead and returns it."""579 rv = self.current580 self.pos = (self.pos + 1) % len(self.items)581 return rv
38 unmodified lines
modified:setup.py+1 added-10 removed
46 unmodified lines
47 ],48)495051# tell distribute to use 2to3 with our own fixers.52extra = {}53if sys.version_info >= (3, 0):54 extra.update(55 use_2to3=True,56 use_2to3_fixers=['custom_fixers']57 )5851# ignore the old '--with-speedups' flag52try:53 speedups_pos = sys.argv.index('--with-speedups')54except ValueError:
41 unmodified lines
96 entry_points="""97 [babel.extractors]98 jinja2 = jinja2.ext:babel_extract[i18n]99 """,108 features={'debugsupport': debugsupport},109 **extra100 features={'debugsupport': debugsupport}101)