diff options
author | artkolesnikov <artkolesnikov@yandex-team.ru> | 2022-02-10 16:47:36 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:47:36 +0300 |
commit | 8611780b719073fe6c7e6536c71d61e20d57a5d6 (patch) | |
tree | 1284229a15a8eeeb4e9c81a6473f4e31d625cb52 /contrib/python/MarkupSafe/py3 | |
parent | cfadda92ca195da3ad68d721a58872a4f1ced696 (diff) | |
download | ydb-8611780b719073fe6c7e6536c71d61e20d57a5d6.tar.gz |
Restoring authorship annotation for <artkolesnikov@yandex-team.ru>. Commit 1 of 2.
Diffstat (limited to 'contrib/python/MarkupSafe/py3')
-rw-r--r-- | contrib/python/MarkupSafe/py3/markupsafe/__init__.py | 156 | ||||
-rw-r--r-- | contrib/python/MarkupSafe/py3/markupsafe/_native.py | 30 | ||||
-rw-r--r-- | contrib/python/MarkupSafe/py3/markupsafe/_speedups.c | 188 | ||||
-rw-r--r-- | contrib/python/MarkupSafe/py3/ya.make | 8 |
4 files changed, 191 insertions, 191 deletions
diff --git a/contrib/python/MarkupSafe/py3/markupsafe/__init__.py b/contrib/python/MarkupSafe/py3/markupsafe/__init__.py index d331ac3622..85bbf45363 100644 --- a/contrib/python/MarkupSafe/py3/markupsafe/__init__.py +++ b/contrib/python/MarkupSafe/py3/markupsafe/__init__.py @@ -1,21 +1,21 @@ import functools -import re -import string +import re +import string import typing as t - + if t.TYPE_CHECKING: import typing_extensions as te - + class HasHTML(te.Protocol): def __html__(self) -> str: pass - - + + __version__ = "2.0.1" _striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)") - - + + def _simple_escaping_wrapper(name: str) -> t.Callable[..., "Markup"]: orig = getattr(str, name) @@ -32,18 +32,18 @@ class Markup(str): """A string that is ready to be safely inserted into an HTML or XML document, either because it was escaped or because it was marked safe. - + Passing an object to the constructor converts it to text and wraps it to mark it safe without escaping. To escape the text, use the :meth:`escape` class method instead. - + >>> Markup("Hello, <em>World</em>!") Markup('Hello, <em>World</em>!') >>> Markup(42) Markup('42') >>> Markup.escape("Hello, <em>World</em>!") Markup('Hello <em>World</em>!') - + This implements the ``__html__()`` interface that some frameworks use. Passing an object that implements ``__html__()`` will wrap the output of that method, marking it safe. @@ -51,46 +51,46 @@ class Markup(str): >>> class Foo: ... def __html__(self): ... return '<a href="/foo">foo</a>' - ... - >>> Markup(Foo()) + ... + >>> Markup(Foo()) Markup('<a href="/foo">foo</a>') - + This is a subclass of :class:`str`. It has the same methods, but escapes their arguments and returns a ``Markup`` instance. - + >>> Markup("<em>%s</em>") % ("foo & bar",) Markup('<em>foo & bar</em>') >>> Markup("<em>Hello</em> ") + "<foo>" Markup('<em>Hello</em> <foo>') """ - - __slots__ = () - + + __slots__ = () + def __new__( cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict" ) -> "Markup": if hasattr(base, "__html__"): - base = base.__html__() + base = base.__html__() - if encoding is None: + if encoding is None: return super().__new__(cls, base) - + return super().__new__(cls, base, encoding, errors) def __html__(self) -> "Markup": - return self - + return self + def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup": if isinstance(other, str) or hasattr(other, "__html__"): return self.__class__(super().__add__(self.escape(other))) - return NotImplemented - + return NotImplemented + def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup": if isinstance(other, str) or hasattr(other, "__html__"): - return self.escape(other).__add__(self) - - return NotImplemented + return self.escape(other).__add__(self) + + return NotImplemented def __mul__(self, num: int) -> "Markup": if isinstance(num, int): @@ -98,50 +98,50 @@ class Markup(str): return NotImplemented # type: ignore - __rmul__ = __mul__ - + __rmul__ = __mul__ + def __mod__(self, arg: t.Any) -> "Markup": - if isinstance(arg, tuple): - arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg) - else: - arg = _MarkupEscapeHelper(arg, self.escape) - + if isinstance(arg, tuple): + arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg) + else: + arg = _MarkupEscapeHelper(arg, self.escape) + return self.__class__(super().__mod__(arg)) - + def __repr__(self) -> str: return f"{self.__class__.__name__}({super().__repr__()})" def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup": return self.__class__(super().join(map(self.escape, seq))) - + join.__doc__ = str.join.__doc__ def split( # type: ignore self, sep: t.Optional[str] = None, maxsplit: int = -1 ) -> t.List["Markup"]: return [self.__class__(v) for v in super().split(sep, maxsplit)] - + split.__doc__ = str.split.__doc__ def rsplit( # type: ignore self, sep: t.Optional[str] = None, maxsplit: int = -1 ) -> t.List["Markup"]: return [self.__class__(v) for v in super().rsplit(sep, maxsplit)] - + rsplit.__doc__ = str.rsplit.__doc__ def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore return [self.__class__(v) for v in super().splitlines(keepends)] - + splitlines.__doc__ = str.splitlines.__doc__ def unescape(self) -> str: """Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent. - + >>> Markup("Main » <em>About</em>").unescape() 'Main » <em>About</em>' - """ + """ from html import unescape return unescape(str(self)) @@ -149,25 +149,25 @@ class Markup(str): def striptags(self) -> str: """:meth:`unescape` the markup, remove tags, and normalize whitespace to single spaces. - + >>> Markup("Main »\t<em>About</em>").striptags() 'Main » About' - """ + """ stripped = " ".join(_striptags_re.sub("", self).split()) - return Markup(stripped).unescape() - - @classmethod + return Markup(stripped).unescape() + + @classmethod def escape(cls, s: t.Any) -> "Markup": """Escape a string. Calls :func:`escape` and ensures that for subclasses the correct type is returned. - """ - rv = escape(s) - - if rv.__class__ is not cls: - return cls(rv) + """ + rv = escape(s) - return rv + if rv.__class__ is not cls: + return cls(rv) + return rv + for method in ( "__getitem__", "capitalize", @@ -187,14 +187,14 @@ class Markup(str): "zfill", ): locals()[method] = _simple_escaping_wrapper(method) - + del method - + def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]: l, s, r = super().partition(self.escape(sep)) cls = self.__class__ return cls(l), cls(s), cls(r) - + def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]: l, s, r = super().rpartition(self.escape(sep)) cls = self.__class__ @@ -203,21 +203,21 @@ class Markup(str): def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup": formatter = EscapeFormatter(self.escape) return self.__class__(formatter.vformat(self, args, kwargs)) - + def __html_format__(self, format_spec: str) -> "Markup": if format_spec: raise ValueError("Unsupported format specification for Markup.") return self - + class EscapeFormatter(string.Formatter): __slots__ = ("escape",) - + def __init__(self, escape: t.Callable[[t.Any], Markup]) -> None: self.escape = escape super().__init__() - + def format_field(self, value: t.Any, format_spec: str) -> str: if hasattr(value, "__html_format__"): rv = value.__html_format__(format_spec) @@ -234,37 +234,37 @@ class EscapeFormatter(string.Formatter): # otherwise the wrong callback methods are invoked. rv = string.Formatter.format_field(self, value, str(format_spec)) return str(self.escape(rv)) - - + + _ListOrDict = t.TypeVar("_ListOrDict", list, dict) - - + + def _escape_argspec( obj: _ListOrDict, iterable: t.Iterable[t.Any], escape: t.Callable[[t.Any], Markup] ) -> _ListOrDict: - """Helper for various string-wrapped functions.""" - for key, value in iterable: + """Helper for various string-wrapped functions.""" + for key, value in iterable: if isinstance(value, str) or hasattr(value, "__html__"): - obj[key] = escape(value) - - return obj - + obj[key] = escape(value) + return obj + + class _MarkupEscapeHelper: """Helper for :meth:`Markup.__mod__`.""" - + __slots__ = ("obj", "escape") def __init__(self, obj: t.Any, escape: t.Callable[[t.Any], Markup]) -> None: - self.obj = obj - self.escape = escape - + self.obj = obj + self.escape = escape + def __getitem__(self, item: t.Any) -> "_MarkupEscapeHelper": return _MarkupEscapeHelper(self.obj[item], self.escape) - + def __str__(self) -> str: return str(self.escape(self.obj)) - + def __repr__(self) -> str: return str(self.escape(repr(self.obj))) @@ -276,12 +276,12 @@ class _MarkupEscapeHelper: # circular import -try: +try: from ._speedups import escape as escape from ._speedups import escape_silent as escape_silent from ._speedups import soft_str as soft_str from ._speedups import soft_unicode -except ImportError: +except ImportError: from ._native import escape as escape from ._native import escape_silent as escape_silent # noqa: F401 from ._native import soft_str as soft_str # noqa: F401 diff --git a/contrib/python/MarkupSafe/py3/markupsafe/_native.py b/contrib/python/MarkupSafe/py3/markupsafe/_native.py index 6f7eb7a8cb..8d5e144bbc 100644 --- a/contrib/python/MarkupSafe/py3/markupsafe/_native.py +++ b/contrib/python/MarkupSafe/py3/markupsafe/_native.py @@ -1,8 +1,8 @@ import typing as t - + from . import Markup - - + + def escape(s: t.Any) -> Markup: """Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in the string with HTML-safe sequences. Use this if you need to display @@ -13,7 +13,7 @@ def escape(s: t.Any) -> Markup: :param s: An object to be converted to a string and escaped. :return: A :class:`Markup` string with the escaped text. - """ + """ if hasattr(s, "__html__"): return Markup(s.__html__()) @@ -24,9 +24,9 @@ def escape(s: t.Any) -> Markup: .replace("<", "<") .replace("'", "'") .replace('"', """) - ) - - + ) + + def escape_silent(s: t.Optional[t.Any]) -> Markup: """Like :func:`escape` but treats ``None`` as the empty string. Useful with optional values, as otherwise you get the string @@ -36,13 +36,13 @@ def escape_silent(s: t.Optional[t.Any]) -> Markup: Markup('None') >>> escape_silent(None) Markup('') - """ - if s is None: - return Markup() - - return escape(s) - + """ + if s is None: + return Markup() + return escape(s) + + def soft_str(s: t.Any) -> str: """Convert an object to a string if it isn't already. This preserves a :class:`Markup` string rather than converting it back to a basic @@ -56,11 +56,11 @@ def soft_str(s: t.Any) -> str: Markup('&lt;User 1&gt;') >>> escape(soft_str(value)) Markup('<User 1>') - """ + """ if not isinstance(s, str): return str(s) - return s + return s def soft_unicode(s: t.Any) -> str: diff --git a/contrib/python/MarkupSafe/py3/markupsafe/_speedups.c b/contrib/python/MarkupSafe/py3/markupsafe/_speedups.c index 44967b1fdc..b56cd6bee1 100644 --- a/contrib/python/MarkupSafe/py3/markupsafe/_speedups.c +++ b/contrib/python/MarkupSafe/py3/markupsafe/_speedups.c @@ -1,22 +1,22 @@ -#include <Python.h> - -static PyObject* markup; - -static int -init_constants(void) -{ - PyObject *module; - - /* import markup type so that we can mark the return value */ - module = PyImport_ImportModule("markupsafe"); - if (!module) - return 0; - markup = PyObject_GetAttrString(module, "Markup"); - Py_DECREF(module); - - return 1; -} - +#include <Python.h> + +static PyObject* markup; + +static int +init_constants(void) +{ + PyObject *module; + + /* import markup type so that we can mark the return value */ + module = PyImport_ImportModule("markupsafe"); + if (!module) + return 0; + markup = PyObject_GetAttrString(module, "Markup"); + Py_DECREF(module); + + return 1; +} + #define GET_DELTA(inp, inp_end, delta) \ while (inp < inp_end) { \ switch (*inp++) { \ @@ -31,7 +31,7 @@ init_constants(void) break; \ } \ } - + #define DO_ESCAPE(inp, inp_end, outp) \ { \ Py_ssize_t ncopy = 0; \ @@ -88,7 +88,7 @@ init_constants(void) memcpy(outp, inp-ncopy, sizeof(*outp)*ncopy); \ } -static PyObject* +static PyObject* escape_unicode_kind1(PyUnicodeObject *in) { Py_UCS1 *inp = PyUnicode_1BYTE_DATA(in); @@ -184,11 +184,11 @@ escape_unicode(PyUnicodeObject *in) } static PyObject* -escape(PyObject *self, PyObject *text) -{ +escape(PyObject *self, PyObject *text) +{ static PyObject *id_html; - PyObject *s = NULL, *rv = NULL, *html; - + PyObject *s = NULL, *rv = NULL, *html; + if (id_html == NULL) { id_html = PyUnicode_InternFromString("__html__"); if (id_html == NULL) { @@ -196,67 +196,67 @@ escape(PyObject *self, PyObject *text) } } - /* we don't have to escape integers, bools or floats */ - if (PyLong_CheckExact(text) || + /* we don't have to escape integers, bools or floats */ + if (PyLong_CheckExact(text) || PyFloat_CheckExact(text) || PyBool_Check(text) || text == Py_None) - return PyObject_CallFunctionObjArgs(markup, text, NULL); - - /* if the object has an __html__ method that performs the escaping */ + return PyObject_CallFunctionObjArgs(markup, text, NULL); + + /* if the object has an __html__ method that performs the escaping */ html = PyObject_GetAttr(text ,id_html); - if (html) { + if (html) { s = PyObject_CallObject(html, NULL); - Py_DECREF(html); + Py_DECREF(html); if (s == NULL) { return NULL; } /* Convert to Markup object */ rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL); Py_DECREF(s); - return rv; - } - - /* otherwise make the object unicode if it isn't, then escape */ - PyErr_Clear(); - if (!PyUnicode_Check(text)) { - PyObject *unicode = PyObject_Str(text); - if (!unicode) - return NULL; - s = escape_unicode((PyUnicodeObject*)unicode); - Py_DECREF(unicode); - } - else - s = escape_unicode((PyUnicodeObject*)text); - - /* convert the unicode string into a markup object. */ - rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL); - Py_DECREF(s); - return rv; -} - - -static PyObject* -escape_silent(PyObject *self, PyObject *text) -{ - if (text != Py_None) - return escape(self, text); - return PyObject_CallFunctionObjArgs(markup, NULL); -} - - -static PyObject* + return rv; + } + + /* otherwise make the object unicode if it isn't, then escape */ + PyErr_Clear(); + if (!PyUnicode_Check(text)) { + PyObject *unicode = PyObject_Str(text); + if (!unicode) + return NULL; + s = escape_unicode((PyUnicodeObject*)unicode); + Py_DECREF(unicode); + } + else + s = escape_unicode((PyUnicodeObject*)text); + + /* convert the unicode string into a markup object. */ + rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL); + Py_DECREF(s); + return rv; +} + + +static PyObject* +escape_silent(PyObject *self, PyObject *text) +{ + if (text != Py_None) + return escape(self, text); + return PyObject_CallFunctionObjArgs(markup, NULL); +} + + +static PyObject* soft_str(PyObject *self, PyObject *s) -{ - if (!PyUnicode_Check(s)) - return PyObject_Str(s); - Py_INCREF(s); - return s; -} - - +{ + if (!PyUnicode_Check(s)) + return PyObject_Str(s); + Py_INCREF(s); + return s; +} + + static PyObject* soft_unicode(PyObject *self, PyObject *s) -{ +{ PyErr_WarnEx( PyExc_DeprecationWarning, "'soft_unicode' has been renamed to 'soft_str'. The old name" @@ -264,9 +264,9 @@ soft_unicode(PyObject *self, PyObject *s) 2 ); return soft_str(self, s); -} - - +} + + static PyMethodDef module_methods[] = { { "escape", @@ -317,23 +317,23 @@ static PyMethodDef module_methods[] = { {NULL, NULL, 0, NULL} /* Sentinel */ }; -static struct PyModuleDef module_definition = { +static struct PyModuleDef module_definition = { PyModuleDef_HEAD_INIT, - "markupsafe._speedups", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL -}; - -PyMODINIT_FUNC + "markupsafe._speedups", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit__speedups(void) -{ - if (!init_constants()) - return NULL; - - return PyModule_Create(&module_definition); -} +{ + if (!init_constants()) + return NULL; + + return PyModule_Create(&module_definition); +} diff --git a/contrib/python/MarkupSafe/py3/ya.make b/contrib/python/MarkupSafe/py3/ya.make index 8c750e15d8..d4344875f6 100644 --- a/contrib/python/MarkupSafe/py3/ya.make +++ b/contrib/python/MarkupSafe/py3/ya.make @@ -1,13 +1,13 @@ # Generated by devtools/yamaker (pypi). - + PY3_LIBRARY() - + OWNER(g:python-contrib) VERSION(2.0.1) LICENSE(BSD-3-Clause) - + NO_COMPILER_WARNINGS() NO_LINT() @@ -34,7 +34,7 @@ RESOURCE_FILES( markupsafe/py.typed ) -END() +END() RECURSE_FOR_TESTS( tests |