Skip to content
Myr

Removed bundled markupsafe

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 4a41dd6 · Browse files · 7 files+4 added−676 removed
This commit

State

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

Diff stats

7 files+4 added−676 removed

  • other:+4 added−676 removed

7 files+4 added−676 removed

deleted:jinja2/_markupsafe/__init__.py-218 removed
1# -*- coding: utf-8 -*-2"""3 markupsafe4 ~~~~~~~~~~56 Implements a Markup string.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12import six13from six.moves import map14from jinja2._compat import unichr1516__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']171819_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')20_entity_re = re.compile(r'&([^;]+);')212223class Markup(six.text_type):24 r"""Marks a string as being safe for inclusion in HTML/XML output without25 needing to be escaped. This implements the `__html__` interface a couple26 of frameworks and web applications use. :class:`Markup` is a direct27 subclass of `unicode` and provides all the methods of `unicode` just that28 it escapes arguments passed and always returns `Markup`.2930 The `escape` function returns markup objects so that double escaping can't31 happen.3233 The constructor of the :class:`Markup` class can be used for three34 different things: When passed an unicode object it's assumed to be safe,35 when passed an object with an HTML representation (has an `__html__`36 method) that representation is used, otherwise the object passed is37 converted into a unicode string and then assumed to be safe:3839 >>> Markup("Hello <em>World</em>!")40 Markup(u'Hello <em>World</em>!')41 >>> class Foo(object):42 ... def __html__(self):43 ... return '<a href="#">foo</a>'44 ... 45 >>> Markup(Foo())46 Markup(u'<a href="#">foo</a>')4748 If you want object passed being always treated as unsafe you can use the49 :meth:`escape` classmethod to create a :class:`Markup` object:5051 >>> Markup.escape("Hello <em>World</em>!")52 Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')5354 Operations on a markup string are markup aware which means that all55 arguments are passed through the :func:`escape` function:5657 >>> em = Markup("<em>%s</em>")58 >>> em % "foo & bar"59 Markup(u'<em>foo &amp; bar</em>')60 >>> strong = Markup("<strong>%(text)s</strong>")61 >>> strong % {'text': '<blink>hacker here</blink>'}62 Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')63 >>> Markup("<em>Hello</em> ") + "<foo>"64 Markup(u'<em>Hello</em> &lt;foo&gt;')65 """66 __slots__ = ()6768 def __new__(cls, base=u'', encoding=None, errors='strict'):69 if hasattr(base, '__html__'):70 base = base.__html__()71 if encoding is None:72 return six.text_type.__new__(cls, base)73 return six.text_type.__new__(cls, base, encoding, errors)7475 def __html__(self):76 return self7778 def __add__(self, other):79 if hasattr(other, '__html__') or isinstance(other, six.string_types):80 return self.__class__(six.text_type(self) + six.text_type(escape(other)))81 return NotImplemented8283 def __radd__(self, other):84 if hasattr(other, '__html__') or isinstance(other, six.string_types):85 return self.__class__(six.text_type(escape(other)) + six.text_type(self))86 return NotImplemented8788 def __mul__(self, num):89 if isinstance(num, (int, long)):90 return self.__class__(six.text_type.__mul__(self, num))91 return NotImplemented92 __rmul__ = __mul__9394 def __mod__(self, arg):95 if isinstance(arg, tuple):96 arg = tuple(map(_MarkupEscapeHelper, arg))97 else:98 arg = _MarkupEscapeHelper(arg)99 return self.__class__(six.text_type.__mod__(self, arg))100101 def __repr__(self):102 return '%s(%s)' % (103 self.__class__.__name__,104 six.text_type.__repr__(self)105 )106107 def join(self, seq):108 return self.__class__(six.text_type.join(self, map(escape, seq)))109 join.__doc__ = six.text_type.join.__doc__110111 def split(self, *args, **kwargs):112 return map(self.__class__, six.text_type.split(self, *args, **kwargs))113 split.__doc__ = six.text_type.split.__doc__114115 def rsplit(self, *args, **kwargs):116 return map(self.__class__, six.text_type.rsplit(self, *args, **kwargs))117 rsplit.__doc__ = six.text_type.rsplit.__doc__118119 def splitlines(self, *args, **kwargs):120 return map(self.__class__, six.text_type.splitlines(self, *args, **kwargs))121 splitlines.__doc__ = six.text_type.splitlines.__doc__122123 def unescape(self):124 r"""Unescape markup again into an unicode string. This also resolves125 known HTML4 and XHTML entities:126127 >>> Markup("Main &raquo; <em>About</em>").unescape()128 u'Main \xbb <em>About</em>'129 """130 from jinja2._markupsafe._constants import HTML_ENTITIES131 def handle_match(m):132 name = m.group(1)133 if name in HTML_ENTITIES:134 return unichr(HTML_ENTITIES[name])135 try:136 if name[:2] in ('#x', '#X'):137 return unichr(int(name[2:], 16))138 elif name.startswith('#'):139 return unichr(int(name[1:]))140 except ValueError:141 pass142 return u''143 return _entity_re.sub(handle_match, six.text_type(self))144145 def striptags(self):146 r"""Unescape markup into an unicode string and strip all tags. This147 also resolves known HTML4 and XHTML entities. Whitespace is148 normalized to one:149150 >>> Markup("Main &raquo; <em>About</em>").striptags()151 u'Main \xbb About'152 """153 stripped = u' '.join(_striptags_re.sub('', self).split())154 return Markup(stripped).unescape()155156 @classmethod157 def escape(cls, s):158 """Escape the string. Works like :func:`escape` with the difference159 that for subclasses of :class:`Markup` this function would return the160 correct subclass.161 """162 rv = escape(s)163 if rv.__class__ is not cls:164 return cls(rv)165 return rv166167 def make_wrapper(name):168 orig = getattr(six.text_type, name)169 def func(self, *args, **kwargs):170 args = _escape_argspec(list(args), enumerate(args))171 _escape_argspec(kwargs, six.iteritems(kwargs))172 return self.__class__(orig(self, *args, **kwargs))173 func.__name__ = orig.__name__174 func.__doc__ = orig.__doc__175 return func176177 for method in '__getitem__', 'capitalize', \178 'title', 'lower', 'upper', 'replace', 'ljust', \179 'format', 'partition', 'rpartition', \180 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \181 'translate', 'expandtabs', 'swapcase', 'zfill':182 locals()[method] = make_wrapper(method)183184 # not in python 3185 if hasattr(six.text_type, '__getslice__'):186 __getslice__ = make_wrapper('__getslice__')187188 del method, make_wrapper189190191def _escape_argspec(obj, iterable):192 """Helper for various string-wrapped functions."""193 for key, value in iterable:194 if hasattr(value, '__html__') or isinstance(value, six.string_types):195 obj[key] = escape(value)196 return obj197198199class _MarkupEscapeHelper(object):200 """Helper for Markup.__mod__"""201202 def __init__(self, obj):203 self.obj = obj204205 __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])206 __str__ = lambda s: str(escape(s.obj))207 __unicode__ = lambda s: six.text_type(escape(s.obj))208 __repr__ = lambda s: str(escape(repr(s.obj)))209 __int__ = lambda s: int(s.obj)210 __float__ = lambda s: float(s.obj)211212213# we have to import it down here as the speedups and native214# modules imports the markup type which is define above.215try:216 from jinja2._markupsafe._speedups import escape, escape_silent, soft_unicode217except ImportError:218 from jinja2._markupsafe._native import escape, escape_silent, soft_unicode
deleted:jinja2/_markupsafe/_bundle.py-50 removed
1# -*- coding: utf-8 -*-2"""3 jinja2._markupsafe._bundle4 ~~~~~~~~~~~~~~~~~~~~~~~~~~56 This script pulls in markupsafe from a source folder and7 bundles it with Jinja2. It does not pull in the speedups8 module though.910 :copyright: Copyright 2010 by the Jinja team, see AUTHORS.11 :license: BSD, see LICENSE for details.12"""13from __future__ import print_function14import sys15import os16import re171819def rewrite_imports(lines):20 for idx, line in enumerate(lines):21 new_line = re.sub(r'(import|from)\s+markupsafe\b',22 r'\1 jinja2._markupsafe', line)23 if new_line != line:24 lines[idx] = new_line252627def main():28 if len(sys.argv) != 2:29 print('error: only argument is path to markupsafe')30 sys.exit(1)31 basedir = os.path.dirname(__file__)32 markupdir = sys.argv[1]33 for filename in os.listdir(markupdir):34 if filename.endswith('.py'):35 f = open(os.path.join(markupdir, filename))36 try:37 lines = list(f)38 finally:39 f.close()40 rewrite_imports(lines)41 f = open(os.path.join(basedir, filename), 'w')42 try:43 for line in lines:44 f.write(line)45 finally:46 f.close()474849if __name__ == '__main__':50 main()
deleted:jinja2/_markupsafe/_constants.py-267 removed
1# -*- coding: utf-8 -*-2"""3 markupsafe._constants4 ~~~~~~~~~~~~~~~~~~~~~56 Highlevel implementation of the Markup string.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213HTML_ENTITIES = {14 'AElig': 198,15 'Aacute': 193,16 'Acirc': 194,17 'Agrave': 192,18 'Alpha': 913,19 'Aring': 197,20 'Atilde': 195,21 'Auml': 196,22 'Beta': 914,23 'Ccedil': 199,24 'Chi': 935,25 'Dagger': 8225,26 'Delta': 916,27 'ETH': 208,28 'Eacute': 201,29 'Ecirc': 202,30 'Egrave': 200,31 'Epsilon': 917,32 'Eta': 919,33 'Euml': 203,34 'Gamma': 915,35 'Iacute': 205,36 'Icirc': 206,37 'Igrave': 204,38 'Iota': 921,39 'Iuml': 207,40 'Kappa': 922,41 'Lambda': 923,42 'Mu': 924,43 'Ntilde': 209,44 'Nu': 925,45 'OElig': 338,46 'Oacute': 211,47 'Ocirc': 212,48 'Ograve': 210,49 'Omega': 937,50 'Omicron': 927,51 'Oslash': 216,52 'Otilde': 213,53 'Ouml': 214,54 'Phi': 934,55 'Pi': 928,56 'Prime': 8243,57 'Psi': 936,58 'Rho': 929,59 'Scaron': 352,60 'Sigma': 931,61 'THORN': 222,62 'Tau': 932,63 'Theta': 920,64 'Uacute': 218,65 'Ucirc': 219,66 'Ugrave': 217,67 'Upsilon': 933,68 'Uuml': 220,69 'Xi': 926,70 'Yacute': 221,71 'Yuml': 376,72 'Zeta': 918,73 'aacute': 225,74 'acirc': 226,75 'acute': 180,76 'aelig': 230,77 'agrave': 224,78 'alefsym': 8501,79 'alpha': 945,80 'amp': 38,81 'and': 8743,82 'ang': 8736,83 'apos': 39,84 'aring': 229,85 'asymp': 8776,86 'atilde': 227,87 'auml': 228,88 'bdquo': 8222,89 'beta': 946,90 'brvbar': 166,91 'bull': 8226,92 'cap': 8745,93 'ccedil': 231,94 'cedil': 184,95 'cent': 162,96 'chi': 967,97 'circ': 710,98 'clubs': 9827,99 'cong': 8773,100 'copy': 169,101 'crarr': 8629,102 'cup': 8746,103 'curren': 164,104 'dArr': 8659,105 'dagger': 8224,106 'darr': 8595,107 'deg': 176,108 'delta': 948,109 'diams': 9830,110 'divide': 247,111 'eacute': 233,112 'ecirc': 234,113 'egrave': 232,114 'empty': 8709,115 'emsp': 8195,116 'ensp': 8194,117 'epsilon': 949,118 'equiv': 8801,119 'eta': 951,120 'eth': 240,121 'euml': 235,122 'euro': 8364,123 'exist': 8707,124 'fnof': 402,125 'forall': 8704,126 'frac12': 189,127 'frac14': 188,128 'frac34': 190,129 'frasl': 8260,130 'gamma': 947,131 'ge': 8805,132 'gt': 62,133 'hArr': 8660,134 'harr': 8596,135 'hearts': 9829,136 'hellip': 8230,137 'iacute': 237,138 'icirc': 238,139 'iexcl': 161,140 'igrave': 236,141 'image': 8465,142 'infin': 8734,143 'int': 8747,144 'iota': 953,145 'iquest': 191,146 'isin': 8712,147 'iuml': 239,148 'kappa': 954,149 'lArr': 8656,150 'lambda': 955,151 'lang': 9001,152 'laquo': 171,153 'larr': 8592,154 'lceil': 8968,155 'ldquo': 8220,156 'le': 8804,157 'lfloor': 8970,158 'lowast': 8727,159 'loz': 9674,160 'lrm': 8206,161 'lsaquo': 8249,162 'lsquo': 8216,163 'lt': 60,164 'macr': 175,165 'mdash': 8212,166 'micro': 181,167 'middot': 183,168 'minus': 8722,169 'mu': 956,170 'nabla': 8711,171 'nbsp': 160,172 'ndash': 8211,173 'ne': 8800,174 'ni': 8715,175 'not': 172,176 'notin': 8713,177 'nsub': 8836,178 'ntilde': 241,179 'nu': 957,180 'oacute': 243,181 'ocirc': 244,182 'oelig': 339,183 'ograve': 242,184 'oline': 8254,185 'omega': 969,186 'omicron': 959,187 'oplus': 8853,188 'or': 8744,189 'ordf': 170,190 'ordm': 186,191 'oslash': 248,192 'otilde': 245,193 'otimes': 8855,194 'ouml': 246,195 'para': 182,196 'part': 8706,197 'permil': 8240,198 'perp': 8869,199 'phi': 966,200 'pi': 960,201 'piv': 982,202 'plusmn': 177,203 'pound': 163,204 'prime': 8242,205 'prod': 8719,206 'prop': 8733,207 'psi': 968,208 'quot': 34,209 'rArr': 8658,210 'radic': 8730,211 'rang': 9002,212 'raquo': 187,213 'rarr': 8594,214 'rceil': 8969,215 'rdquo': 8221,216 'real': 8476,217 'reg': 174,218 'rfloor': 8971,219 'rho': 961,220 'rlm': 8207,221 'rsaquo': 8250,222 'rsquo': 8217,223 'sbquo': 8218,224 'scaron': 353,225 'sdot': 8901,226 'sect': 167,227 'shy': 173,228 'sigma': 963,229 'sigmaf': 962,230 'sim': 8764,231 'spades': 9824,232 'sub': 8834,233 'sube': 8838,234 'sum': 8721,235 'sup': 8835,236 'sup1': 185,237 'sup2': 178,238 'sup3': 179,239 'supe': 8839,240 'szlig': 223,241 'tau': 964,242 'there4': 8756,243 'theta': 952,244 'thetasym': 977,245 'thinsp': 8201,246 'thorn': 254,247 'tilde': 732,248 'times': 215,249 'trade': 8482,250 'uArr': 8657,251 'uacute': 250,252 'uarr': 8593,253 'ucirc': 251,254 'ugrave': 249,255 'uml': 168,256 'upsih': 978,257 'upsilon': 965,258 'uuml': 252,259 'weierp': 8472,260 'xi': 958,261 'yacute': 253,262 'yen': 165,263 'yuml': 255,264 'zeta': 950,265 'zwj': 8205,266 'zwnj': 8204267}
deleted:jinja2/_markupsafe/_native.py-46 removed
1# -*- coding: utf-8 -*-2"""3 markupsafe._native4 ~~~~~~~~~~~~~~~~~~56 Native Python implementation the C module is not compiled.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja2._markupsafe import Markup12import six131415def escape(s):16 """Convert the characters &, <, >, ' and " in string s to HTML-safe17 sequences. Use this if you need to display text that might contain18 such characters in HTML. Marks return value as markup string.19 """20 if hasattr(s, '__html__'):21 return s.__html__()22 return Markup(six.text_type(s)23 .replace('&', '&amp;')24 .replace('>', '&gt;')25 .replace('<', '&lt;')26 .replace("'", '&#39;')27 .replace('"', '&#34;')28 )293031def escape_silent(s):32 """Like :func:`escape` but converts `None` into an empty33 markup string.34 """35 if s is None:36 return Markup()37 return escape(s)383940def 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, six.text_type):45 s = six.text_type(s)46 return s
deleted:jinja2/_markupsafe/tests.py-81 removed
1import gc2import unittest3from jinja2._markupsafe import Markup, escape, escape_silent4import six567class MarkupTestCase(unittest.TestCase):89 def test_markup_operations(self):10 # adding two strings should escape the unsafe one11 unsafe = '<script type="application/x-some-script">alert("foo");</script>'12 safe = Markup('<em>username</em>')13 assert unsafe + safe == six.text_type(escape(unsafe)) + six.text_type(safe)1415 # string interpolations are safe to use too16 assert Markup('<em>%s</em>') % '<bad user>' == \17 '<em>&lt;bad user&gt;</em>'18 assert Markup('<em>%(username)s</em>') % {19 'username': '<bad user>'20 } == '<em>&lt;bad user&gt;</em>'2122 # an escaped object is markup too23 assert type(Markup('foo') + 'bar') is Markup2425 # and it implements __html__ by returning itself26 x = Markup("foo")27 assert x.__html__() is x2829 # it also knows how to treat __html__ objects30 class Foo(object):31 def __html__(self):32 return '<em>awesome</em>'33 def __unicode__(self):34 return 'awesome'35 assert Markup(Foo()) == '<em>awesome</em>'36 assert Markup('<strong>%s</strong>') % Foo() == \37 '<strong><em>awesome</em></strong>'3839 # escaping and unescaping40 assert escape('"<>&\'') == '&#34;&lt;&gt;&amp;&#39;'41 assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"42 assert Markup("&lt;test&gt;").unescape() == "<test>"4344 def test_all_set(self):45 import jinja2._markupsafe as markup46 for item in markup.__all__:47 getattr(markup, item)4849 def test_escape_silent(self):50 assert escape_silent(None) == Markup()51 assert escape(None) == Markup(None)52 assert escape_silent('<foo>') == Markup(u'&lt;foo&gt;')535455class MarkupLeakTestCase(unittest.TestCase):5657 def test_markup_leaks(self):58 counts = set()59 for count in range(20):60 for item in range(1000):61 escape("foo")62 escape("<foo>")63 escape(u"foo")64 escape(u"<foo>")65 counts.add(len(gc.get_objects()))66 assert len(counts) == 1, 'ouch, c extension seems to leak objects'676869def suite():70 suite = unittest.TestSuite()71 suite.addTest(unittest.makeSuite(MarkupTestCase))7273 # this test only tests the c extension74 if not hasattr(escape, 'func_code'):75 suite.addTest(unittest.makeSuite(MarkupLeakTestCase))7677 return suite787980if __name__ == '__main__':81 unittest.main(defaultTest='suite')
modified:jinja2/utils.py+2 added-11 removed
563 unmodified lines
564 return u''565 return self.sep566567568# try markupsafe first, if that fails go with Jinja2's bundled version569# of markupsafe. Markupsafe was previously Jinja2's implementation of570# the Markup object but was moved into a separate package in a patchlevel571# release572try:573 from markupsafe import Markup, escape, soft_unicode574except ImportError:575 from jinja2._markupsafe import Markup, escape, soft_unicode576577578from functools import partial568# Imported here because that's where it was in the past569from markupsafe import Markup, escape, soft_unicode
modified:setup.py+2 added-3 removed
77 unmodified lines
78 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',79 'Topic :: Software Development :: Libraries :: Python Modules',80 'Topic :: Text Processing :: Markup :: HTML'81 ],82 packages=['jinja2', 'jinja2.testsuite', 'jinja2.testsuite.res',83 'jinja2._markupsafe'],84 install_requires=['six>=1.3.0'],82 packages=['jinja2', 'jinja2.testsuite', 'jinja2.testsuite.res'],83 install_requires=['six>=1.3.0', 'markupsafe'],84 extras_require={'i18n': ['Babel>=0.8']},85 test_suite='jinja2.testsuite.suite',86 include_package_data=True,87 entry_points="""
4 unmodified lines