nwo
stringlengths 10
28
| sha
stringlengths 40
40
| path
stringlengths 11
97
| identifier
stringlengths 1
64
| parameters
stringlengths 2
2.24k
| return_statement
stringlengths 0
2.17k
| docstring
stringlengths 0
5.45k
| docstring_summary
stringlengths 0
3.83k
| func_begin
int64 1
13.4k
| func_end
int64 2
13.4k
| function
stringlengths 28
56.4k
| url
stringlengths 106
209
| project
int64 1
48
| executed_lines
list | executed_lines_pc
float64 0
153
| missing_lines
list | missing_lines_pc
float64 0
100
| covered
bool 2
classes | filecoverage
float64 2.53
100
| function_lines
int64 2
1.46k
| mccabe
int64 1
253
| coverage
float64 0
100
| docstring_lines
int64 0
112
| function_nodoc
stringlengths 9
56.4k
| id
int64 0
29.8k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
sync_do_map
|
(
context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any
)
|
Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
You can specify a ``default`` value to use if an object in the list
does not have the given attribute.
.. sourcecode:: jinja
{{ users|map(attribute="username", default="Anonymous")|join(", ") }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
Similar to a generator comprehension such as:
.. code-block:: python
(u.username for u in users)
(getattr(u, "username", "Anonymous") for u in users)
(do_lower(x) for x in titles)
.. versionchanged:: 2.11.0
Added the ``default`` parameter.
.. versionadded:: 2.7
|
Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
| 1,422 | 1,468 |
def sync_do_map(
context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any
) -> t.Iterable:
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
You can specify a ``default`` value to use if an object in the list
does not have the given attribute.
.. sourcecode:: jinja
{{ users|map(attribute="username", default="Anonymous")|join(", ") }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
Similar to a generator comprehension such as:
.. code-block:: python
(u.username for u in users)
(getattr(u, "username", "Anonymous") for u in users)
(do_lower(x) for x in titles)
.. versionchanged:: 2.11.0
Added the ``default`` parameter.
.. versionadded:: 2.7
"""
if value:
func = prepare_map(context, args, kwargs)
for item in value:
yield func(item)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1422-L1468
| 42 |
[
0,
41,
42,
43,
44,
45,
46
] | 14.893617 |
[] | 0 | false | 88.768606 | 47 | 3 | 100 | 38 |
def sync_do_map(
context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any
) -> t.Iterable:
if value:
func = prepare_map(context, args, kwargs)
for item in value:
yield func(item)
| 27,561 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
do_map
|
(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
name: str,
*args: t.Any,
**kwargs: t.Any,
)
| 1,472 | 1,479 |
def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
name: str,
*args: t.Any,
**kwargs: t.Any,
) -> t.Iterable:
...
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1472-L1479
| 42 |
[
0
] | 12.5 |
[
7
] | 12.5 | false | 88.768606 | 8 | 1 | 87.5 | 0 |
def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
name: str,
*args: t.Any,
**kwargs: t.Any,
) -> t.Iterable:
...
| 27,562 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
do_map
|
(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
*,
attribute: str = ...,
default: t.Optional[t.Any] = None,
)
| 1,483 | 1,490 |
def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
*,
attribute: str = ...,
default: t.Optional[t.Any] = None,
) -> t.Iterable:
...
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1483-L1490
| 42 |
[
0
] | 12.5 |
[
7
] | 12.5 | false | 88.768606 | 8 | 1 | 87.5 | 0 |
def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
*,
attribute: str = ...,
default: t.Optional[t.Any] = None,
) -> t.Iterable:
...
| 27,563 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
do_map
|
(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
*args: t.Any,
**kwargs: t.Any,
)
| 1,494 | 1,504 |
async def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
*args: t.Any,
**kwargs: t.Any,
) -> t.AsyncIterable:
if value:
func = prepare_map(context, args, kwargs)
async for item in auto_aiter(value):
yield await auto_await(func(item))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1494-L1504
| 42 |
[
0,
6,
7,
8,
9,
10
] | 54.545455 |
[] | 0 | false | 88.768606 | 11 | 3 | 100 | 0 |
async def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
*args: t.Any,
**kwargs: t.Any,
) -> t.AsyncIterable:
if value:
func = prepare_map(context, args, kwargs)
async for item in auto_aiter(value):
yield await auto_await(func(item))
| 27,564 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
sync_do_select
|
(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
)
|
return select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
Filters a sequence of objects by applying a test to each object,
and only selecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|select("odd") }}
{{ numbers|select("odd") }}
{{ numbers|select("divisibleby", 3) }}
{{ numbers|select("lessthan", 42) }}
{{ strings|select("equalto", "mystring") }}
Similar to a generator comprehension such as:
.. code-block:: python
(n for n in numbers if test_odd(n))
(n for n in numbers if test_divisibleby(n, 3))
.. versionadded:: 2.7
|
Filters a sequence of objects by applying a test to each object,
and only selecting the objects with the test succeeding.
| 1,508 | 1,535 |
def sync_do_select(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
"""Filters a sequence of objects by applying a test to each object,
and only selecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|select("odd") }}
{{ numbers|select("odd") }}
{{ numbers|select("divisibleby", 3) }}
{{ numbers|select("lessthan", 42) }}
{{ strings|select("equalto", "mystring") }}
Similar to a generator comprehension such as:
.. code-block:: python
(n for n in numbers if test_odd(n))
(n for n in numbers if test_divisibleby(n, 3))
.. versionadded:: 2.7
"""
return select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1508-L1535
| 42 |
[
0,
26,
27
] | 10.714286 |
[] | 0 | false | 88.768606 | 28 | 1 | 100 | 23 |
def sync_do_select(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
return select_or_reject(context, value, args, kwargs, lambda x: x, False)
| 27,565 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
do_select
|
(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
)
|
return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)
| 1,539 | 1,545 |
async def do_select(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1539-L1545
| 42 |
[
0,
6
] | 28.571429 |
[] | 0 | false | 88.768606 | 7 | 1 | 100 | 0 |
async def do_select(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)
| 27,566 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
sync_do_reject
|
(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
)
|
return select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
Filters a sequence of objects by applying a test to each object,
and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|reject("odd") }}
Similar to a generator comprehension such as:
.. code-block:: python
(n for n in numbers if not test_odd(n))
.. versionadded:: 2.7
|
Filters a sequence of objects by applying a test to each object,
and rejecting the objects with the test succeeding.
| 1,549 | 1,571 |
def sync_do_reject(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
"""Filters a sequence of objects by applying a test to each object,
and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|reject("odd") }}
Similar to a generator comprehension such as:
.. code-block:: python
(n for n in numbers if not test_odd(n))
.. versionadded:: 2.7
"""
return select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1549-L1571
| 42 |
[
0,
21,
22
] | 13.043478 |
[] | 0 | false | 88.768606 | 23 | 1 | 100 | 18 |
def sync_do_reject(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
return select_or_reject(context, value, args, kwargs, lambda x: not x, False)
| 27,567 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
do_reject
|
(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
)
|
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)
| 1,575 | 1,581 |
async def do_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1575-L1581
| 42 |
[
0,
6
] | 28.571429 |
[] | 0 | false | 88.768606 | 7 | 1 | 100 | 0 |
async def do_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)
| 27,568 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
sync_do_selectattr
|
(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
)
|
return select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
Example usage:
.. sourcecode:: jinja
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
Similar to a generator comprehension such as:
.. code-block:: python
(u for user in users if user.is_active)
(u for user in users if test_none(user.email))
.. versionadded:: 2.7
|
Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding.
| 1,585 | 1,611 |
def sync_do_selectattr(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
"""Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
Example usage:
.. sourcecode:: jinja
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
Similar to a generator comprehension such as:
.. code-block:: python
(u for user in users if user.is_active)
(u for user in users if test_none(user.email))
.. versionadded:: 2.7
"""
return select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1585-L1611
| 42 |
[
0,
25,
26
] | 11.111111 |
[] | 0 | false | 88.768606 | 27 | 1 | 100 | 22 |
def sync_do_selectattr(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
return select_or_reject(context, value, args, kwargs, lambda x: x, True)
| 27,569 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
do_selectattr
|
(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
)
|
return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)
| 1,615 | 1,621 |
async def do_selectattr(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1615-L1621
| 42 |
[
0,
6
] | 28.571429 |
[] | 0 | false | 88.768606 | 7 | 1 | 100 | 0 |
async def do_selectattr(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)
| 27,570 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
sync_do_rejectattr
|
(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
)
|
return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
Filters a sequence of objects by applying a test to the specified
attribute of each object, and rejecting the objects with the test
succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
Similar to a generator comprehension such as:
.. code-block:: python
(u for user in users if not user.is_active)
(u for user in users if not test_none(user.email))
.. versionadded:: 2.7
|
Filters a sequence of objects by applying a test to the specified
attribute of each object, and rejecting the objects with the test
succeeding.
| 1,625 | 1,649 |
def sync_do_rejectattr(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
"""Filters a sequence of objects by applying a test to the specified
attribute of each object, and rejecting the objects with the test
succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
Similar to a generator comprehension such as:
.. code-block:: python
(u for user in users if not user.is_active)
(u for user in users if not test_none(user.email))
.. versionadded:: 2.7
"""
return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1625-L1649
| 42 |
[
0,
23,
24
] | 12 |
[] | 0 | false | 88.768606 | 25 | 1 | 100 | 20 |
def sync_do_rejectattr(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
| 27,571 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
do_rejectattr
|
(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
)
|
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)
| 1,653 | 1,659 |
async def do_rejectattr(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1653-L1659
| 42 |
[
0
] | 14.285714 |
[
6
] | 14.285714 | false | 88.768606 | 7 | 1 | 85.714286 | 0 |
async def do_rejectattr(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)
| 27,572 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
do_tojson
|
(
eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
)
|
return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)
|
Serialize an object to a string of JSON, and mark it safe to
render in HTML. This filter is only for use in HTML documents.
The returned string is safe to render in HTML documents and
``<script>`` tags. The exception is in HTML attributes that are
double quoted; either use single quotes or the ``|forceescape``
filter.
:param value: The object to serialize to JSON.
:param indent: The ``indent`` parameter passed to ``dumps``, for
pretty-printing the value.
.. versionadded:: 2.9
|
Serialize an object to a string of JSON, and mark it safe to
render in HTML. This filter is only for use in HTML documents.
| 1,663 | 1,688 |
def do_tojson(
eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
) -> Markup:
"""Serialize an object to a string of JSON, and mark it safe to
render in HTML. This filter is only for use in HTML documents.
The returned string is safe to render in HTML documents and
``<script>`` tags. The exception is in HTML attributes that are
double quoted; either use single quotes or the ``|forceescape``
filter.
:param value: The object to serialize to JSON.
:param indent: The ``indent`` parameter passed to ``dumps``, for
pretty-printing the value.
.. versionadded:: 2.9
"""
policies = eval_ctx.environment.policies
dumps = policies["json.dumps_function"]
kwargs = policies["json.dumps_kwargs"]
if indent is not None:
kwargs = kwargs.copy()
kwargs["indent"] = indent
return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1663-L1688
| 42 |
[
0,
16,
17,
18,
19,
20,
21,
24,
25
] | 34.615385 |
[
22,
23
] | 7.692308 | false | 88.768606 | 26 | 2 | 92.307692 | 13 |
def do_tojson(
eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
) -> Markup:
policies = eval_ctx.environment.policies
dumps = policies["json.dumps_function"]
kwargs = policies["json.dumps_kwargs"]
if indent is not None:
kwargs = kwargs.copy()
kwargs["indent"] = indent
return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)
| 27,573 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
prepare_map
|
(
context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]
)
|
return func
| 1,691 | 1,716 |
def prepare_map(
context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]
) -> t.Callable[[t.Any], t.Any]:
if not args and "attribute" in kwargs:
attribute = kwargs.pop("attribute")
default = kwargs.pop("default", None)
if kwargs:
raise FilterArgumentError(
f"Unexpected keyword argument {next(iter(kwargs))!r}"
)
func = make_attrgetter(context.environment, attribute, default=default)
else:
try:
name = args[0]
args = args[1:]
except LookupError:
raise FilterArgumentError("map requires a filter argument") from None
def func(item: t.Any) -> t.Any:
return context.environment.call_filter(
name, item, args, kwargs, context=context
)
return func
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1691-L1716
| 42 |
[
0,
3,
4,
5,
6,
7,
11,
12,
14,
15,
16,
19,
20,
21,
24,
25
] | 61.538462 |
[
8,
17,
18
] | 11.538462 | false | 88.768606 | 26 | 6 | 88.461538 | 0 |
def prepare_map(
context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]
) -> t.Callable[[t.Any], t.Any]:
if not args and "attribute" in kwargs:
attribute = kwargs.pop("attribute")
default = kwargs.pop("default", None)
if kwargs:
raise FilterArgumentError(
f"Unexpected keyword argument {next(iter(kwargs))!r}"
)
func = make_attrgetter(context.environment, attribute, default=default)
else:
try:
name = args[0]
args = args[1:]
except LookupError:
raise FilterArgumentError("map requires a filter argument") from None
def func(item: t.Any) -> t.Any:
return context.environment.call_filter(
name, item, args, kwargs, context=context
)
return func
| 27,574 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
prepare_select_or_reject
|
(
context: "Context",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
)
|
return lambda item: modfunc(func(transfunc(item)))
| 1,719 | 1,750 |
def prepare_select_or_reject(
context: "Context",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> t.Callable[[t.Any], t.Any]:
if lookup_attr:
try:
attr = args[0]
except LookupError:
raise FilterArgumentError("Missing parameter for attribute name") from None
transfunc = make_attrgetter(context.environment, attr)
off = 1
else:
off = 0
def transfunc(x: V) -> V:
return x
try:
name = args[off]
args = args[1 + off :]
def func(item: t.Any) -> t.Any:
return context.environment.call_test(name, item, args, kwargs)
except LookupError:
func = bool # type: ignore
return lambda item: modfunc(func(transfunc(item)))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1719-L1750
| 42 |
[
0,
7,
8,
9,
12,
13,
14,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
] | 71.875 |
[
10,
11
] | 6.25 | false | 88.768606 | 32 | 6 | 93.75 | 0 |
def prepare_select_or_reject(
context: "Context",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> t.Callable[[t.Any], t.Any]:
if lookup_attr:
try:
attr = args[0]
except LookupError:
raise FilterArgumentError("Missing parameter for attribute name") from None
transfunc = make_attrgetter(context.environment, attr)
off = 1
else:
off = 0
def transfunc(x: V) -> V:
return x
try:
name = args[off]
args = args[1 + off :]
def func(item: t.Any) -> t.Any:
return context.environment.call_test(name, item, args, kwargs)
except LookupError:
func = bool # type: ignore
return lambda item: modfunc(func(transfunc(item)))
| 27,575 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
select_or_reject
|
(
context: "Context",
value: "t.Iterable[V]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
)
| 1,753 | 1,766 |
def select_or_reject(
context: "Context",
value: "t.Iterable[V]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.Iterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
for item in value:
if func(item):
yield item
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1753-L1766
| 42 |
[
0,
8,
9,
10,
11,
12,
13
] | 50 |
[] | 0 | false | 88.768606 | 14 | 4 | 100 | 0 |
def select_or_reject(
context: "Context",
value: "t.Iterable[V]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.Iterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
for item in value:
if func(item):
yield item
| 27,576 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
async_select_or_reject
|
(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
)
| 1,769 | 1,782 |
async def async_select_or_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.AsyncIterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
async for item in auto_aiter(value):
if func(item):
yield item
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1769-L1782
| 42 |
[
0,
8,
9,
10,
11,
12,
13
] | 50 |
[] | 0 | false | 88.768606 | 14 | 4 | 100 | 0 |
async def async_select_or_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.AsyncIterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
async for item in auto_aiter(value):
if func(item):
yield item
| 27,577 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
_GroupTuple.__repr__
|
(self)
|
return tuple.__repr__(self)
| 1,153 | 1,154 |
def __repr__(self) -> str:
return tuple.__repr__(self)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1153-L1154
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 88.768606 | 2 | 1 | 100 | 0 |
def __repr__(self) -> str:
return tuple.__repr__(self)
| 27,578 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/filters.py
|
_GroupTuple.__str__
|
(self)
|
return tuple.__str__(self)
| 1,156 | 1,157 |
def __str__(self) -> str:
return tuple.__str__(self)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1156-L1157
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 88.768606 | 2 | 1 | 100 | 0 |
def __str__(self) -> str:
return tuple.__str__(self)
| 27,579 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/async_utils.py
|
async_variant
|
(normal_func)
|
return decorator
| 12 | 53 |
def async_variant(normal_func): # type: ignore
def decorator(async_func): # type: ignore
pass_arg = _PassArg.from_obj(normal_func)
need_eval_context = pass_arg is None
if pass_arg is _PassArg.environment:
def is_async(args: t.Any) -> bool:
return t.cast(bool, args[0].is_async)
else:
def is_async(args: t.Any) -> bool:
return t.cast(bool, args[0].environment.is_async)
# Take the doc and annotations from the sync function, but the
# name from the async function. Pallets-Sphinx-Themes
# build_function_directive expects __wrapped__ to point to the
# sync function.
async_func_attrs = ("__module__", "__name__", "__qualname__")
normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs))
@wraps(normal_func, assigned=normal_func_attrs)
@wraps(async_func, assigned=async_func_attrs, updated=())
def wrapper(*args, **kwargs): # type: ignore
b = is_async(args)
if need_eval_context:
args = args[1:]
if b:
return async_func(*args, **kwargs)
return normal_func(*args, **kwargs)
if need_eval_context:
wrapper = pass_eval_context(wrapper)
wrapper.jinja_async_variant = True
return wrapper
return decorator
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/async_utils.py#L12-L53
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41
] | 97.619048 |
[] | 0 | false | 100 | 42 | 9 | 100 | 0 |
def async_variant(normal_func): # type: ignore
def decorator(async_func): # type: ignore
pass_arg = _PassArg.from_obj(normal_func)
need_eval_context = pass_arg is None
if pass_arg is _PassArg.environment:
def is_async(args: t.Any) -> bool:
return t.cast(bool, args[0].is_async)
else:
def is_async(args: t.Any) -> bool:
return t.cast(bool, args[0].environment.is_async)
# Take the doc and annotations from the sync function, but the
# name from the async function. Pallets-Sphinx-Themes
# build_function_directive expects __wrapped__ to point to the
# sync function.
async_func_attrs = ("__module__", "__name__", "__qualname__")
normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs))
@wraps(normal_func, assigned=normal_func_attrs)
@wraps(async_func, assigned=async_func_attrs, updated=())
def wrapper(*args, **kwargs): # type: ignore
b = is_async(args)
if need_eval_context:
args = args[1:]
if b:
return async_func(*args, **kwargs)
return normal_func(*args, **kwargs)
if need_eval_context:
wrapper = pass_eval_context(wrapper)
wrapper.jinja_async_variant = True
return wrapper
return decorator
| 27,580 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/async_utils.py
|
auto_await
|
(value: t.Union[t.Awaitable["V"], "V"])
|
return t.cast("V", value)
| 59 | 67 |
async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
# Avoid a costly call to isawaitable
if type(value) in _common_primitives:
return t.cast("V", value)
if inspect.isawaitable(value):
return await t.cast("t.Awaitable[V]", value)
return t.cast("V", value)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/async_utils.py#L59-L67
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 |
[] | 0 | true | 100 | 9 | 3 | 100 | 0 |
async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
# Avoid a costly call to isawaitable
if type(value) in _common_primitives:
return t.cast("V", value)
if inspect.isawaitable(value):
return await t.cast("t.Awaitable[V]", value)
return t.cast("V", value)
| 27,581 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/async_utils.py
|
auto_aiter
|
(
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
)
| 70 | 78 |
async def auto_aiter(
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> "t.AsyncIterator[V]":
if hasattr(iterable, "__aiter__"):
async for item in t.cast("t.AsyncIterable[V]", iterable):
yield item
else:
for item in iterable:
yield item
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/async_utils.py#L70-L78
| 42 |
[
0,
3,
4,
5,
7,
8
] | 66.666667 |
[] | 0 | false | 100 | 9 | 4 | 100 | 0 |
async def auto_aiter(
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> "t.AsyncIterator[V]":
if hasattr(iterable, "__aiter__"):
async for item in t.cast("t.AsyncIterable[V]", iterable):
yield item
else:
for item in iterable:
yield item
| 27,582 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/async_utils.py
|
auto_to_list
|
(
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
)
|
return [x async for x in auto_aiter(value)]
| 81 | 84 |
async def auto_to_list(
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> t.List["V"]:
return [x async for x in auto_aiter(value)]
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/async_utils.py#L81-L84
| 42 |
[
0,
3
] | 50 |
[] | 0 | false | 100 | 4 | 2 | 100 | 0 |
async def auto_to_list(
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> t.List["V"]:
return [x async for x in auto_aiter(value)]
| 27,583 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
Bucket.__init__
|
(self, environment: "Environment", key: str, checksum: str)
| 53 | 57 |
def __init__(self, environment: "Environment", key: str, checksum: str) -> None:
self.environment = environment
self.key = key
self.checksum = checksum
self.reset()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L53-L57
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 56.666667 | 5 | 1 | 100 | 0 |
def __init__(self, environment: "Environment", key: str, checksum: str) -> None:
self.environment = environment
self.key = key
self.checksum = checksum
self.reset()
| 27,584 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
Bucket.reset
|
(self)
|
Resets the bucket (unloads the bytecode).
|
Resets the bucket (unloads the bytecode).
| 59 | 61 |
def reset(self) -> None:
"""Resets the bucket (unloads the bytecode)."""
self.code: t.Optional[CodeType] = None
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L59-L61
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 56.666667 | 3 | 1 | 100 | 1 |
def reset(self) -> None:
self.code: t.Optional[CodeType] = None
| 27,585 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
Bucket.load_bytecode
|
(self, f: t.BinaryIO)
|
Loads bytecode from a file or file like object.
|
Loads bytecode from a file or file like object.
| 63 | 80 |
def load_bytecode(self, f: t.BinaryIO) -> None:
"""Loads bytecode from a file or file like object."""
# make sure the magic header is correct
magic = f.read(len(bc_magic))
if magic != bc_magic:
self.reset()
return
# the source code of the file changed, we need to reload
checksum = pickle.load(f)
if self.checksum != checksum:
self.reset()
return
# if marshal_load fails then we need to reload
try:
self.code = marshal.load(f)
except (EOFError, ValueError, TypeError):
self.reset()
return
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L63-L80
| 42 |
[
0,
1,
2,
3,
4,
7,
8,
9,
12,
13,
14
] | 61.111111 |
[
5,
6,
10,
11,
15,
16,
17
] | 38.888889 | false | 56.666667 | 18 | 4 | 61.111111 | 1 |
def load_bytecode(self, f: t.BinaryIO) -> None:
# make sure the magic header is correct
magic = f.read(len(bc_magic))
if magic != bc_magic:
self.reset()
return
# the source code of the file changed, we need to reload
checksum = pickle.load(f)
if self.checksum != checksum:
self.reset()
return
# if marshal_load fails then we need to reload
try:
self.code = marshal.load(f)
except (EOFError, ValueError, TypeError):
self.reset()
return
| 27,586 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
Bucket.write_bytecode
|
(self, f: t.IO[bytes])
|
Dump the bytecode into the file or file like object passed.
|
Dump the bytecode into the file or file like object passed.
| 82 | 88 |
def write_bytecode(self, f: t.IO[bytes]) -> None:
"""Dump the bytecode into the file or file like object passed."""
if self.code is None:
raise TypeError("can't write empty bucket")
f.write(bc_magic)
pickle.dump(self.checksum, f, 2)
marshal.dump(self.code, f)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L82-L88
| 42 |
[
0,
1,
2,
4,
5,
6
] | 85.714286 |
[
3
] | 14.285714 | false | 56.666667 | 7 | 2 | 85.714286 | 1 |
def write_bytecode(self, f: t.IO[bytes]) -> None:
if self.code is None:
raise TypeError("can't write empty bucket")
f.write(bc_magic)
pickle.dump(self.checksum, f, 2)
marshal.dump(self.code, f)
| 27,587 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
Bucket.bytecode_from_string
|
(self, string: bytes)
|
Load bytecode from bytes.
|
Load bytecode from bytes.
| 90 | 92 |
def bytecode_from_string(self, string: bytes) -> None:
"""Load bytecode from bytes."""
self.load_bytecode(BytesIO(string))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L90-L92
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 56.666667 | 3 | 1 | 100 | 1 |
def bytecode_from_string(self, string: bytes) -> None:
self.load_bytecode(BytesIO(string))
| 27,588 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
Bucket.bytecode_to_string
|
(self)
|
return out.getvalue()
|
Return the bytecode as bytes.
|
Return the bytecode as bytes.
| 94 | 98 |
def bytecode_to_string(self) -> bytes:
"""Return the bytecode as bytes."""
out = BytesIO()
self.write_bytecode(out)
return out.getvalue()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L94-L98
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 56.666667 | 5 | 1 | 100 | 1 |
def bytecode_to_string(self) -> bytes:
out = BytesIO()
self.write_bytecode(out)
return out.getvalue()
| 27,589 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
BytecodeCache.load_bytecode
|
(self, bucket: Bucket)
|
Subclasses have to override this method to load bytecode into a
bucket. If they are not able to find code in the cache for the
bucket, it must not do anything.
|
Subclasses have to override this method to load bytecode into a
bucket. If they are not able to find code in the cache for the
bucket, it must not do anything.
| 130 | 135 |
def load_bytecode(self, bucket: Bucket) -> None:
"""Subclasses have to override this method to load bytecode into a
bucket. If they are not able to find code in the cache for the
bucket, it must not do anything.
"""
raise NotImplementedError()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L130-L135
| 42 |
[
0,
1,
2,
3,
4
] | 83.333333 |
[
5
] | 16.666667 | false | 56.666667 | 6 | 1 | 83.333333 | 3 |
def load_bytecode(self, bucket: Bucket) -> None:
raise NotImplementedError()
| 27,590 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
BytecodeCache.dump_bytecode
|
(self, bucket: Bucket)
|
Subclasses have to override this method to write the bytecode
from a bucket back to the cache. If it unable to do so it must not
fail silently but raise an exception.
|
Subclasses have to override this method to write the bytecode
from a bucket back to the cache. If it unable to do so it must not
fail silently but raise an exception.
| 137 | 142 |
def dump_bytecode(self, bucket: Bucket) -> None:
"""Subclasses have to override this method to write the bytecode
from a bucket back to the cache. If it unable to do so it must not
fail silently but raise an exception.
"""
raise NotImplementedError()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L137-L142
| 42 |
[
0,
1,
2,
3,
4
] | 83.333333 |
[
5
] | 16.666667 | false | 56.666667 | 6 | 1 | 83.333333 | 3 |
def dump_bytecode(self, bucket: Bucket) -> None:
raise NotImplementedError()
| 27,591 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
BytecodeCache.clear
|
(self)
|
Clears the cache. This method is not used by Jinja but should be
implemented to allow applications to clear the bytecode cache used
by a particular environment.
|
Clears the cache. This method is not used by Jinja but should be
implemented to allow applications to clear the bytecode cache used
by a particular environment.
| 144 | 148 |
def clear(self) -> None:
"""Clears the cache. This method is not used by Jinja but should be
implemented to allow applications to clear the bytecode cache used
by a particular environment.
"""
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L144-L148
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 56.666667 | 5 | 1 | 100 | 3 |
def clear(self) -> None:
| 27,592 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
BytecodeCache.get_cache_key
|
(
self, name: str, filename: t.Optional[t.Union[str]] = None
)
|
return hash.hexdigest()
|
Returns the unique hash key for this template name.
|
Returns the unique hash key for this template name.
| 150 | 159 |
def get_cache_key(
self, name: str, filename: t.Optional[t.Union[str]] = None
) -> str:
"""Returns the unique hash key for this template name."""
hash = sha1(name.encode("utf-8"))
if filename is not None:
hash.update(f"|{filename}".encode())
return hash.hexdigest()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L150-L159
| 42 |
[
0,
3,
4,
5,
6,
7,
8,
9
] | 80 |
[] | 0 | false | 56.666667 | 10 | 2 | 100 | 1 |
def get_cache_key(
self, name: str, filename: t.Optional[t.Union[str]] = None
) -> str:
hash = sha1(name.encode("utf-8"))
if filename is not None:
hash.update(f"|{filename}".encode())
return hash.hexdigest()
| 27,593 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
BytecodeCache.get_source_checksum
|
(self, source: str)
|
return sha1(source.encode("utf-8")).hexdigest()
|
Returns a checksum for the source.
|
Returns a checksum for the source.
| 161 | 163 |
def get_source_checksum(self, source: str) -> str:
"""Returns a checksum for the source."""
return sha1(source.encode("utf-8")).hexdigest()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L161-L163
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 56.666667 | 3 | 1 | 100 | 1 |
def get_source_checksum(self, source: str) -> str:
return sha1(source.encode("utf-8")).hexdigest()
| 27,594 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
BytecodeCache.get_bucket
|
(
self,
environment: "Environment",
name: str,
filename: t.Optional[str],
source: str,
)
|
return bucket
|
Return a cache bucket for the given template. All arguments are
mandatory but filename may be `None`.
|
Return a cache bucket for the given template. All arguments are
mandatory but filename may be `None`.
| 165 | 179 |
def get_bucket(
self,
environment: "Environment",
name: str,
filename: t.Optional[str],
source: str,
) -> Bucket:
"""Return a cache bucket for the given template. All arguments are
mandatory but filename may be `None`.
"""
key = self.get_cache_key(name, filename)
checksum = self.get_source_checksum(source)
bucket = Bucket(environment, key, checksum)
self.load_bytecode(bucket)
return bucket
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L165-L179
| 42 |
[
0,
9,
10,
11,
12,
13,
14
] | 46.666667 |
[] | 0 | false | 56.666667 | 15 | 1 | 100 | 2 |
def get_bucket(
self,
environment: "Environment",
name: str,
filename: t.Optional[str],
source: str,
) -> Bucket:
key = self.get_cache_key(name, filename)
checksum = self.get_source_checksum(source)
bucket = Bucket(environment, key, checksum)
self.load_bytecode(bucket)
return bucket
| 27,595 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
BytecodeCache.set_bucket
|
(self, bucket: Bucket)
|
Put the bucket into the cache.
|
Put the bucket into the cache.
| 181 | 183 |
def set_bucket(self, bucket: Bucket) -> None:
"""Put the bucket into the cache."""
self.dump_bytecode(bucket)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L181-L183
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 56.666667 | 3 | 1 | 100 | 1 |
def set_bucket(self, bucket: Bucket) -> None:
self.dump_bytecode(bucket)
| 27,596 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
FileSystemBytecodeCache.__init__
|
(
self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache"
)
| 204 | 210 |
def __init__(
self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache"
) -> None:
if directory is None:
directory = self._get_default_cache_dir()
self.directory = directory
self.pattern = pattern
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L204-L210
| 42 |
[
0,
3,
5,
6
] | 57.142857 |
[
4
] | 14.285714 | false | 56.666667 | 7 | 2 | 85.714286 | 0 |
def __init__(
self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache"
) -> None:
if directory is None:
directory = self._get_default_cache_dir()
self.directory = directory
self.pattern = pattern
| 27,597 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
FileSystemBytecodeCache._get_default_cache_dir
|
(self)
|
return actual_dir
| 212 | 257 |
def _get_default_cache_dir(self) -> str:
def _unsafe_dir() -> "te.NoReturn":
raise RuntimeError(
"Cannot determine safe temp directory. You "
"need to explicitly provide one."
)
tmpdir = tempfile.gettempdir()
# On windows the temporary directory is used specific unless
# explicitly forced otherwise. We can just use that.
if os.name == "nt":
return tmpdir
if not hasattr(os, "getuid"):
_unsafe_dir()
dirname = f"_jinja2-cache-{os.getuid()}"
actual_dir = os.path.join(tmpdir, dirname)
try:
os.mkdir(actual_dir, stat.S_IRWXU)
except OSError as e:
if e.errno != errno.EEXIST:
raise
try:
os.chmod(actual_dir, stat.S_IRWXU)
actual_dir_stat = os.lstat(actual_dir)
if (
actual_dir_stat.st_uid != os.getuid()
or not stat.S_ISDIR(actual_dir_stat.st_mode)
or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU
):
_unsafe_dir()
except OSError as e:
if e.errno != errno.EEXIST:
raise
actual_dir_stat = os.lstat(actual_dir)
if (
actual_dir_stat.st_uid != os.getuid()
or not stat.S_ISDIR(actual_dir_stat.st_mode)
or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU
):
_unsafe_dir()
return actual_dir
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L212-L257
| 42 |
[
0
] | 2.173913 |
[
1,
2,
7,
11,
12,
13,
14,
16,
17,
19,
20,
21,
22,
23,
24,
25,
26,
27,
32,
33,
34,
35,
37,
38,
43,
45
] | 56.521739 | false | 56.666667 | 46 | 14 | 43.478261 | 0 |
def _get_default_cache_dir(self) -> str:
def _unsafe_dir() -> "te.NoReturn":
raise RuntimeError(
"Cannot determine safe temp directory. You "
"need to explicitly provide one."
)
tmpdir = tempfile.gettempdir()
# On windows the temporary directory is used specific unless
# explicitly forced otherwise. We can just use that.
if os.name == "nt":
return tmpdir
if not hasattr(os, "getuid"):
_unsafe_dir()
dirname = f"_jinja2-cache-{os.getuid()}"
actual_dir = os.path.join(tmpdir, dirname)
try:
os.mkdir(actual_dir, stat.S_IRWXU)
except OSError as e:
if e.errno != errno.EEXIST:
raise
try:
os.chmod(actual_dir, stat.S_IRWXU)
actual_dir_stat = os.lstat(actual_dir)
if (
actual_dir_stat.st_uid != os.getuid()
or not stat.S_ISDIR(actual_dir_stat.st_mode)
or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU
):
_unsafe_dir()
except OSError as e:
if e.errno != errno.EEXIST:
raise
actual_dir_stat = os.lstat(actual_dir)
if (
actual_dir_stat.st_uid != os.getuid()
or not stat.S_ISDIR(actual_dir_stat.st_mode)
or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU
):
_unsafe_dir()
return actual_dir
| 27,598 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
FileSystemBytecodeCache._get_cache_filename
|
(self, bucket: Bucket)
|
return os.path.join(self.directory, self.pattern % (bucket.key,))
| 259 | 260 |
def _get_cache_filename(self, bucket: Bucket) -> str:
return os.path.join(self.directory, self.pattern % (bucket.key,))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L259-L260
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 56.666667 | 2 | 1 | 100 | 0 |
def _get_cache_filename(self, bucket: Bucket) -> str:
return os.path.join(self.directory, self.pattern % (bucket.key,))
| 27,599 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
FileSystemBytecodeCache.load_bytecode
|
(self, bucket: Bucket)
| 262 | 275 |
def load_bytecode(self, bucket: Bucket) -> None:
filename = self._get_cache_filename(bucket)
# Don't test for existence before opening the file, since the
# file could disappear after the test before the open.
try:
f = open(filename, "rb")
except (FileNotFoundError, IsADirectoryError, PermissionError):
# PermissionError can occur on Windows when an operation is
# in progress, such as calling clear().
return
with f:
bucket.load_bytecode(f)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L262-L275
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 85.714286 |
[
12,
13
] | 14.285714 | false | 56.666667 | 14 | 3 | 85.714286 | 0 |
def load_bytecode(self, bucket: Bucket) -> None:
filename = self._get_cache_filename(bucket)
# Don't test for existence before opening the file, since the
# file could disappear after the test before the open.
try:
f = open(filename, "rb")
except (FileNotFoundError, IsADirectoryError, PermissionError):
# PermissionError can occur on Windows when an operation is
# in progress, such as calling clear().
return
with f:
bucket.load_bytecode(f)
| 27,600 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
FileSystemBytecodeCache.dump_bytecode
|
(self, bucket: Bucket)
| 277 | 313 |
def dump_bytecode(self, bucket: Bucket) -> None:
# Write to a temporary file, then rename to the real name after
# writing. This avoids another process reading the file before
# it is fully written.
name = self._get_cache_filename(bucket)
f = tempfile.NamedTemporaryFile(
mode="wb",
dir=os.path.dirname(name),
prefix=os.path.basename(name),
suffix=".tmp",
delete=False,
)
def remove_silent() -> None:
try:
os.remove(f.name)
except OSError:
# Another process may have called clear(). On Windows,
# another program may be holding the file open.
pass
try:
with f:
bucket.write_bytecode(f)
except BaseException:
remove_silent()
raise
try:
os.replace(f.name, name)
except OSError:
# Another process may have called clear(). On Windows,
# another program may be holding the file open.
remove_silent()
except BaseException:
remove_silent()
raise
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L277-L313
| 42 |
[
0,
1,
2,
3,
4,
5,
12,
13,
20,
21,
22,
23,
27,
28,
29
] | 40.540541 |
[
14,
15,
16,
19,
24,
25,
26,
30,
33,
34,
35,
36
] | 32.432432 | false | 56.666667 | 37 | 7 | 67.567568 | 0 |
def dump_bytecode(self, bucket: Bucket) -> None:
# Write to a temporary file, then rename to the real name after
# writing. This avoids another process reading the file before
# it is fully written.
name = self._get_cache_filename(bucket)
f = tempfile.NamedTemporaryFile(
mode="wb",
dir=os.path.dirname(name),
prefix=os.path.basename(name),
suffix=".tmp",
delete=False,
)
def remove_silent() -> None:
try:
os.remove(f.name)
except OSError:
# Another process may have called clear(). On Windows,
# another program may be holding the file open.
pass
try:
with f:
bucket.write_bytecode(f)
except BaseException:
remove_silent()
raise
try:
os.replace(f.name, name)
except OSError:
# Another process may have called clear(). On Windows,
# another program may be holding the file open.
remove_silent()
except BaseException:
remove_silent()
raise
| 27,601 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
FileSystemBytecodeCache.clear
|
(self)
| 315 | 326 |
def clear(self) -> None:
# imported lazily here because google app-engine doesn't support
# write access on the file system and the function does not exist
# normally.
from os import remove
files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",))
for filename in files:
try:
remove(os.path.join(self.directory, filename))
except OSError:
pass
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L315-L326
| 42 |
[
0,
1,
2,
3
] | 33.333333 |
[
4,
6,
7,
8,
9,
10,
11
] | 58.333333 | false | 56.666667 | 12 | 3 | 41.666667 | 0 |
def clear(self) -> None:
# imported lazily here because google app-engine doesn't support
# write access on the file system and the function does not exist
# normally.
from os import remove
files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",))
for filename in files:
try:
remove(os.path.join(self.directory, filename))
except OSError:
pass
| 27,602 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
MemcachedBytecodeCache.__init__
|
(
self,
client: "_MemcachedClient",
prefix: str = "jinja2/bytecode/",
timeout: t.Optional[int] = None,
ignore_memcache_errors: bool = True,
)
| 374 | 384 |
def __init__(
self,
client: "_MemcachedClient",
prefix: str = "jinja2/bytecode/",
timeout: t.Optional[int] = None,
ignore_memcache_errors: bool = True,
):
self.client = client
self.prefix = prefix
self.timeout = timeout
self.ignore_memcache_errors = ignore_memcache_errors
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L374-L384
| 42 |
[
0,
7,
8,
9,
10
] | 45.454545 |
[] | 0 | false | 56.666667 | 11 | 1 | 100 | 0 |
def __init__(
self,
client: "_MemcachedClient",
prefix: str = "jinja2/bytecode/",
timeout: t.Optional[int] = None,
ignore_memcache_errors: bool = True,
):
self.client = client
self.prefix = prefix
self.timeout = timeout
self.ignore_memcache_errors = ignore_memcache_errors
| 27,603 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
MemcachedBytecodeCache.load_bytecode
|
(self, bucket: Bucket)
| 386 | 393 |
def load_bytecode(self, bucket: Bucket) -> None:
try:
code = self.client.get(self.prefix + bucket.key)
except Exception:
if not self.ignore_memcache_errors:
raise
else:
bucket.bytecode_from_string(code)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L386-L393
| 42 |
[
0,
1,
2,
3,
4,
5,
7
] | 87.5 |
[] | 0 | false | 56.666667 | 8 | 3 | 100 | 0 |
def load_bytecode(self, bucket: Bucket) -> None:
try:
code = self.client.get(self.prefix + bucket.key)
except Exception:
if not self.ignore_memcache_errors:
raise
else:
bucket.bytecode_from_string(code)
| 27,604 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/bccache.py
|
MemcachedBytecodeCache.dump_bytecode
|
(self, bucket: Bucket)
| 395 | 406 |
def dump_bytecode(self, bucket: Bucket) -> None:
key = self.prefix + bucket.key
value = bucket.bytecode_to_string()
try:
if self.timeout is not None:
self.client.set(key, value, self.timeout)
else:
self.client.set(key, value)
except Exception:
if not self.ignore_memcache_errors:
raise
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/bccache.py#L395-L406
| 42 |
[
0,
1,
2,
3,
4,
5,
8,
9,
10,
11
] | 83.333333 |
[
6
] | 8.333333 | false | 56.666667 | 12 | 4 | 91.666667 | 0 |
def dump_bytecode(self, bucket: Bucket) -> None:
key = self.prefix + bucket.key
value = bucket.bytecode_to_string()
try:
if self.timeout is not None:
self.client.set(key, value, self.timeout)
else:
self.client.set(key, value)
except Exception:
if not self.ignore_memcache_errors:
raise
| 27,605 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
_gettext_alias
|
(
__context: Context, *args: t.Any, **kwargs: t.Any
)
|
return __context.call(__context.resolve("gettext"), *args, **kwargs)
| 164 | 167 |
def _gettext_alias(
__context: Context, *args: t.Any, **kwargs: t.Any
) -> t.Union[t.Any, Undefined]:
return __context.call(__context.resolve("gettext"), *args, **kwargs)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L164-L167
| 42 |
[
0,
3
] | 50 |
[] | 0 | false | 78.838951 | 4 | 1 | 100 | 0 |
def _gettext_alias(
__context: Context, *args: t.Any, **kwargs: t.Any
) -> t.Union[t.Any, Undefined]:
return __context.call(__context.resolve("gettext"), *args, **kwargs)
| 27,606 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
_make_new_gettext
|
(func: t.Callable[[str], str])
|
return gettext
| 170 | 181 |
def _make_new_gettext(func: t.Callable[[str], str]) -> t.Callable[..., str]:
@pass_context
def gettext(__context: Context, __string: str, **variables: t.Any) -> str:
rv = __context.call(func, __string)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, even if there are no
# variables. This makes translation strings more consistent
# and predictable. This requires escaping
return rv % variables # type: ignore
return gettext
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L170-L181
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 |
[] | 0 | true | 78.838951 | 12 | 3 | 100 | 0 |
def _make_new_gettext(func: t.Callable[[str], str]) -> t.Callable[..., str]:
@pass_context
def gettext(__context: Context, __string: str, **variables: t.Any) -> str:
rv = __context.call(func, __string)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, even if there are no
# variables. This makes translation strings more consistent
# and predictable. This requires escaping
return rv % variables # type: ignore
return gettext
| 27,607 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
_make_new_ngettext
|
(func: t.Callable[[str, str, int], str])
|
return ngettext
| 184 | 200 |
def _make_new_ngettext(func: t.Callable[[str, str, int], str]) -> t.Callable[..., str]:
@pass_context
def ngettext(
__context: Context,
__singular: str,
__plural: str,
__num: int,
**variables: t.Any,
) -> str:
variables.setdefault("num", __num)
rv = __context.call(func, __singular, __plural, __num)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return ngettext
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L184-L200
| 42 |
[
0,
1,
2,
9,
10,
11,
13,
14,
15,
16
] | 58.823529 |
[
12
] | 5.882353 | false | 78.838951 | 17 | 3 | 94.117647 | 0 |
def _make_new_ngettext(func: t.Callable[[str, str, int], str]) -> t.Callable[..., str]:
@pass_context
def ngettext(
__context: Context,
__singular: str,
__plural: str,
__num: int,
**variables: t.Any,
) -> str:
variables.setdefault("num", __num)
rv = __context.call(func, __singular, __plural, __num)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return ngettext
| 27,608 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
_make_new_pgettext
|
(func: t.Callable[[str, str], str])
|
return pgettext
| 203 | 217 |
def _make_new_pgettext(func: t.Callable[[str, str], str]) -> t.Callable[..., str]:
@pass_context
def pgettext(
__context: Context, __string_ctx: str, __string: str, **variables: t.Any
) -> str:
variables.setdefault("context", __string_ctx)
rv = __context.call(func, __string_ctx, __string)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return pgettext
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L203-L217
| 42 |
[
0,
1,
2,
5,
6,
7,
8,
11,
12,
13,
14
] | 73.333333 |
[
9
] | 6.666667 | false | 78.838951 | 15 | 3 | 93.333333 | 0 |
def _make_new_pgettext(func: t.Callable[[str, str], str]) -> t.Callable[..., str]:
@pass_context
def pgettext(
__context: Context, __string_ctx: str, __string: str, **variables: t.Any
) -> str:
variables.setdefault("context", __string_ctx)
rv = __context.call(func, __string_ctx, __string)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return pgettext
| 27,609 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
_make_new_npgettext
|
(
func: t.Callable[[str, str, str, int], str]
)
|
return npgettext
| 220 | 242 |
def _make_new_npgettext(
func: t.Callable[[str, str, str, int], str]
) -> t.Callable[..., str]:
@pass_context
def npgettext(
__context: Context,
__string_ctx: str,
__singular: str,
__plural: str,
__num: int,
**variables: t.Any,
) -> str:
variables.setdefault("context", __string_ctx)
variables.setdefault("num", __num)
rv = __context.call(func, __string_ctx, __singular, __plural, __num)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return npgettext
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L220-L242
| 42 |
[
0,
3,
4,
12,
13,
14,
15,
16,
19,
20,
21,
22
] | 52.173913 |
[
17
] | 4.347826 | false | 78.838951 | 23 | 3 | 95.652174 | 0 |
def _make_new_npgettext(
func: t.Callable[[str, str, str, int], str]
) -> t.Callable[..., str]:
@pass_context
def npgettext(
__context: Context,
__string_ctx: str,
__singular: str,
__plural: str,
__num: int,
**variables: t.Any,
) -> str:
variables.setdefault("context", __string_ctx)
variables.setdefault("num", __num)
rv = __context.call(func, __string_ctx, __singular, __plural, __num)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return npgettext
| 27,610 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
extract_from_ast
|
(
ast: nodes.Template,
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
babel_style: bool = True,
)
|
Extract localizable strings from the given template node. Per
default this function returns matches in babel style that means non string
parameters as well as keyword arguments are returned as `None`. This
allows Babel to figure out what you really meant if you are using
gettext functions that allow keyword arguments for placeholder expansion.
If you don't want that behavior set the `babel_style` parameter to `False`
which causes only strings to be returned and parameters are always stored
in tuples. As a consequence invalid gettext calls (calls without a single
string parameter or string parameters after non-string parameters) are
skipped.
This example explains the behavior:
>>> from jinja2 import Environment
>>> env = Environment()
>>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
>>> list(extract_from_ast(node))
[(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
>>> list(extract_from_ast(node, babel_style=False))
[(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
For every string found this function yields a ``(lineno, function,
message)`` tuple, where:
* ``lineno`` is the number of the line on which the string was found,
* ``function`` is the name of the ``gettext`` function used (if the
string was extracted from embedded Python code), and
* ``message`` is the string, or a tuple of strings for functions
with multiple string arguments.
This extraction function operates on the AST and is because of that unable
to extract any comments. For comment support you have to use the babel
extraction interface or extract comments yourself.
|
Extract localizable strings from the given template node. Per
default this function returns matches in babel style that means non string
parameters as well as keyword arguments are returned as `None`. This
allows Babel to figure out what you really meant if you are using
gettext functions that allow keyword arguments for placeholder expansion.
If you don't want that behavior set the `babel_style` parameter to `False`
which causes only strings to be returned and parameters are always stored
in tuples. As a consequence invalid gettext calls (calls without a single
string parameter or string parameters after non-string parameters) are
skipped.
| 644 | 720 |
def extract_from_ast(
ast: nodes.Template,
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
babel_style: bool = True,
) -> t.Iterator[
t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]
]:
"""Extract localizable strings from the given template node. Per
default this function returns matches in babel style that means non string
parameters as well as keyword arguments are returned as `None`. This
allows Babel to figure out what you really meant if you are using
gettext functions that allow keyword arguments for placeholder expansion.
If you don't want that behavior set the `babel_style` parameter to `False`
which causes only strings to be returned and parameters are always stored
in tuples. As a consequence invalid gettext calls (calls without a single
string parameter or string parameters after non-string parameters) are
skipped.
This example explains the behavior:
>>> from jinja2 import Environment
>>> env = Environment()
>>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
>>> list(extract_from_ast(node))
[(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
>>> list(extract_from_ast(node, babel_style=False))
[(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
For every string found this function yields a ``(lineno, function,
message)`` tuple, where:
* ``lineno`` is the number of the line on which the string was found,
* ``function`` is the name of the ``gettext`` function used (if the
string was extracted from embedded Python code), and
* ``message`` is the string, or a tuple of strings for functions
with multiple string arguments.
This extraction function operates on the AST and is because of that unable
to extract any comments. For comment support you have to use the babel
extraction interface or extract comments yourself.
"""
out: t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]
for node in ast.find_all(nodes.Call):
if (
not isinstance(node.node, nodes.Name)
or node.node.name not in gettext_functions
):
continue
strings: t.List[t.Optional[str]] = []
for arg in node.args:
if isinstance(arg, nodes.Const) and isinstance(arg.value, str):
strings.append(arg.value)
else:
strings.append(None)
for _ in node.kwargs:
strings.append(None)
if node.dyn_args is not None:
strings.append(None)
if node.dyn_kwargs is not None:
strings.append(None)
if not babel_style:
out = tuple(x for x in strings if x is not None)
if not out:
continue
else:
if len(strings) == 1:
out = strings[0]
else:
out = tuple(strings)
yield node.lineno, node.node.name, out
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L644-L720
| 42 |
[
0,
42,
43,
44,
49,
50,
51,
52,
53,
54,
56,
57,
58,
60,
62,
64,
65,
71,
72,
74,
75,
76
] | 28.571429 |
[
48,
59,
61,
63,
66,
68,
69
] | 9.090909 | false | 78.838951 | 77 | 13 | 90.909091 | 33 |
def extract_from_ast(
ast: nodes.Template,
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
babel_style: bool = True,
) -> t.Iterator[
t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]
]:
out: t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]
for node in ast.find_all(nodes.Call):
if (
not isinstance(node.node, nodes.Name)
or node.node.name not in gettext_functions
):
continue
strings: t.List[t.Optional[str]] = []
for arg in node.args:
if isinstance(arg, nodes.Const) and isinstance(arg.value, str):
strings.append(arg.value)
else:
strings.append(None)
for _ in node.kwargs:
strings.append(None)
if node.dyn_args is not None:
strings.append(None)
if node.dyn_kwargs is not None:
strings.append(None)
if not babel_style:
out = tuple(x for x in strings if x is not None)
if not out:
continue
else:
if len(strings) == 1:
out = strings[0]
else:
out = tuple(strings)
yield node.lineno, node.node.name, out
| 27,611 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
babel_extract
|
(
fileobj: t.BinaryIO,
keywords: t.Sequence[str],
comment_tags: t.Sequence[str],
options: t.Dict[str, t.Any],
)
|
Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently)
|
Babel extraction method for Jinja templates.
| 763 | 852 |
def babel_extract(
fileobj: t.BinaryIO,
keywords: t.Sequence[str],
comment_tags: t.Sequence[str],
options: t.Dict[str, t.Any],
) -> t.Iterator[
t.Tuple[
int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]], t.List[str]
]
]:
"""Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently)
"""
extensions: t.Dict[t.Type[Extension], None] = {}
for extension_name in options.get("extensions", "").split(","):
extension_name = extension_name.strip()
if not extension_name:
continue
extensions[import_string(extension_name)] = None
if InternationalizationExtension not in extensions:
extensions[InternationalizationExtension] = None
def getbool(options: t.Mapping[str, str], key: str, default: bool = False) -> bool:
return options.get(key, str(default)).lower() in {"1", "on", "yes", "true"}
silent = getbool(options, "silent", True)
environment = Environment(
options.get("block_start_string", defaults.BLOCK_START_STRING),
options.get("block_end_string", defaults.BLOCK_END_STRING),
options.get("variable_start_string", defaults.VARIABLE_START_STRING),
options.get("variable_end_string", defaults.VARIABLE_END_STRING),
options.get("comment_start_string", defaults.COMMENT_START_STRING),
options.get("comment_end_string", defaults.COMMENT_END_STRING),
options.get("line_statement_prefix") or defaults.LINE_STATEMENT_PREFIX,
options.get("line_comment_prefix") or defaults.LINE_COMMENT_PREFIX,
getbool(options, "trim_blocks", defaults.TRIM_BLOCKS),
getbool(options, "lstrip_blocks", defaults.LSTRIP_BLOCKS),
defaults.NEWLINE_SEQUENCE,
getbool(options, "keep_trailing_newline", defaults.KEEP_TRAILING_NEWLINE),
tuple(extensions),
cache_size=0,
auto_reload=False,
)
if getbool(options, "trimmed"):
environment.policies["ext.i18n.trimmed"] = True
if getbool(options, "newstyle_gettext"):
environment.newstyle_gettext = True # type: ignore
source = fileobj.read().decode(options.get("encoding", "utf-8"))
try:
node = environment.parse(source)
tokens = list(environment.lex(environment.preprocess(source)))
except TemplateSyntaxError:
if not silent:
raise
# skip templates with syntax errors
return
finder = _CommentFinder(tokens, comment_tags)
for lineno, func, message in extract_from_ast(node, keywords):
yield lineno, func, message, finder.find_comments(lineno)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L763-L852
| 42 |
[
0,
36,
37,
38,
39,
40,
41,
42,
43,
44,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
76,
77,
78,
79,
80,
86,
87,
88,
89
] | 53.333333 |
[
45,
75,
81,
82,
83,
85
] | 6.666667 | false | 78.838951 | 90 | 12 | 93.333333 | 26 |
def babel_extract(
fileobj: t.BinaryIO,
keywords: t.Sequence[str],
comment_tags: t.Sequence[str],
options: t.Dict[str, t.Any],
) -> t.Iterator[
t.Tuple[
int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]], t.List[str]
]
]:
extensions: t.Dict[t.Type[Extension], None] = {}
for extension_name in options.get("extensions", "").split(","):
extension_name = extension_name.strip()
if not extension_name:
continue
extensions[import_string(extension_name)] = None
if InternationalizationExtension not in extensions:
extensions[InternationalizationExtension] = None
def getbool(options: t.Mapping[str, str], key: str, default: bool = False) -> bool:
return options.get(key, str(default)).lower() in {"1", "on", "yes", "true"}
silent = getbool(options, "silent", True)
environment = Environment(
options.get("block_start_string", defaults.BLOCK_START_STRING),
options.get("block_end_string", defaults.BLOCK_END_STRING),
options.get("variable_start_string", defaults.VARIABLE_START_STRING),
options.get("variable_end_string", defaults.VARIABLE_END_STRING),
options.get("comment_start_string", defaults.COMMENT_START_STRING),
options.get("comment_end_string", defaults.COMMENT_END_STRING),
options.get("line_statement_prefix") or defaults.LINE_STATEMENT_PREFIX,
options.get("line_comment_prefix") or defaults.LINE_COMMENT_PREFIX,
getbool(options, "trim_blocks", defaults.TRIM_BLOCKS),
getbool(options, "lstrip_blocks", defaults.LSTRIP_BLOCKS),
defaults.NEWLINE_SEQUENCE,
getbool(options, "keep_trailing_newline", defaults.KEEP_TRAILING_NEWLINE),
tuple(extensions),
cache_size=0,
auto_reload=False,
)
if getbool(options, "trimmed"):
environment.policies["ext.i18n.trimmed"] = True
if getbool(options, "newstyle_gettext"):
environment.newstyle_gettext = True # type: ignore
source = fileobj.read().decode(options.get("encoding", "utf-8"))
try:
node = environment.parse(source)
tokens = list(environment.lex(environment.preprocess(source)))
except TemplateSyntaxError:
if not silent:
raise
# skip templates with syntax errors
return
finder = _CommentFinder(tokens, comment_tags)
for lineno, func, message in extract_from_ast(node, keywords):
yield lineno, func, message, finder.find_comments(lineno)
| 27,612 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
Extension.__init_subclass__
|
(cls)
| 75 | 76 |
def __init_subclass__(cls) -> None:
cls.identifier = f"{cls.__module__}.{cls.__name__}"
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L75-L76
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 78.838951 | 2 | 1 | 100 | 0 |
def __init_subclass__(cls) -> None:
cls.identifier = f"{cls.__module__}.{cls.__name__}"
| 27,613 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
Extension.__init__
|
(self, environment: Environment)
| 88 | 89 |
def __init__(self, environment: Environment) -> None:
self.environment = environment
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L88-L89
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 78.838951 | 2 | 1 | 100 | 0 |
def __init__(self, environment: Environment) -> None:
self.environment = environment
| 27,614 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
Extension.bind
|
(self, environment: Environment)
|
return rv
|
Create a copy of this extension bound to another environment.
|
Create a copy of this extension bound to another environment.
| 91 | 96 |
def bind(self, environment: Environment) -> "Extension":
"""Create a copy of this extension bound to another environment."""
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.environment = environment
return rv
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L91-L96
| 42 |
[
0,
1,
2,
3,
4,
5
] | 100 |
[] | 0 | true | 78.838951 | 6 | 1 | 100 | 1 |
def bind(self, environment: Environment) -> "Extension":
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.environment = environment
return rv
| 27,615 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
Extension.preprocess
|
(
self, source: str, name: t.Optional[str], filename: t.Optional[str] = None
)
|
return source
|
This method is called before the actual lexing and can be used to
preprocess the source. The `filename` is optional. The return value
must be the preprocessed source.
|
This method is called before the actual lexing and can be used to
preprocess the source. The `filename` is optional. The return value
must be the preprocessed source.
| 98 | 105 |
def preprocess(
self, source: str, name: t.Optional[str], filename: t.Optional[str] = None
) -> str:
"""This method is called before the actual lexing and can be used to
preprocess the source. The `filename` is optional. The return value
must be the preprocessed source.
"""
return source
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L98-L105
| 42 |
[
0,
6,
7
] | 37.5 |
[] | 0 | false | 78.838951 | 8 | 1 | 100 | 3 |
def preprocess(
self, source: str, name: t.Optional[str], filename: t.Optional[str] = None
) -> str:
return source
| 27,616 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
Extension.filter_stream
|
(
self, stream: "TokenStream"
)
|
return stream
|
It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
to filter tokens returned. This method has to return an iterable of
:class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a
:class:`~jinja2.lexer.TokenStream`.
|
It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
to filter tokens returned. This method has to return an iterable of
:class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a
:class:`~jinja2.lexer.TokenStream`.
| 107 | 115 |
def filter_stream(
self, stream: "TokenStream"
) -> t.Union["TokenStream", t.Iterable["Token"]]:
"""It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
to filter tokens returned. This method has to return an iterable of
:class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a
:class:`~jinja2.lexer.TokenStream`.
"""
return stream
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L107-L115
| 42 |
[
0,
7,
8
] | 33.333333 |
[] | 0 | false | 78.838951 | 9 | 1 | 100 | 4 |
def filter_stream(
self, stream: "TokenStream"
) -> t.Union["TokenStream", t.Iterable["Token"]]:
return stream
| 27,617 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
Extension.parse
|
(self, parser: "Parser")
|
If any of the :attr:`tags` matched this method is called with the
parser as first argument. The token the parser stream is pointing at
is the name token that matched. This method has to return one or a
list of multiple nodes.
|
If any of the :attr:`tags` matched this method is called with the
parser as first argument. The token the parser stream is pointing at
is the name token that matched. This method has to return one or a
list of multiple nodes.
| 117 | 123 |
def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
"""If any of the :attr:`tags` matched this method is called with the
parser as first argument. The token the parser stream is pointing at
is the name token that matched. This method has to return one or a
list of multiple nodes.
"""
raise NotImplementedError()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L117-L123
| 42 |
[
0,
1,
2,
3,
4,
5
] | 85.714286 |
[
6
] | 14.285714 | false | 78.838951 | 7 | 1 | 85.714286 | 4 |
def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
raise NotImplementedError()
| 27,618 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
Extension.attr
|
(
self, name: str, lineno: t.Optional[int] = None
)
|
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
|
Return an attribute node for the current extension. This is useful
to pass constants on extensions to generated template code.
::
self.attr('_my_attribute', lineno=lineno)
|
Return an attribute node for the current extension. This is useful
to pass constants on extensions to generated template code.
| 125 | 135 |
def attr(
self, name: str, lineno: t.Optional[int] = None
) -> nodes.ExtensionAttribute:
"""Return an attribute node for the current extension. This is useful
to pass constants on extensions to generated template code.
::
self.attr('_my_attribute', lineno=lineno)
"""
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L125-L135
| 42 |
[
0,
9,
10
] | 27.272727 |
[] | 0 | false | 78.838951 | 11 | 1 | 100 | 6 |
def attr(
self, name: str, lineno: t.Optional[int] = None
) -> nodes.ExtensionAttribute:
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
| 27,619 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
Extension.call_method
|
(
self,
name: str,
args: t.Optional[t.List[nodes.Expr]] = None,
kwargs: t.Optional[t.List[nodes.Keyword]] = None,
dyn_args: t.Optional[nodes.Expr] = None,
dyn_kwargs: t.Optional[nodes.Expr] = None,
lineno: t.Optional[int] = None,
)
|
return nodes.Call(
self.attr(name, lineno=lineno),
args,
kwargs,
dyn_args,
dyn_kwargs,
lineno=lineno,
)
|
Call a method of the extension. This is a shortcut for
:meth:`attr` + :class:`jinja2.nodes.Call`.
|
Call a method of the extension. This is a shortcut for
:meth:`attr` + :class:`jinja2.nodes.Call`.
| 137 | 160 |
def call_method(
self,
name: str,
args: t.Optional[t.List[nodes.Expr]] = None,
kwargs: t.Optional[t.List[nodes.Keyword]] = None,
dyn_args: t.Optional[nodes.Expr] = None,
dyn_kwargs: t.Optional[nodes.Expr] = None,
lineno: t.Optional[int] = None,
) -> nodes.Call:
"""Call a method of the extension. This is a shortcut for
:meth:`attr` + :class:`jinja2.nodes.Call`.
"""
if args is None:
args = []
if kwargs is None:
kwargs = []
return nodes.Call(
self.attr(name, lineno=lineno),
args,
kwargs,
dyn_args,
dyn_kwargs,
lineno=lineno,
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L137-L160
| 42 |
[
0,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
] | 58.333333 |
[] | 0 | false | 78.838951 | 24 | 3 | 100 | 2 |
def call_method(
self,
name: str,
args: t.Optional[t.List[nodes.Expr]] = None,
kwargs: t.Optional[t.List[nodes.Keyword]] = None,
dyn_args: t.Optional[nodes.Expr] = None,
dyn_kwargs: t.Optional[nodes.Expr] = None,
lineno: t.Optional[int] = None,
) -> nodes.Call:
if args is None:
args = []
if kwargs is None:
kwargs = []
return nodes.Call(
self.attr(name, lineno=lineno),
args,
kwargs,
dyn_args,
dyn_kwargs,
lineno=lineno,
)
| 27,620 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension.__init__
|
(self, environment: Environment)
| 257 | 267 |
def __init__(self, environment: Environment) -> None:
super().__init__(environment)
environment.globals["_"] = _gettext_alias
environment.extend(
install_gettext_translations=self._install,
install_null_translations=self._install_null,
install_gettext_callables=self._install_callables,
uninstall_gettext_translations=self._uninstall,
extract_translations=self._extract,
newstyle_gettext=False,
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L257-L267
| 42 |
[
0,
1,
2,
3
] | 36.363636 |
[] | 0 | false | 78.838951 | 11 | 1 | 100 | 0 |
def __init__(self, environment: Environment) -> None:
super().__init__(environment)
environment.globals["_"] = _gettext_alias
environment.extend(
install_gettext_translations=self._install,
install_null_translations=self._install_null,
install_gettext_callables=self._install_callables,
uninstall_gettext_translations=self._uninstall,
extract_translations=self._extract,
newstyle_gettext=False,
)
| 27,621 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension._install
|
(
self, translations: "_SupportedTranslations", newstyle: t.Optional[bool] = None
)
| 269 | 285 |
def _install(
self, translations: "_SupportedTranslations", newstyle: t.Optional[bool] = None
) -> None:
# ugettext and ungettext are preferred in case the I18N library
# is providing compatibility with older Python versions.
gettext = getattr(translations, "ugettext", None)
if gettext is None:
gettext = translations.gettext
ngettext = getattr(translations, "ungettext", None)
if ngettext is None:
ngettext = translations.ngettext
pgettext = getattr(translations, "pgettext", None)
npgettext = getattr(translations, "npgettext", None)
self._install_callables(
gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L269-L285
| 42 |
[
0
] | 5.882353 |
[
5,
6,
7,
8,
9,
10,
12,
13,
14
] | 52.941176 | false | 78.838951 | 17 | 3 | 47.058824 | 0 |
def _install(
self, translations: "_SupportedTranslations", newstyle: t.Optional[bool] = None
) -> None:
# ugettext and ungettext are preferred in case the I18N library
# is providing compatibility with older Python versions.
gettext = getattr(translations, "ugettext", None)
if gettext is None:
gettext = translations.gettext
ngettext = getattr(translations, "ungettext", None)
if ngettext is None:
ngettext = translations.ngettext
pgettext = getattr(translations, "pgettext", None)
npgettext = getattr(translations, "npgettext", None)
self._install_callables(
gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext
)
| 27,622 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension._install_null
|
(self, newstyle: t.Optional[bool] = None)
| 287 | 313 |
def _install_null(self, newstyle: t.Optional[bool] = None) -> None:
import gettext
translations = gettext.NullTranslations()
if hasattr(translations, "pgettext"):
# Python < 3.8
pgettext = translations.pgettext
else:
def pgettext(c: str, s: str) -> str:
return s
if hasattr(translations, "npgettext"):
npgettext = translations.npgettext
else:
def npgettext(c: str, s: str, p: str, n: int) -> str:
return s if n == 1 else p
self._install_callables(
gettext=translations.gettext,
ngettext=translations.ngettext,
newstyle=newstyle,
pgettext=pgettext,
npgettext=npgettext,
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L287-L313
| 42 |
[
0
] | 3.703704 |
[
1,
3,
5,
7,
10,
11,
13,
14,
17,
18,
20
] | 40.740741 | false | 78.838951 | 27 | 5 | 59.259259 | 0 |
def _install_null(self, newstyle: t.Optional[bool] = None) -> None:
import gettext
translations = gettext.NullTranslations()
if hasattr(translations, "pgettext"):
# Python < 3.8
pgettext = translations.pgettext
else:
def pgettext(c: str, s: str) -> str:
return s
if hasattr(translations, "npgettext"):
npgettext = translations.npgettext
else:
def npgettext(c: str, s: str, p: str, n: int) -> str:
return s if n == 1 else p
self._install_callables(
gettext=translations.gettext,
ngettext=translations.ngettext,
newstyle=newstyle,
pgettext=pgettext,
npgettext=npgettext,
)
| 27,623 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension._install_callables
|
(
self,
gettext: t.Callable[[str], str],
ngettext: t.Callable[[str, str, int], str],
newstyle: t.Optional[bool] = None,
pgettext: t.Optional[t.Callable[[str, str], str]] = None,
npgettext: t.Optional[t.Callable[[str, str, str, int], str]] = None,
)
| 315 | 337 |
def _install_callables(
self,
gettext: t.Callable[[str], str],
ngettext: t.Callable[[str, str, int], str],
newstyle: t.Optional[bool] = None,
pgettext: t.Optional[t.Callable[[str, str], str]] = None,
npgettext: t.Optional[t.Callable[[str, str, str, int], str]] = None,
) -> None:
if newstyle is not None:
self.environment.newstyle_gettext = newstyle # type: ignore
if self.environment.newstyle_gettext: # type: ignore
gettext = _make_new_gettext(gettext)
ngettext = _make_new_ngettext(ngettext)
if pgettext is not None:
pgettext = _make_new_pgettext(pgettext)
if npgettext is not None:
npgettext = _make_new_npgettext(npgettext)
self.environment.globals.update(
gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L315-L337
| 42 |
[
0,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
] | 60.869565 |
[] | 0 | false | 78.838951 | 23 | 5 | 100 | 0 |
def _install_callables(
self,
gettext: t.Callable[[str], str],
ngettext: t.Callable[[str, str, int], str],
newstyle: t.Optional[bool] = None,
pgettext: t.Optional[t.Callable[[str, str], str]] = None,
npgettext: t.Optional[t.Callable[[str, str, str, int], str]] = None,
) -> None:
if newstyle is not None:
self.environment.newstyle_gettext = newstyle # type: ignore
if self.environment.newstyle_gettext: # type: ignore
gettext = _make_new_gettext(gettext)
ngettext = _make_new_ngettext(ngettext)
if pgettext is not None:
pgettext = _make_new_pgettext(pgettext)
if npgettext is not None:
npgettext = _make_new_npgettext(npgettext)
self.environment.globals.update(
gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext
)
| 27,624 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension._uninstall
|
(self, translations: "_SupportedTranslations")
| 339 | 341 |
def _uninstall(self, translations: "_SupportedTranslations") -> None:
for key in ("gettext", "ngettext", "pgettext", "npgettext"):
self.environment.globals.pop(key, None)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L339-L341
| 42 |
[
0
] | 33.333333 |
[
1,
2
] | 66.666667 | false | 78.838951 | 3 | 2 | 33.333333 | 0 |
def _uninstall(self, translations: "_SupportedTranslations") -> None:
for key in ("gettext", "ngettext", "pgettext", "npgettext"):
self.environment.globals.pop(key, None)
| 27,625 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension._extract
|
(
self,
source: t.Union[str, nodes.Template],
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
)
|
return extract_from_ast(source, gettext_functions)
| 343 | 352 |
def _extract(
self,
source: t.Union[str, nodes.Template],
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
) -> t.Iterator[
t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]
]:
if isinstance(source, str):
source = self.environment.parse(source)
return extract_from_ast(source, gettext_functions)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L343-L352
| 42 |
[
0
] | 10 |
[
7,
8,
9
] | 30 | false | 78.838951 | 10 | 2 | 70 | 0 |
def _extract(
self,
source: t.Union[str, nodes.Template],
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
) -> t.Iterator[
t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]
]:
if isinstance(source, str):
source = self.environment.parse(source)
return extract_from_ast(source, gettext_functions)
| 27,626 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension.parse
|
(self, parser: "Parser")
|
Parse a translatable tag.
|
Parse a translatable tag.
| 354 | 474 |
def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
"""Parse a translatable tag."""
lineno = next(parser.stream).lineno
context = None
context_token = parser.stream.next_if("string")
if context_token is not None:
context = context_token.value
# find all the variables referenced. Additionally a variable can be
# defined in the body of the trans block too, but this is checked at
# a later state.
plural_expr: t.Optional[nodes.Expr] = None
plural_expr_assignment: t.Optional[nodes.Assign] = None
num_called_num = False
variables: t.Dict[str, nodes.Expr] = {}
trimmed = None
while parser.stream.current.type != "block_end":
if variables:
parser.stream.expect("comma")
# skip colon for python compatibility
if parser.stream.skip_if("colon"):
break
token = parser.stream.expect("name")
if token.value in variables:
parser.fail(
f"translatable variable {token.value!r} defined twice.",
token.lineno,
exc=TemplateAssertionError,
)
# expressions
if parser.stream.current.type == "assign":
next(parser.stream)
variables[token.value] = var = parser.parse_expression()
elif trimmed is None and token.value in ("trimmed", "notrimmed"):
trimmed = token.value == "trimmed"
continue
else:
variables[token.value] = var = nodes.Name(token.value, "load")
if plural_expr is None:
if isinstance(var, nodes.Call):
plural_expr = nodes.Name("_trans", "load")
variables[token.value] = plural_expr
plural_expr_assignment = nodes.Assign(
nodes.Name("_trans", "store"), var
)
else:
plural_expr = var
num_called_num = token.value == "num"
parser.stream.expect("block_end")
plural = None
have_plural = False
referenced = set()
# now parse until endtrans or pluralize
singular_names, singular = self._parse_block(parser, True)
if singular_names:
referenced.update(singular_names)
if plural_expr is None:
plural_expr = nodes.Name(singular_names[0], "load")
num_called_num = singular_names[0] == "num"
# if we have a pluralize block, we parse that too
if parser.stream.current.test("name:pluralize"):
have_plural = True
next(parser.stream)
if parser.stream.current.type != "block_end":
token = parser.stream.expect("name")
if token.value not in variables:
parser.fail(
f"unknown variable {token.value!r} for pluralization",
token.lineno,
exc=TemplateAssertionError,
)
plural_expr = variables[token.value]
num_called_num = token.value == "num"
parser.stream.expect("block_end")
plural_names, plural = self._parse_block(parser, False)
next(parser.stream)
referenced.update(plural_names)
else:
next(parser.stream)
# register free names as simple name expressions
for name in referenced:
if name not in variables:
variables[name] = nodes.Name(name, "load")
if not have_plural:
plural_expr = None
elif plural_expr is None:
parser.fail("pluralize without variables", lineno)
if trimmed is None:
trimmed = self.environment.policies["ext.i18n.trimmed"]
if trimmed:
singular = self._trim_whitespace(singular)
if plural:
plural = self._trim_whitespace(plural)
node = self._make_node(
singular,
plural,
context,
variables,
plural_expr,
bool(referenced),
num_called_num and have_plural,
)
node.set_lineno(lineno)
if plural_expr_assignment is not None:
return [plural_expr_assignment, node]
else:
return node
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L354-L474
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
25,
26,
27,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
99,
100,
101,
102,
103,
104,
105,
106,
107,
108,
109,
110,
111,
112,
113,
114,
115,
116,
117,
118,
119,
120
] | 93.38843 |
[
24,
28,
98
] | 2.479339 | false | 78.838951 | 121 | 25 | 97.520661 | 1 |
def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
lineno = next(parser.stream).lineno
context = None
context_token = parser.stream.next_if("string")
if context_token is not None:
context = context_token.value
# find all the variables referenced. Additionally a variable can be
# defined in the body of the trans block too, but this is checked at
# a later state.
plural_expr: t.Optional[nodes.Expr] = None
plural_expr_assignment: t.Optional[nodes.Assign] = None
num_called_num = False
variables: t.Dict[str, nodes.Expr] = {}
trimmed = None
while parser.stream.current.type != "block_end":
if variables:
parser.stream.expect("comma")
# skip colon for python compatibility
if parser.stream.skip_if("colon"):
break
token = parser.stream.expect("name")
if token.value in variables:
parser.fail(
f"translatable variable {token.value!r} defined twice.",
token.lineno,
exc=TemplateAssertionError,
)
# expressions
if parser.stream.current.type == "assign":
next(parser.stream)
variables[token.value] = var = parser.parse_expression()
elif trimmed is None and token.value in ("trimmed", "notrimmed"):
trimmed = token.value == "trimmed"
continue
else:
variables[token.value] = var = nodes.Name(token.value, "load")
if plural_expr is None:
if isinstance(var, nodes.Call):
plural_expr = nodes.Name("_trans", "load")
variables[token.value] = plural_expr
plural_expr_assignment = nodes.Assign(
nodes.Name("_trans", "store"), var
)
else:
plural_expr = var
num_called_num = token.value == "num"
parser.stream.expect("block_end")
plural = None
have_plural = False
referenced = set()
# now parse until endtrans or pluralize
singular_names, singular = self._parse_block(parser, True)
if singular_names:
referenced.update(singular_names)
if plural_expr is None:
plural_expr = nodes.Name(singular_names[0], "load")
num_called_num = singular_names[0] == "num"
# if we have a pluralize block, we parse that too
if parser.stream.current.test("name:pluralize"):
have_plural = True
next(parser.stream)
if parser.stream.current.type != "block_end":
token = parser.stream.expect("name")
if token.value not in variables:
parser.fail(
f"unknown variable {token.value!r} for pluralization",
token.lineno,
exc=TemplateAssertionError,
)
plural_expr = variables[token.value]
num_called_num = token.value == "num"
parser.stream.expect("block_end")
plural_names, plural = self._parse_block(parser, False)
next(parser.stream)
referenced.update(plural_names)
else:
next(parser.stream)
# register free names as simple name expressions
for name in referenced:
if name not in variables:
variables[name] = nodes.Name(name, "load")
if not have_plural:
plural_expr = None
elif plural_expr is None:
parser.fail("pluralize without variables", lineno)
if trimmed is None:
trimmed = self.environment.policies["ext.i18n.trimmed"]
if trimmed:
singular = self._trim_whitespace(singular)
if plural:
plural = self._trim_whitespace(plural)
node = self._make_node(
singular,
plural,
context,
variables,
plural_expr,
bool(referenced),
num_called_num and have_plural,
)
node.set_lineno(lineno)
if plural_expr_assignment is not None:
return [plural_expr_assignment, node]
else:
return node
| 27,627 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension._trim_whitespace
|
(self, string: str, _ws_re: t.Pattern[str] = _ws_re)
|
return _ws_re.sub(" ", string.strip())
| 476 | 477 |
def _trim_whitespace(self, string: str, _ws_re: t.Pattern[str] = _ws_re) -> str:
return _ws_re.sub(" ", string.strip())
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L476-L477
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 78.838951 | 2 | 1 | 100 | 0 |
def _trim_whitespace(self, string: str, _ws_re: t.Pattern[str] = _ws_re) -> str:
return _ws_re.sub(" ", string.strip())
| 27,628 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension._parse_block
|
(
self, parser: "Parser", allow_pluralize: bool
)
|
return referenced, concat(buf)
|
Parse until the next block tag with a given name.
|
Parse until the next block tag with a given name.
| 479 | 514 |
def _parse_block(
self, parser: "Parser", allow_pluralize: bool
) -> t.Tuple[t.List[str], str]:
"""Parse until the next block tag with a given name."""
referenced = []
buf = []
while True:
if parser.stream.current.type == "data":
buf.append(parser.stream.current.value.replace("%", "%%"))
next(parser.stream)
elif parser.stream.current.type == "variable_begin":
next(parser.stream)
name = parser.stream.expect("name").value
referenced.append(name)
buf.append(f"%({name})s")
parser.stream.expect("variable_end")
elif parser.stream.current.type == "block_begin":
next(parser.stream)
if parser.stream.current.test("name:endtrans"):
break
elif parser.stream.current.test("name:pluralize"):
if allow_pluralize:
break
parser.fail(
"a translatable section can have only one pluralize section"
)
parser.fail(
"control structures in translatable sections are not allowed"
)
elif parser.stream.eos:
parser.fail("unclosed translation block")
else:
raise RuntimeError("internal parser error")
return referenced, concat(buf)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L479-L514
| 42 |
[
0,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
34,
35
] | 66.666667 |
[
24,
27,
30,
31,
33
] | 13.888889 | false | 78.838951 | 36 | 9 | 86.111111 | 1 |
def _parse_block(
self, parser: "Parser", allow_pluralize: bool
) -> t.Tuple[t.List[str], str]:
referenced = []
buf = []
while True:
if parser.stream.current.type == "data":
buf.append(parser.stream.current.value.replace("%", "%%"))
next(parser.stream)
elif parser.stream.current.type == "variable_begin":
next(parser.stream)
name = parser.stream.expect("name").value
referenced.append(name)
buf.append(f"%({name})s")
parser.stream.expect("variable_end")
elif parser.stream.current.type == "block_begin":
next(parser.stream)
if parser.stream.current.test("name:endtrans"):
break
elif parser.stream.current.test("name:pluralize"):
if allow_pluralize:
break
parser.fail(
"a translatable section can have only one pluralize section"
)
parser.fail(
"control structures in translatable sections are not allowed"
)
elif parser.stream.eos:
parser.fail("unclosed translation block")
else:
raise RuntimeError("internal parser error")
return referenced, concat(buf)
| 27,629 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
InternationalizationExtension._make_node
|
(
self,
singular: str,
plural: t.Optional[str],
context: t.Optional[str],
variables: t.Dict[str, nodes.Expr],
plural_expr: t.Optional[nodes.Expr],
vars_referenced: bool,
num_called_num: bool,
)
|
return nodes.Output([node])
|
Generates a useful node from the data provided.
|
Generates a useful node from the data provided.
| 516 | 576 |
def _make_node(
self,
singular: str,
plural: t.Optional[str],
context: t.Optional[str],
variables: t.Dict[str, nodes.Expr],
plural_expr: t.Optional[nodes.Expr],
vars_referenced: bool,
num_called_num: bool,
) -> nodes.Output:
"""Generates a useful node from the data provided."""
newstyle = self.environment.newstyle_gettext # type: ignore
node: nodes.Expr
# no variables referenced? no need to escape for old style
# gettext invocations only if there are vars.
if not vars_referenced and not newstyle:
singular = singular.replace("%%", "%")
if plural:
plural = plural.replace("%%", "%")
func_name = "gettext"
func_args: t.List[nodes.Expr] = [nodes.Const(singular)]
if context is not None:
func_args.insert(0, nodes.Const(context))
func_name = f"p{func_name}"
if plural_expr is not None:
func_name = f"n{func_name}"
func_args.extend((nodes.Const(plural), plural_expr))
node = nodes.Call(nodes.Name(func_name, "load"), func_args, [], None, None)
# in case newstyle gettext is used, the method is powerful
# enough to handle the variable expansion and autoescape
# handling itself
if newstyle:
for key, value in variables.items():
# the function adds that later anyways in case num was
# called num, so just skip it.
if num_called_num and key == "num":
continue
node.kwargs.append(nodes.Keyword(key, value))
# otherwise do that here
else:
# mark the return value as safe if we are in an
# environment with autoescaping turned on
node = nodes.MarkSafeIfAutoescape(node)
if variables:
node = nodes.Mod(
node,
nodes.Dict(
[
nodes.Pair(nodes.Const(key), value)
for key, value in variables.items()
]
),
)
return nodes.Output([node])
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L516-L576
| 42 |
[
0,
10,
11,
12,
13,
14,
15,
16,
17,
18,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60
] | 83.606557 |
[
19
] | 1.639344 | false | 78.838951 | 61 | 12 | 98.360656 | 1 |
def _make_node(
self,
singular: str,
plural: t.Optional[str],
context: t.Optional[str],
variables: t.Dict[str, nodes.Expr],
plural_expr: t.Optional[nodes.Expr],
vars_referenced: bool,
num_called_num: bool,
) -> nodes.Output:
newstyle = self.environment.newstyle_gettext # type: ignore
node: nodes.Expr
# no variables referenced? no need to escape for old style
# gettext invocations only if there are vars.
if not vars_referenced and not newstyle:
singular = singular.replace("%%", "%")
if plural:
plural = plural.replace("%%", "%")
func_name = "gettext"
func_args: t.List[nodes.Expr] = [nodes.Const(singular)]
if context is not None:
func_args.insert(0, nodes.Const(context))
func_name = f"p{func_name}"
if plural_expr is not None:
func_name = f"n{func_name}"
func_args.extend((nodes.Const(plural), plural_expr))
node = nodes.Call(nodes.Name(func_name, "load"), func_args, [], None, None)
# in case newstyle gettext is used, the method is powerful
# enough to handle the variable expansion and autoescape
# handling itself
if newstyle:
for key, value in variables.items():
# the function adds that later anyways in case num was
# called num, so just skip it.
if num_called_num and key == "num":
continue
node.kwargs.append(nodes.Keyword(key, value))
# otherwise do that here
else:
# mark the return value as safe if we are in an
# environment with autoescaping turned on
node = nodes.MarkSafeIfAutoescape(node)
if variables:
node = nodes.Mod(
node,
nodes.Dict(
[
nodes.Pair(nodes.Const(key), value)
for key, value in variables.items()
]
),
)
return nodes.Output([node])
| 27,630 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
ExprStmtExtension.parse
|
(self, parser: "Parser")
|
return node
| 586 | 589 |
def parse(self, parser: "Parser") -> nodes.ExprStmt:
node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
node.node = parser.parse_tuple()
return node
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L586-L589
| 42 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 78.838951 | 4 | 1 | 100 | 0 |
def parse(self, parser: "Parser") -> nodes.ExprStmt:
node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
node.node = parser.parse_tuple()
return node
| 27,631 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
LoopControlExtension.parse
|
(self, parser: "Parser")
|
return nodes.Continue(lineno=token.lineno)
| 597 | 601 |
def parse(self, parser: "Parser") -> t.Union[nodes.Break, nodes.Continue]:
token = next(parser.stream)
if token.value == "break":
return nodes.Break(lineno=token.lineno)
return nodes.Continue(lineno=token.lineno)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L597-L601
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 78.838951 | 5 | 2 | 100 | 0 |
def parse(self, parser: "Parser") -> t.Union[nodes.Break, nodes.Continue]:
token = next(parser.stream)
if token.value == "break":
return nodes.Break(lineno=token.lineno)
return nodes.Continue(lineno=token.lineno)
| 27,632 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
DebugExtension.parse
|
(self, parser: "Parser")
|
return nodes.Output([result], lineno=lineno)
| 627 | 631 |
def parse(self, parser: "Parser") -> nodes.Output:
lineno = parser.stream.expect("name:debug").lineno
context = nodes.ContextReference()
result = self.call_method("_render", [context], lineno=lineno)
return nodes.Output([result], lineno=lineno)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L627-L631
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 78.838951 | 5 | 1 | 100 | 0 |
def parse(self, parser: "Parser") -> nodes.Output:
lineno = parser.stream.expect("name:debug").lineno
context = nodes.ContextReference()
result = self.call_method("_render", [context], lineno=lineno)
return nodes.Output([result], lineno=lineno)
| 27,633 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
DebugExtension._render
|
(self, context: Context)
|
return pprint.pformat(result, depth=3, compact=True)
| 633 | 641 |
def _render(self, context: Context) -> str:
result = {
"context": context.get_all(),
"filters": sorted(self.environment.filters.keys()),
"tests": sorted(self.environment.tests.keys()),
}
# Set the depth since the intent is to show the top few names.
return pprint.pformat(result, depth=3, compact=True)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L633-L641
| 42 |
[
0,
1,
7,
8
] | 44.444444 |
[] | 0 | false | 78.838951 | 9 | 1 | 100 | 0 |
def _render(self, context: Context) -> str:
result = {
"context": context.get_all(),
"filters": sorted(self.environment.filters.keys()),
"tests": sorted(self.environment.tests.keys()),
}
# Set the depth since the intent is to show the top few names.
return pprint.pformat(result, depth=3, compact=True)
| 27,634 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
_CommentFinder.__init__
|
(
self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str]
)
| 730 | 736 |
def __init__(
self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str]
) -> None:
self.tokens = tokens
self.comment_tags = comment_tags
self.offset = 0
self.last_lineno = 0
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L730-L736
| 42 |
[
0,
3,
4,
5,
6
] | 71.428571 |
[] | 0 | false | 78.838951 | 7 | 1 | 100 | 0 |
def __init__(
self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str]
) -> None:
self.tokens = tokens
self.comment_tags = comment_tags
self.offset = 0
self.last_lineno = 0
| 27,635 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
_CommentFinder.find_backwards
|
(self, offset: int)
| 738 | 752 |
def find_backwards(self, offset: int) -> t.List[str]:
try:
for _, token_type, token_value in reversed(
self.tokens[self.offset : offset]
):
if token_type in ("comment", "linecomment"):
try:
prefix, comment = token_value.split(None, 1)
except ValueError:
continue
if prefix in self.comment_tags:
return [comment.rstrip()]
return []
finally:
self.offset = offset
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L738-L752
| 42 |
[
0,
1,
2,
5,
6,
7,
10,
11,
14
] | 60 |
[
8,
9,
12
] | 20 | false | 78.838951 | 15 | 5 | 80 | 0 |
def find_backwards(self, offset: int) -> t.List[str]:
try:
for _, token_type, token_value in reversed(
self.tokens[self.offset : offset]
):
if token_type in ("comment", "linecomment"):
try:
prefix, comment = token_value.split(None, 1)
except ValueError:
continue
if prefix in self.comment_tags:
return [comment.rstrip()]
return []
finally:
self.offset = offset
| 27,636 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/ext.py
|
_CommentFinder.find_comments
|
(self, lineno: int)
|
return self.find_backwards(len(self.tokens))
| 754 | 760 |
def find_comments(self, lineno: int) -> t.List[str]:
if not self.comment_tags or self.last_lineno > lineno:
return []
for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):
if token_lineno > lineno:
return self.find_backwards(self.offset + idx)
return self.find_backwards(len(self.tokens))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/ext.py#L754-L760
| 42 |
[
0,
1,
2,
3,
4,
5,
6
] | 100 |
[] | 0 | true | 78.838951 | 7 | 5 | 100 | 0 |
def find_comments(self, lineno: int) -> t.List[str]:
if not self.comment_tags or self.last_lineno > lineno:
return []
for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):
if token_lineno > lineno:
return self.find_backwards(self.offset + idx)
return self.find_backwards(len(self.tokens))
| 27,637 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/exceptions.py
|
TemplateError.__init__
|
(self, message: t.Optional[str] = None)
| 10 | 11 |
def __init__(self, message: t.Optional[str] = None) -> None:
super().__init__(message)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/exceptions.py#L10-L11
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 89.285714 | 2 | 1 | 100 | 0 |
def __init__(self, message: t.Optional[str] = None) -> None:
super().__init__(message)
| 27,638 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/exceptions.py
|
TemplateError.message
|
(self)
|
return self.args[0] if self.args else None
| 14 | 15 |
def message(self) -> t.Optional[str]:
return self.args[0] if self.args else None
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/exceptions.py#L14-L15
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 89.285714 | 2 | 1 | 100 | 0 |
def message(self) -> t.Optional[str]:
return self.args[0] if self.args else None
| 27,639 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/exceptions.py
|
TemplateNotFound.__init__
|
(
self,
name: t.Optional[t.Union[str, "Undefined"]],
message: t.Optional[str] = None,
)
| 30 | 47 |
def __init__(
self,
name: t.Optional[t.Union[str, "Undefined"]],
message: t.Optional[str] = None,
) -> None:
IOError.__init__(self, name)
if message is None:
from .runtime import Undefined
if isinstance(name, Undefined):
name._fail_with_undefined_error()
message = name
self.message = message
self.name = name
self.templates = [name]
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/exceptions.py#L30-L47
| 42 |
[
0,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17
] | 77.777778 |
[] | 0 | false | 89.285714 | 18 | 3 | 100 | 0 |
def __init__(
self,
name: t.Optional[t.Union[str, "Undefined"]],
message: t.Optional[str] = None,
) -> None:
IOError.__init__(self, name)
if message is None:
from .runtime import Undefined
if isinstance(name, Undefined):
name._fail_with_undefined_error()
message = name
self.message = message
self.name = name
self.templates = [name]
| 27,640 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/exceptions.py
|
TemplateNotFound.__str__
|
(self)
|
return str(self.message)
| 49 | 50 |
def __str__(self) -> str:
return str(self.message)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/exceptions.py#L49-L50
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 89.285714 | 2 | 1 | 100 | 0 |
def __str__(self) -> str:
return str(self.message)
| 27,641 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/exceptions.py
|
TemplatesNotFound.__init__
|
(
self,
names: t.Sequence[t.Union[str, "Undefined"]] = (),
message: t.Optional[str] = None,
)
| 65 | 85 |
def __init__(
self,
names: t.Sequence[t.Union[str, "Undefined"]] = (),
message: t.Optional[str] = None,
) -> None:
if message is None:
from .runtime import Undefined
parts = []
for name in names:
if isinstance(name, Undefined):
parts.append(name._undefined_message)
else:
parts.append(name)
parts_str = ", ".join(map(str, parts))
message = f"none of the templates given were found: {parts_str}"
super().__init__(names[-1] if names else None, message)
self.templates = list(names)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/exceptions.py#L65-L85
| 42 |
[
0,
5,
6,
7,
8,
9,
10,
11,
12,
14,
15,
16,
17,
18,
19,
20
] | 76.190476 |
[] | 0 | false | 89.285714 | 21 | 4 | 100 | 0 |
def __init__(
self,
names: t.Sequence[t.Union[str, "Undefined"]] = (),
message: t.Optional[str] = None,
) -> None:
if message is None:
from .runtime import Undefined
parts = []
for name in names:
if isinstance(name, Undefined):
parts.append(name._undefined_message)
else:
parts.append(name)
parts_str = ", ".join(map(str, parts))
message = f"none of the templates given were found: {parts_str}"
super().__init__(names[-1] if names else None, message)
self.templates = list(names)
| 27,642 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/exceptions.py
|
TemplateSyntaxError.__init__
|
(
self,
message: str,
lineno: int,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
)
| 91 | 106 |
def __init__(
self,
message: str,
lineno: int,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> None:
super().__init__(message)
self.lineno = lineno
self.name = name
self.filename = filename
self.source: t.Optional[str] = None
# this is set to True if the debug.translate_syntax_error
# function translated the syntax error into a new traceback
self.translated = False
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/exceptions.py#L91-L106
| 42 |
[
0,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 62.5 |
[] | 0 | false | 89.285714 | 16 | 1 | 100 | 0 |
def __init__(
self,
message: str,
lineno: int,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> None:
super().__init__(message)
self.lineno = lineno
self.name = name
self.filename = filename
self.source: t.Optional[str] = None
# this is set to True if the debug.translate_syntax_error
# function translated the syntax error into a new traceback
self.translated = False
| 27,643 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/exceptions.py
|
TemplateSyntaxError.__str__
|
(self)
|
return "\n".join(lines)
| 108 | 129 |
def __str__(self) -> str:
# for translated errors we only return the message
if self.translated:
return t.cast(str, self.message)
# otherwise attach some stuff
location = f"line {self.lineno}"
name = self.filename or self.name
if name:
location = f'File "{name}", {location}'
lines = [t.cast(str, self.message), " " + location]
# if the source is set, add the line to the output
if self.source is not None:
try:
line = self.source.splitlines()[self.lineno - 1]
except IndexError:
pass
else:
lines.append(" " + line.strip())
return "\n".join(lines)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/exceptions.py#L108-L129
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
20,
21
] | 72.727273 |
[
14,
15,
16,
17,
19
] | 22.727273 | false | 89.285714 | 22 | 6 | 77.272727 | 0 |
def __str__(self) -> str:
# for translated errors we only return the message
if self.translated:
return t.cast(str, self.message)
# otherwise attach some stuff
location = f"line {self.lineno}"
name = self.filename or self.name
if name:
location = f'File "{name}", {location}'
lines = [t.cast(str, self.message), " " + location]
# if the source is set, add the line to the output
if self.source is not None:
try:
line = self.source.splitlines()[self.lineno - 1]
except IndexError:
pass
else:
lines.append(" " + line.strip())
return "\n".join(lines)
| 27,644 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/exceptions.py
|
TemplateSyntaxError.__reduce__
|
(self)
|
return self.__class__, (self.message, self.lineno, self.name, self.filename)
| 131 | 136 |
def __reduce__(self): # type: ignore
# https://bugs.python.org/issue1692335 Exceptions that take
# multiple required arguments have problems with pickling.
# Without this, raises TypeError: __init__() missing 1 required
# positional argument: 'lineno'
return self.__class__, (self.message, self.lineno, self.name, self.filename)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/exceptions.py#L131-L136
| 42 |
[
0,
1,
2,
3,
4,
5
] | 100 |
[] | 0 | true | 89.285714 | 6 | 1 | 100 | 0 |
def __reduce__(self): # type: ignore
# https://bugs.python.org/issue1692335 Exceptions that take
# multiple required arguments have problems with pickling.
# Without this, raises TypeError: __init__() missing 1 required
# positional argument: 'lineno'
return self.__class__, (self.message, self.lineno, self.name, self.filename)
| 27,645 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
inspect_format_method
|
(callable: t.Callable)
|
return None
| 83 | 94 |
def inspect_format_method(callable: t.Callable) -> t.Optional[str]:
if not isinstance(
callable, (types.MethodType, types.BuiltinMethodType)
) or callable.__name__ not in ("format", "format_map"):
return None
obj = callable.__self__
if isinstance(obj, str):
return obj
return None
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L83-L94
| 42 |
[
0,
1,
4,
5,
6,
7,
8,
9,
10
] | 75 |
[
11
] | 8.333333 | false | 70.192308 | 12 | 4 | 91.666667 | 0 |
def inspect_format_method(callable: t.Callable) -> t.Optional[str]:
if not isinstance(
callable, (types.MethodType, types.BuiltinMethodType)
) or callable.__name__ not in ("format", "format_map"):
return None
obj = callable.__self__
if isinstance(obj, str):
return obj
return None
| 27,646 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
safe_range
|
(*args: int)
|
return rng
|
A range that can't generate ranges with a length of more than
MAX_RANGE items.
|
A range that can't generate ranges with a length of more than
MAX_RANGE items.
| 97 | 109 |
def safe_range(*args: int) -> range:
"""A range that can't generate ranges with a length of more than
MAX_RANGE items.
"""
rng = range(*args)
if len(rng) > MAX_RANGE:
raise OverflowError(
"Range too big. The sandbox blocks ranges larger than"
f" MAX_RANGE ({MAX_RANGE})."
)
return rng
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L97-L109
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 92.307692 |
[
12
] | 7.692308 | false | 70.192308 | 13 | 2 | 92.307692 | 2 |
def safe_range(*args: int) -> range:
rng = range(*args)
if len(rng) > MAX_RANGE:
raise OverflowError(
"Range too big. The sandbox blocks ranges larger than"
f" MAX_RANGE ({MAX_RANGE})."
)
return rng
| 27,647 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
unsafe
|
(f: F)
|
return f
|
Marks a function or method as unsafe.
.. code-block: python
@unsafe
def delete(self):
pass
|
Marks a function or method as unsafe.
| 112 | 122 |
def unsafe(f: F) -> F:
"""Marks a function or method as unsafe.
.. code-block: python
@unsafe
def delete(self):
pass
"""
f.unsafe_callable = True # type: ignore
return f
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L112-L122
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 100 |
[] | 0 | true | 70.192308 | 11 | 1 | 100 | 7 |
def unsafe(f: F) -> F:
f.unsafe_callable = True # type: ignore
return f
| 27,648 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
is_internal_attribute
|
(obj: t.Any, attr: str)
|
return attr.startswith("__")
|
Test if the attribute given is an internal python attribute. For
example this function returns `True` for the `func_code` attribute of
python objects. This is useful if the environment method
:meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
>>> from jinja2.sandbox import is_internal_attribute
>>> is_internal_attribute(str, "mro")
True
>>> is_internal_attribute(str, "upper")
False
|
Test if the attribute given is an internal python attribute. For
example this function returns `True` for the `func_code` attribute of
python objects. This is useful if the environment method
:meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
| 125 | 159 |
def is_internal_attribute(obj: t.Any, attr: str) -> bool:
"""Test if the attribute given is an internal python attribute. For
example this function returns `True` for the `func_code` attribute of
python objects. This is useful if the environment method
:meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
>>> from jinja2.sandbox import is_internal_attribute
>>> is_internal_attribute(str, "mro")
True
>>> is_internal_attribute(str, "upper")
False
"""
if isinstance(obj, types.FunctionType):
if attr in UNSAFE_FUNCTION_ATTRIBUTES:
return True
elif isinstance(obj, types.MethodType):
if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:
return True
elif isinstance(obj, type):
if attr == "mro":
return True
elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
return True
elif isinstance(obj, types.GeneratorType):
if attr in UNSAFE_GENERATOR_ATTRIBUTES:
return True
elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):
if attr in UNSAFE_COROUTINE_ATTRIBUTES:
return True
elif hasattr(types, "AsyncGeneratorType") and isinstance(
obj, types.AsyncGeneratorType
):
if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
return True
return attr.startswith("__")
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L125-L159
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
15,
18,
21,
23,
26,
29,
30,
31,
34
] | 62.857143 |
[
13,
14,
16,
17,
19,
20,
22,
24,
25,
27,
28,
32,
33
] | 37.142857 | false | 70.192308 | 35 | 17 | 62.857143 | 10 |
def is_internal_attribute(obj: t.Any, attr: str) -> bool:
if isinstance(obj, types.FunctionType):
if attr in UNSAFE_FUNCTION_ATTRIBUTES:
return True
elif isinstance(obj, types.MethodType):
if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:
return True
elif isinstance(obj, type):
if attr == "mro":
return True
elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
return True
elif isinstance(obj, types.GeneratorType):
if attr in UNSAFE_GENERATOR_ATTRIBUTES:
return True
elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):
if attr in UNSAFE_COROUTINE_ATTRIBUTES:
return True
elif hasattr(types, "AsyncGeneratorType") and isinstance(
obj, types.AsyncGeneratorType
):
if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
return True
return attr.startswith("__")
| 27,649 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
modifies_known_mutable
|
(obj: t.Any, attr: str)
|
return False
|
This function checks if an attribute on a builtin mutable object
(list, dict, set or deque) or the corresponding ABCs would modify it
if called.
>>> modifies_known_mutable({}, "clear")
True
>>> modifies_known_mutable({}, "keys")
False
>>> modifies_known_mutable([], "append")
True
>>> modifies_known_mutable([], "index")
False
If called with an unsupported object, ``False`` is returned.
>>> modifies_known_mutable("foo", "upper")
False
|
This function checks if an attribute on a builtin mutable object
(list, dict, set or deque) or the corresponding ABCs would modify it
if called.
| 162 | 184 |
def modifies_known_mutable(obj: t.Any, attr: str) -> bool:
"""This function checks if an attribute on a builtin mutable object
(list, dict, set or deque) or the corresponding ABCs would modify it
if called.
>>> modifies_known_mutable({}, "clear")
True
>>> modifies_known_mutable({}, "keys")
False
>>> modifies_known_mutable([], "append")
True
>>> modifies_known_mutable([], "index")
False
If called with an unsupported object, ``False`` is returned.
>>> modifies_known_mutable("foo", "upper")
False
"""
for typespec, unsafe in _mutable_spec:
if isinstance(obj, typespec):
return attr in unsafe
return False
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L162-L184
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21
] | 95.652174 |
[
22
] | 4.347826 | false | 70.192308 | 23 | 3 | 95.652174 | 17 |
def modifies_known_mutable(obj: t.Any, attr: str) -> bool:
for typespec, unsafe in _mutable_spec:
if isinstance(obj, typespec):
return attr in unsafe
return False
| 27,650 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.__init__
|
(self, *args: t.Any, **kwargs: t.Any)
| 252 | 256 |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.globals["range"] = safe_range
self.binop_table = self.default_binop_table.copy()
self.unop_table = self.default_unop_table.copy()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L252-L256
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 70.192308 | 5 | 1 | 100 | 0 |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
super().__init__(*args, **kwargs)
self.globals["range"] = safe_range
self.binop_table = self.default_binop_table.copy()
self.unop_table = self.default_unop_table.copy()
| 27,651 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.is_safe_attribute
|
(self, obj: t.Any, attr: str, value: t.Any)
|
return not (attr.startswith("_") or is_internal_attribute(obj, attr))
|
The sandboxed environment will call this method to check if the
attribute of an object is safe to access. Per default all attributes
starting with an underscore are considered private as well as the
special attributes of internal python objects as returned by the
:func:`is_internal_attribute` function.
|
The sandboxed environment will call this method to check if the
attribute of an object is safe to access. Per default all attributes
starting with an underscore are considered private as well as the
special attributes of internal python objects as returned by the
:func:`is_internal_attribute` function.
| 258 | 265 |
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:
"""The sandboxed environment will call this method to check if the
attribute of an object is safe to access. Per default all attributes
starting with an underscore are considered private as well as the
special attributes of internal python objects as returned by the
:func:`is_internal_attribute` function.
"""
return not (attr.startswith("_") or is_internal_attribute(obj, attr))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L258-L265
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 70.192308 | 8 | 2 | 100 | 5 |
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:
return not (attr.startswith("_") or is_internal_attribute(obj, attr))
| 27,652 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.is_safe_callable
|
(self, obj: t.Any)
|
return not (
getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)
)
|
Check if an object is safely callable. By default callables
are considered safe unless decorated with :func:`unsafe`.
This also recognizes the Django convention of setting
``func.alters_data = True``.
|
Check if an object is safely callable. By default callables
are considered safe unless decorated with :func:`unsafe`.
| 267 | 276 |
def is_safe_callable(self, obj: t.Any) -> bool:
"""Check if an object is safely callable. By default callables
are considered safe unless decorated with :func:`unsafe`.
This also recognizes the Django convention of setting
``func.alters_data = True``.
"""
return not (
getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L267-L276
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 |
[] | 0 | true | 70.192308 | 10 | 2 | 100 | 5 |
def is_safe_callable(self, obj: t.Any) -> bool:
return not (
getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)
)
| 27,653 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.call_binop
|
(
self, context: Context, operator: str, left: t.Any, right: t.Any
)
|
return self.binop_table[operator](left, right)
|
For intercepted binary operator calls (:meth:`intercepted_binops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
.. versionadded:: 2.6
|
For intercepted binary operator calls (:meth:`intercepted_binops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
| 278 | 287 |
def call_binop(
self, context: Context, operator: str, left: t.Any, right: t.Any
) -> t.Any:
"""For intercepted binary operator calls (:meth:`intercepted_binops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
.. versionadded:: 2.6
"""
return self.binop_table[operator](left, right)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L278-L287
| 42 |
[
0,
8,
9
] | 30 |
[] | 0 | false | 70.192308 | 10 | 1 | 100 | 5 |
def call_binop(
self, context: Context, operator: str, left: t.Any, right: t.Any
) -> t.Any:
return self.binop_table[operator](left, right)
| 27,654 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.call_unop
|
(self, context: Context, operator: str, arg: t.Any)
|
return self.unop_table[operator](arg)
|
For intercepted unary operator calls (:meth:`intercepted_unops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
.. versionadded:: 2.6
|
For intercepted unary operator calls (:meth:`intercepted_unops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
| 289 | 296 |
def call_unop(self, context: Context, operator: str, arg: t.Any) -> t.Any:
"""For intercepted unary operator calls (:meth:`intercepted_unops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
.. versionadded:: 2.6
"""
return self.unop_table[operator](arg)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L289-L296
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 70.192308 | 8 | 1 | 100 | 5 |
def call_unop(self, context: Context, operator: str, arg: t.Any) -> t.Any:
return self.unop_table[operator](arg)
| 27,655 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.getitem
|
(
self, obj: t.Any, argument: t.Union[str, t.Any]
)
|
return self.undefined(obj=obj, name=argument)
|
Subscribe an object from sandboxed code.
|
Subscribe an object from sandboxed code.
| 298 | 319 |
def getitem(
self, obj: t.Any, argument: t.Union[str, t.Any]
) -> t.Union[t.Any, Undefined]:
"""Subscribe an object from sandboxed code."""
try:
return obj[argument]
except (TypeError, LookupError):
if isinstance(argument, str):
try:
attr = str(argument)
except Exception:
pass
else:
try:
value = getattr(obj, attr)
except AttributeError:
pass
else:
if self.is_safe_attribute(obj, argument, value):
return value
return self.unsafe_undefined(obj, argument)
return self.undefined(obj=obj, name=argument)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L298-L319
| 42 |
[
0,
3,
4,
5
] | 18.181818 |
[
6,
7,
8,
9,
10,
11,
13,
14,
15,
16,
18,
19,
20,
21
] | 63.636364 | false | 70.192308 | 22 | 6 | 36.363636 | 1 |
def getitem(
self, obj: t.Any, argument: t.Union[str, t.Any]
) -> t.Union[t.Any, Undefined]:
try:
return obj[argument]
except (TypeError, LookupError):
if isinstance(argument, str):
try:
attr = str(argument)
except Exception:
pass
else:
try:
value = getattr(obj, attr)
except AttributeError:
pass
else:
if self.is_safe_attribute(obj, argument, value):
return value
return self.unsafe_undefined(obj, argument)
return self.undefined(obj=obj, name=argument)
| 27,656 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.getattr
|
(self, obj: t.Any, attribute: str)
|
return self.undefined(obj=obj, name=attribute)
|
Subscribe an object from sandboxed code and prefer the
attribute. The attribute passed *must* be a bytestring.
|
Subscribe an object from sandboxed code and prefer the
attribute. The attribute passed *must* be a bytestring.
| 321 | 336 |
def getattr(self, obj: t.Any, attribute: str) -> t.Union[t.Any, Undefined]:
"""Subscribe an object from sandboxed code and prefer the
attribute. The attribute passed *must* be a bytestring.
"""
try:
value = getattr(obj, attribute)
except AttributeError:
try:
return obj[attribute]
except (TypeError, LookupError):
pass
else:
if self.is_safe_attribute(obj, attribute, value):
return value
return self.unsafe_undefined(obj, attribute)
return self.undefined(obj=obj, name=attribute)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L321-L336
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 100 |
[] | 0 | true | 70.192308 | 16 | 4 | 100 | 2 |
def getattr(self, obj: t.Any, attribute: str) -> t.Union[t.Any, Undefined]:
try:
value = getattr(obj, attribute)
except AttributeError:
try:
return obj[attribute]
except (TypeError, LookupError):
pass
else:
if self.is_safe_attribute(obj, attribute, value):
return value
return self.unsafe_undefined(obj, attribute)
return self.undefined(obj=obj, name=attribute)
| 27,657 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.unsafe_undefined
|
(self, obj: t.Any, attribute: str)
|
return self.undefined(
f"access to attribute {attribute!r} of"
f" {type(obj).__name__!r} object is unsafe.",
name=attribute,
obj=obj,
exc=SecurityError,
)
|
Return an undefined object for unsafe attributes.
|
Return an undefined object for unsafe attributes.
| 338 | 346 |
def unsafe_undefined(self, obj: t.Any, attribute: str) -> Undefined:
"""Return an undefined object for unsafe attributes."""
return self.undefined(
f"access to attribute {attribute!r} of"
f" {type(obj).__name__!r} object is unsafe.",
name=attribute,
obj=obj,
exc=SecurityError,
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L338-L346
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 |
[] | 0 | true | 70.192308 | 9 | 1 | 100 | 1 |
def unsafe_undefined(self, obj: t.Any, attribute: str) -> Undefined:
return self.undefined(
f"access to attribute {attribute!r} of"
f" {type(obj).__name__!r} object is unsafe.",
name=attribute,
obj=obj,
exc=SecurityError,
)
| 27,658 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.format_string
|
(
self,
s: str,
args: t.Tuple[t.Any, ...],
kwargs: t.Dict[str, t.Any],
format_func: t.Optional[t.Callable] = None,
)
|
return type(s)(rv)
|
If a format call is detected, then this is routed through this
method so that our safety sandbox can be used for it.
|
If a format call is detected, then this is routed through this
method so that our safety sandbox can be used for it.
| 348 | 375 |
def format_string(
self,
s: str,
args: t.Tuple[t.Any, ...],
kwargs: t.Dict[str, t.Any],
format_func: t.Optional[t.Callable] = None,
) -> str:
"""If a format call is detected, then this is routed through this
method so that our safety sandbox can be used for it.
"""
formatter: SandboxedFormatter
if isinstance(s, Markup):
formatter = SandboxedEscapeFormatter(self, escape=s.escape)
else:
formatter = SandboxedFormatter(self)
if format_func is not None and format_func.__name__ == "format_map":
if len(args) != 1 or kwargs:
raise TypeError(
"format_map() takes exactly one argument"
f" {len(args) + (kwargs is not None)} given"
)
kwargs = args[0]
args = ()
rv = formatter.vformat(s, args, kwargs)
return type(s)(rv)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L348-L375
| 42 |
[
0,
11,
12,
14,
15,
16,
17,
22,
23,
24,
25,
26,
27
] | 46.428571 |
[
18
] | 3.571429 | false | 70.192308 | 28 | 6 | 96.428571 | 2 |
def format_string(
self,
s: str,
args: t.Tuple[t.Any, ...],
kwargs: t.Dict[str, t.Any],
format_func: t.Optional[t.Callable] = None,
) -> str:
formatter: SandboxedFormatter
if isinstance(s, Markup):
formatter = SandboxedEscapeFormatter(self, escape=s.escape)
else:
formatter = SandboxedFormatter(self)
if format_func is not None and format_func.__name__ == "format_map":
if len(args) != 1 or kwargs:
raise TypeError(
"format_map() takes exactly one argument"
f" {len(args) + (kwargs is not None)} given"
)
kwargs = args[0]
args = ()
rv = formatter.vformat(s, args, kwargs)
return type(s)(rv)
| 27,659 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedEnvironment.call
|
(
__self, # noqa: B902
__context: Context,
__obj: t.Any,
*args: t.Any,
**kwargs: t.Any,
)
|
return __context.call(__obj, *args, **kwargs)
|
Call an object from sandboxed code.
|
Call an object from sandboxed code.
| 377 | 393 |
def call(
__self, # noqa: B902
__context: Context,
__obj: t.Any,
*args: t.Any,
**kwargs: t.Any,
) -> t.Any:
"""Call an object from sandboxed code."""
fmt = inspect_format_method(__obj)
if fmt is not None:
return __self.format_string(fmt, args, kwargs, __obj)
# the double prefixes are to avoid double keyword argument
# errors when proxying the call.
if not __self.is_safe_callable(__obj):
raise SecurityError(f"{__obj!r} is not safely callable")
return __context.call(__obj, *args, **kwargs)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L377-L393
| 42 |
[
0,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16
] | 64.705882 |
[] | 0 | false | 70.192308 | 17 | 3 | 100 | 1 |
def call(
__self, # noqa: B902
__context: Context,
__obj: t.Any,
*args: t.Any,
**kwargs: t.Any,
) -> t.Any:
fmt = inspect_format_method(__obj)
if fmt is not None:
return __self.format_string(fmt, args, kwargs, __obj)
# the double prefixes are to avoid double keyword argument
# errors when proxying the call.
if not __self.is_safe_callable(__obj):
raise SecurityError(f"{__obj!r} is not safely callable")
return __context.call(__obj, *args, **kwargs)
| 27,660 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.