tstr 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tstr/__init__.py +32 -0
- tstr/_compat.py +141 -0
- tstr/_html.py +55 -0
- tstr/_sqlite.py +37 -0
- tstr/_template.py +15 -0
- tstr/_template.pyi +70 -0
- tstr/_utils.py +385 -0
- tstr-0.1.0.dist-info/METADATA +146 -0
- tstr-0.1.0.dist-info/RECORD +11 -0
- tstr-0.1.0.dist-info/WHEEL +4 -0
- tstr-0.1.0.dist-info/licenses/LICENSE +202 -0
tstr/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from ._template import TEMPLATE_STRING_SUPPORTED, Conversion, Interpolation, Template
|
|
2
|
+
from ._utils import (
|
|
3
|
+
TemplateGenerationError,
|
|
4
|
+
bind,
|
|
5
|
+
binder,
|
|
6
|
+
convert,
|
|
7
|
+
converter,
|
|
8
|
+
f,
|
|
9
|
+
generate_template,
|
|
10
|
+
normalize,
|
|
11
|
+
normalize_str,
|
|
12
|
+
render,
|
|
13
|
+
t,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"bind",
|
|
18
|
+
"binder",
|
|
19
|
+
"f",
|
|
20
|
+
"render",
|
|
21
|
+
"convert",
|
|
22
|
+
"converter",
|
|
23
|
+
"normalize",
|
|
24
|
+
"normalize_str",
|
|
25
|
+
"Template",
|
|
26
|
+
"Interpolation",
|
|
27
|
+
"Conversion",
|
|
28
|
+
"generate_template",
|
|
29
|
+
"t",
|
|
30
|
+
"TemplateGenerationError",
|
|
31
|
+
"TEMPLATE_STRING_SUPPORTED",
|
|
32
|
+
]
|
tstr/_compat.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import typing
|
|
4
|
+
from itertools import zip_longest
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Template:
|
|
8
|
+
__strings: tuple[str, ...]
|
|
9
|
+
__interpolations: tuple[Interpolation, ...]
|
|
10
|
+
|
|
11
|
+
@property
|
|
12
|
+
def strings(self) -> tuple[str, ...]:
|
|
13
|
+
"""
|
|
14
|
+
A non-empty tuple of the string parts of the template,
|
|
15
|
+
with N+1 items, where N is the number of interpolations
|
|
16
|
+
in the template.
|
|
17
|
+
"""
|
|
18
|
+
return self.__strings
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def interpolations(self) -> tuple[Interpolation, ...]:
|
|
22
|
+
"""
|
|
23
|
+
A tuple of the interpolation parts of the template.
|
|
24
|
+
This will be an empty tuple if there are no interpolations.
|
|
25
|
+
"""
|
|
26
|
+
return self.__interpolations
|
|
27
|
+
|
|
28
|
+
def __init__(self, *args: str | Interpolation) -> None:
|
|
29
|
+
"""
|
|
30
|
+
Create a new Template instance.
|
|
31
|
+
|
|
32
|
+
Arguments can be provided in any order.
|
|
33
|
+
"""
|
|
34
|
+
str_last_added = False
|
|
35
|
+
strings = []
|
|
36
|
+
interpolations = []
|
|
37
|
+
for item in args:
|
|
38
|
+
if isinstance(item, str):
|
|
39
|
+
if str_last_added:
|
|
40
|
+
strings[-1] += item
|
|
41
|
+
else:
|
|
42
|
+
strings.append(item)
|
|
43
|
+
str_last_added = True
|
|
44
|
+
elif isinstance(item, Interpolation):
|
|
45
|
+
if not str_last_added:
|
|
46
|
+
strings.append("")
|
|
47
|
+
interpolations.append(item)
|
|
48
|
+
str_last_added = False
|
|
49
|
+
else:
|
|
50
|
+
raise TypeError(
|
|
51
|
+
f"Template.__new__ *args need to be of type 'str' or 'Interpolation', got {type(item).__name__}"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
if len(strings) == len(interpolations):
|
|
55
|
+
strings.append("")
|
|
56
|
+
|
|
57
|
+
self.__strings = tuple(strings)
|
|
58
|
+
self.__interpolations = tuple(interpolations)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def values(self) -> tuple[object, ...]:
|
|
62
|
+
"""
|
|
63
|
+
Return a tuple of the `value` attributes of each Interpolation
|
|
64
|
+
in the template.
|
|
65
|
+
This will be an empty tuple if there are no interpolations.
|
|
66
|
+
"""
|
|
67
|
+
return tuple(interpolation.value for interpolation in self.interpolations)
|
|
68
|
+
|
|
69
|
+
def __iter__(self) -> typing.Iterator[str | Interpolation]:
|
|
70
|
+
"""
|
|
71
|
+
Iterate over the string parts and interpolations in the template.
|
|
72
|
+
|
|
73
|
+
These may appear in any order. Empty strings will not be included.
|
|
74
|
+
"""
|
|
75
|
+
for string, interpolation in zip_longest(self.strings, self.interpolations):
|
|
76
|
+
if string:
|
|
77
|
+
yield string
|
|
78
|
+
if interpolation:
|
|
79
|
+
yield interpolation
|
|
80
|
+
|
|
81
|
+
def __add__(self, other: str | Template) -> Template:
|
|
82
|
+
if isinstance(other, str):
|
|
83
|
+
return Template(*self, other)
|
|
84
|
+
elif isinstance(other, Template):
|
|
85
|
+
return Template(*self, *other)
|
|
86
|
+
else:
|
|
87
|
+
return NotImplemented
|
|
88
|
+
|
|
89
|
+
def __radd__(self, other: str | Template) -> Template:
|
|
90
|
+
if isinstance(other, str):
|
|
91
|
+
return Template(other, *self)
|
|
92
|
+
elif isinstance(other, Template):
|
|
93
|
+
return Template(*other, *self)
|
|
94
|
+
else:
|
|
95
|
+
return NotImplemented
|
|
96
|
+
|
|
97
|
+
def __repr__(self) -> str:
|
|
98
|
+
return f"Template(strings={self.strings!r}, interpolations={self.interpolations!r})"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Interpolation:
|
|
102
|
+
__match_args__ = ("value", "expression", "conversion", "format_spec")
|
|
103
|
+
__value: object
|
|
104
|
+
__expression: str
|
|
105
|
+
__conversion: typing.Literal["a", "r", "s"] | None
|
|
106
|
+
__format_spec: str
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def value(self) -> object:
|
|
110
|
+
return self.__value
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def expression(self) -> str:
|
|
114
|
+
return self.__expression
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def conversion(self) -> typing.Literal["a", "r", "s"] | None:
|
|
118
|
+
return self.__conversion
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def format_spec(self) -> str:
|
|
122
|
+
return self.__format_spec
|
|
123
|
+
|
|
124
|
+
def __init__(
|
|
125
|
+
self,
|
|
126
|
+
value: object,
|
|
127
|
+
expression: str,
|
|
128
|
+
conversion: typing.Literal["a", "r", "s"] | None = None,
|
|
129
|
+
format_spec: str = "",
|
|
130
|
+
) -> None:
|
|
131
|
+
self.__value = value
|
|
132
|
+
if conversion not in (None, "a", "r", "s"):
|
|
133
|
+
raise ValueError(
|
|
134
|
+
f"Interpolation() argument 'conversion' must be one of 's', 'a' or 'r'"
|
|
135
|
+
)
|
|
136
|
+
self.__expression = expression
|
|
137
|
+
self.__conversion = conversion
|
|
138
|
+
self.__format_spec = format_spec
|
|
139
|
+
|
|
140
|
+
def __repr__(self) -> str:
|
|
141
|
+
return f"Interpolation({self.value!r}, {self.expression!r}, {self.conversion!r}, {self.format_spec!r})"
|
tstr/_html.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from html import escape
|
|
2
|
+
|
|
3
|
+
from tstr import Interpolation, binder
|
|
4
|
+
|
|
5
|
+
__all__ = ["html_safe"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@binder
|
|
9
|
+
def html_safe(interpolation: Interpolation) -> str:
|
|
10
|
+
"""
|
|
11
|
+
Escapes HTML special characters in interpolations for safe HTML rendering.
|
|
12
|
+
|
|
13
|
+
This function helps prevent XSS attacks by escaping any HTML special
|
|
14
|
+
characters in interpolated values. It's specifically designed for safely
|
|
15
|
+
including user-provided content in HTML templates.
|
|
16
|
+
|
|
17
|
+
Special behavior:
|
|
18
|
+
- When the 'r' conversion is used (e.g., {content!r}), the value is treated as
|
|
19
|
+
raw HTML and will NOT be escaped. This allows for intentional inclusion of
|
|
20
|
+
HTML markup when needed.
|
|
21
|
+
- Other conversion specifiers ('s', 'a') are not allowed to avoid confusion.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
template (Template): The template to process.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
str: The HTML-escaped string, or unescaped if using the 'r' conversion.
|
|
28
|
+
|
|
29
|
+
Raises:
|
|
30
|
+
ValueError: If any conversion specifier other than 'r' is used.
|
|
31
|
+
|
|
32
|
+
Example:
|
|
33
|
+
```python
|
|
34
|
+
from tstr._html import html_safe
|
|
35
|
+
|
|
36
|
+
# Unsafe user input that will be safely escaped
|
|
37
|
+
username = "<script>alert('XSS')</script>"
|
|
38
|
+
template = t"<div>Welcome, {username}!</div>"
|
|
39
|
+
result = html_safe(template)
|
|
40
|
+
assert result == "<div>Welcome, <script>alert('XSS')</script>!</div>"
|
|
41
|
+
|
|
42
|
+
# Intentionally including raw HTML with the 'r' conversion
|
|
43
|
+
title_html = "<b>Important Notice</b>"
|
|
44
|
+
template = t"<h1>{title_html!r}</h1>"
|
|
45
|
+
result = html_safe(template)
|
|
46
|
+
assert result == "<h1><b>Important Notice</b></h1>"
|
|
47
|
+
```
|
|
48
|
+
"""
|
|
49
|
+
formatted = format(interpolation.value, interpolation.format_spec)
|
|
50
|
+
if interpolation.conversion == "r":
|
|
51
|
+
return formatted
|
|
52
|
+
elif interpolation.conversion:
|
|
53
|
+
raise ValueError("Conversion other than 'r' is prohibited.")
|
|
54
|
+
else:
|
|
55
|
+
return escape(formatted)
|
tstr/_sqlite.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import sqlite3
|
|
2
|
+
|
|
3
|
+
from tstr import Template, normalize
|
|
4
|
+
|
|
5
|
+
__all__ = ["execute"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def execute(cursor: sqlite3.Cursor, sql: Template) -> sqlite3.Cursor:
|
|
9
|
+
"""
|
|
10
|
+
Executes SQL safely using template strings to prevent SQL injection.
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
# XXX: Using f-string (vulnerable to SQL injection):
|
|
14
|
+
cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'")
|
|
15
|
+
|
|
16
|
+
# Using template string (safe):
|
|
17
|
+
execute(cursor, t"SELECT * FROM users WHERE name = {user_input}")
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
cursor (sqlite3.Cursor): The SQLite cursor to execute the SQL statement.
|
|
22
|
+
sql (Template): The SQL statement as a template string.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
sqlite3.Cursor: The cursor after executing the SQL statement.
|
|
26
|
+
"""
|
|
27
|
+
assert isinstance(sql, Template), "SQL statement must be a template string."
|
|
28
|
+
|
|
29
|
+
query = []
|
|
30
|
+
params = []
|
|
31
|
+
for item in sql:
|
|
32
|
+
if isinstance(item, str):
|
|
33
|
+
query.append(item)
|
|
34
|
+
else:
|
|
35
|
+
query.append("?")
|
|
36
|
+
params.append(normalize(item))
|
|
37
|
+
return cursor.execute("".join(query), params)
|
tstr/_template.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import typing
|
|
2
|
+
|
|
3
|
+
__all__ = ["Template", "Interpolation", "Conversion", "TEMPLATE_STRING_SUPPORTED"]
|
|
4
|
+
|
|
5
|
+
type Conversion = typing.Literal["a", "r", "s"]
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from string.templatelib import Interpolation, Template # type: ignore
|
|
9
|
+
|
|
10
|
+
TEMPLATE_STRING_SUPPORTED = True
|
|
11
|
+
except Exception:
|
|
12
|
+
# Fallback to compatible implementation if template strings are not supported
|
|
13
|
+
from ._compat import Interpolation, Template
|
|
14
|
+
|
|
15
|
+
TEMPLATE_STRING_SUPPORTED = False
|
tstr/_template.pyi
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
import typing
|
|
5
|
+
|
|
6
|
+
__all__ = ["Template", "Interpolation", "Conversion"]
|
|
7
|
+
|
|
8
|
+
type Conversion = typing.Literal["a", "r", "s"]
|
|
9
|
+
|
|
10
|
+
if sys.version_info >= (3, 14):
|
|
11
|
+
TEMPLATE_STRING_SUPPORTED = True
|
|
12
|
+
else:
|
|
13
|
+
TEMPLATE_STRING_SUPPORTED = False
|
|
14
|
+
|
|
15
|
+
@typing.runtime_checkable
|
|
16
|
+
class Template(typing.Protocol):
|
|
17
|
+
@property
|
|
18
|
+
def strings(self) -> tuple[str, ...]:
|
|
19
|
+
"""
|
|
20
|
+
A non-empty tuple of the string parts of the template,
|
|
21
|
+
with N+1 items, where N is the number of interpolations
|
|
22
|
+
in the template.
|
|
23
|
+
"""
|
|
24
|
+
@property
|
|
25
|
+
def interpolations(self) -> tuple[Interpolation, ...]:
|
|
26
|
+
"""
|
|
27
|
+
A tuple of the interpolation parts of the template.
|
|
28
|
+
This will be an empty tuple if there are no interpolations.
|
|
29
|
+
"""
|
|
30
|
+
def __new__(cls, *args: str | Interpolation):
|
|
31
|
+
"""
|
|
32
|
+
Create a new Template instance.
|
|
33
|
+
|
|
34
|
+
Arguments can be provided in any order.
|
|
35
|
+
"""
|
|
36
|
+
@property
|
|
37
|
+
def values(self) -> tuple[object, ...]:
|
|
38
|
+
"""
|
|
39
|
+
Return a tuple of the `value` attributes of each Interpolation
|
|
40
|
+
in the template.
|
|
41
|
+
This will be an empty tuple if there are no interpolations.
|
|
42
|
+
"""
|
|
43
|
+
def __iter__(self) -> typing.Iterator[str | Interpolation]:
|
|
44
|
+
"""
|
|
45
|
+
Iterate over the string parts and interpolations in the template.
|
|
46
|
+
|
|
47
|
+
These may appear in any order. Empty strings will not be included.
|
|
48
|
+
"""
|
|
49
|
+
def __add__(self, other: str | Template) -> Template: ...
|
|
50
|
+
def __radd__(self, other: str | Template) -> Template: ...
|
|
51
|
+
|
|
52
|
+
@typing.runtime_checkable
|
|
53
|
+
class Interpolation(typing.Protocol):
|
|
54
|
+
__match_args__ = ("value", "expression", "conversion", "format_spec")
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def value(self) -> object: ...
|
|
58
|
+
@property
|
|
59
|
+
def expression(self) -> str: ...
|
|
60
|
+
@property
|
|
61
|
+
def conversion(self) -> typing.Literal["a", "r", "s"] | None: ...
|
|
62
|
+
@property
|
|
63
|
+
def format_spec(self) -> str: ...
|
|
64
|
+
def __new__(
|
|
65
|
+
cls,
|
|
66
|
+
value: object,
|
|
67
|
+
expression: str,
|
|
68
|
+
conversion: typing.Literal["a", "r", "s"] | None = None,
|
|
69
|
+
format_spec: str = "",
|
|
70
|
+
): ...
|
tstr/_utils.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import types
|
|
3
|
+
import typing
|
|
4
|
+
from string import Formatter
|
|
5
|
+
|
|
6
|
+
from ._template import TEMPLATE_STRING_SUPPORTED, Conversion, Interpolation, Template
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"bind",
|
|
10
|
+
"binder",
|
|
11
|
+
"f",
|
|
12
|
+
"render",
|
|
13
|
+
"convert",
|
|
14
|
+
"converter",
|
|
15
|
+
"normalize",
|
|
16
|
+
"normalize_str",
|
|
17
|
+
"generate_template",
|
|
18
|
+
"TemplateGenerationError",
|
|
19
|
+
"template_eq",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
_formatter = Formatter()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TemplateGenerationError(Exception):
|
|
26
|
+
"""
|
|
27
|
+
Exception raised when a template cannot be generated.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def converter[T](conversion: Conversion) -> typing.Callable[[T], T | str]:
|
|
32
|
+
"""
|
|
33
|
+
Returns a callable that converts a value based on conversion specifiers.
|
|
34
|
+
|
|
35
|
+
This function maps conversion specifiers to their corresponding conversion
|
|
36
|
+
functions: "a" returns `ascii`, "r" returns `repr`, and "s" returns `str`.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
conversion (Conversion): The conversion specifier.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
Callable[[T], T | str]: A function that performs the specified conversion.
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
ValueError: If the conversion specifier is not one of the allowed values.
|
|
46
|
+
"""
|
|
47
|
+
if conversion == "a":
|
|
48
|
+
return ascii
|
|
49
|
+
elif conversion == "r":
|
|
50
|
+
return repr
|
|
51
|
+
elif conversion == "s":
|
|
52
|
+
return str
|
|
53
|
+
else:
|
|
54
|
+
raise ValueError(f"Invalid conversion: {conversion}")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def convert[T](
|
|
58
|
+
value: T,
|
|
59
|
+
conversion: Conversion | None,
|
|
60
|
+
) -> T | str:
|
|
61
|
+
"""
|
|
62
|
+
Applies a conversion to a value, similar to how f-strings handle conversions.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
value (T): The value to convert, typically from an Interpolation.value.
|
|
66
|
+
conversion (Conversion | None): The conversion specifier ('a', 'r', or 's'), or None.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
T | str: The value converted according to the specified conversion; if 'conversion' is None, returns the original value unchanged.
|
|
70
|
+
"""
|
|
71
|
+
return converter(conversion)(value) if conversion else value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def normalize_str(interpolation: Interpolation) -> str:
|
|
75
|
+
"""
|
|
76
|
+
Normalizes a PEP 750 Interpolation to a formatted string.
|
|
77
|
+
|
|
78
|
+
This processes an Interpolation object similarly to how f-strings process
|
|
79
|
+
interpolated expressions: it applies any conversion and format specification.
|
|
80
|
+
Unlike normalize(), this always returns a string.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
interpolation (Interpolation): The interpolation to normalize.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
str: The formatted string representation of the interpolation.
|
|
87
|
+
"""
|
|
88
|
+
converted = convert(interpolation.value, interpolation.conversion)
|
|
89
|
+
return format(converted, interpolation.format_spec)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def normalize(interpolation: Interpolation) -> str | object:
|
|
93
|
+
"""
|
|
94
|
+
Normalizes a PEP 750 Interpolation, preserving its type when possible.
|
|
95
|
+
|
|
96
|
+
This is a more flexible version of normalize_str() that preserves the original
|
|
97
|
+
value's type when no conversion is specified.
|
|
98
|
+
|
|
99
|
+
If neither a conversion nor a format spec is specified, the original value
|
|
100
|
+
is returned without any modification, ensuring that the value's type is preserved.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
interpolation (Interpolation): The interpolation to normalize.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
str | object: The normalized string if conversion or format spec is specified,
|
|
107
|
+
otherwise the original value.
|
|
108
|
+
"""
|
|
109
|
+
if interpolation.conversion or interpolation.format_spec:
|
|
110
|
+
return normalize_str(interpolation)
|
|
111
|
+
else:
|
|
112
|
+
return interpolation.value
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@typing.overload
|
|
116
|
+
def bind(
|
|
117
|
+
template: Template,
|
|
118
|
+
binder: typing.Callable[[Interpolation], str],
|
|
119
|
+
*,
|
|
120
|
+
joiner: typing.Callable[[typing.Iterable[str]], str] = ...,
|
|
121
|
+
) -> str: ...
|
|
122
|
+
@typing.overload
|
|
123
|
+
def bind[U](
|
|
124
|
+
template: Template,
|
|
125
|
+
binder: typing.Callable[[Interpolation], str],
|
|
126
|
+
*,
|
|
127
|
+
joiner: typing.Callable[[typing.Iterable[str]], U],
|
|
128
|
+
) -> U: ...
|
|
129
|
+
@typing.overload
|
|
130
|
+
def bind[T, U](
|
|
131
|
+
template: Template,
|
|
132
|
+
binder: typing.Callable[[Interpolation], T],
|
|
133
|
+
*,
|
|
134
|
+
joiner: typing.Callable[[typing.Iterable[T | str]], U],
|
|
135
|
+
) -> U: ...
|
|
136
|
+
def bind(template: Template, binder, *, joiner="".join) -> typing.Any:
|
|
137
|
+
"""
|
|
138
|
+
Binds a template by processing its interpolations using a binder function
|
|
139
|
+
and combining the results with a joiner function.
|
|
140
|
+
|
|
141
|
+
This function processes each `Interpolation` in the given template using the
|
|
142
|
+
provided `binder` function, and then combines the processed parts using the
|
|
143
|
+
`joiner` function. By default, the `joiner` concatenates the parts into a single
|
|
144
|
+
string.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
template (Template): A template to process.
|
|
148
|
+
binder: A callable that transforms each Interpolation.
|
|
149
|
+
joiner: A callable to join the processed template parts.
|
|
150
|
+
"""
|
|
151
|
+
return joiner(_bind_iterator(template, binder))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@typing.overload
|
|
155
|
+
def binder(
|
|
156
|
+
binder: typing.Callable[[Interpolation], str],
|
|
157
|
+
joiner: typing.Callable[[typing.Iterable[str]], str] = ...,
|
|
158
|
+
) -> typing.Callable[[Template], str]: ...
|
|
159
|
+
@typing.overload
|
|
160
|
+
def binder[U](
|
|
161
|
+
binder: typing.Callable[[Interpolation], str],
|
|
162
|
+
joiner: typing.Callable[[typing.Iterable[str]], U],
|
|
163
|
+
) -> typing.Callable[[Template], U]: ...
|
|
164
|
+
@typing.overload
|
|
165
|
+
def binder[T, U](
|
|
166
|
+
binder: typing.Callable[[Interpolation], T],
|
|
167
|
+
joiner: typing.Callable[[typing.Iterable[T | str]], U],
|
|
168
|
+
) -> typing.Callable[[Template], U]: ...
|
|
169
|
+
def binder(binder, joiner="".join) -> typing.Any:
|
|
170
|
+
"""
|
|
171
|
+
Creates a reusable template processor function from a binder function.
|
|
172
|
+
|
|
173
|
+
This is a higher-order function that creates specialized template processors,
|
|
174
|
+
as described in the "Creating Reusable Binders" section of PEP 750.
|
|
175
|
+
Use this when you want to process multiple templates with the same transformation.
|
|
176
|
+
|
|
177
|
+
Additionally, this can be used as a decorator to create reusable template
|
|
178
|
+
processors in a concise and readable way.
|
|
179
|
+
|
|
180
|
+
Args:
|
|
181
|
+
binder: A function that transforms Interpolation objects.
|
|
182
|
+
joiner: A function to join the processed template parts. Defaults to "".join.
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
Callable[[Template], Any]: A function that processes templates using the given binder.
|
|
186
|
+
|
|
187
|
+
Example:
|
|
188
|
+
```python
|
|
189
|
+
@binder
|
|
190
|
+
def html_safe(interpolation: Interpolation) -> str:
|
|
191
|
+
# Example binder that escapes HTML in interpolations
|
|
192
|
+
return escape(normalize_str(interpolation))
|
|
193
|
+
|
|
194
|
+
username = "<script>alert('XSS')</script>"
|
|
195
|
+
template = t"Hello {username}!"
|
|
196
|
+
result = html_safe(template)
|
|
197
|
+
assert result == "Hello <script>alert('XSS')</script>!"
|
|
198
|
+
```
|
|
199
|
+
"""
|
|
200
|
+
return lambda template: bind(template, binder, joiner=joiner)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
f = render = binder(normalize_str)
|
|
204
|
+
"""
|
|
205
|
+
Renders a template as a string, just like f-strings.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
template (Template): The template to render.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
str: The rendered string.
|
|
212
|
+
"""
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def template_eq(
|
|
216
|
+
template1: Template,
|
|
217
|
+
template2: Template,
|
|
218
|
+
/,
|
|
219
|
+
*,
|
|
220
|
+
compare_value: bool = True,
|
|
221
|
+
compare_expr: bool = True,
|
|
222
|
+
) -> bool:
|
|
223
|
+
"""
|
|
224
|
+
Compares two Template objects for equivalence.
|
|
225
|
+
|
|
226
|
+
This function checks whether two Template instances are equivalent by comparing
|
|
227
|
+
their string and interpolation parts.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
template1 (Template): The first template to compare.
|
|
231
|
+
template2 (Template): The second template to compare.
|
|
232
|
+
compare_value (bool, optional): If False, the 'value' attribute of each interpolation is not compared. Defaults to True.
|
|
233
|
+
compare_expr (bool, optional): If False, the 'expression' attribute of each interpolation is not compared. Defaults to True.
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
bool: True if the templates are considered equivalent based on the specified criteria, False otherwise.
|
|
237
|
+
|
|
238
|
+
Example:
|
|
239
|
+
```python
|
|
240
|
+
name = "world"
|
|
241
|
+
template1 = t"Hello {name}!"
|
|
242
|
+
template2 = t"Hello {name}!"
|
|
243
|
+
assert template_eq(template1, template2)
|
|
244
|
+
|
|
245
|
+
# Compare structure but not values
|
|
246
|
+
name1 = "world"
|
|
247
|
+
name2 = "universe"
|
|
248
|
+
template1 = t"Hello {name1}!"
|
|
249
|
+
template2 = t"Hello {name2}!"
|
|
250
|
+
assert template_eq(template1, template2, compare_value=False)
|
|
251
|
+
assert not template_eq(template1, template2, compare_value=True)
|
|
252
|
+
```
|
|
253
|
+
"""
|
|
254
|
+
# Comparing strings also guarantees that the number of interpolations is equal.
|
|
255
|
+
if template1.strings != template2.strings:
|
|
256
|
+
return False
|
|
257
|
+
for i1, i2 in zip(template1.interpolations, template2.interpolations, strict=True):
|
|
258
|
+
if (
|
|
259
|
+
i1.conversion != i2.conversion
|
|
260
|
+
or i1.format_spec != i2.format_spec
|
|
261
|
+
or compare_expr and i1.expression != i2.expression
|
|
262
|
+
or compare_value and i1.value != i2.value
|
|
263
|
+
):
|
|
264
|
+
return False
|
|
265
|
+
return True
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _bind_iterator(template: Template, binder):
|
|
269
|
+
for item in template:
|
|
270
|
+
if isinstance(item, str):
|
|
271
|
+
yield item
|
|
272
|
+
else:
|
|
273
|
+
yield binder(item)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def generate_template(
|
|
277
|
+
string: typing.LiteralString,
|
|
278
|
+
context: typing.Mapping[str, object] | None = None,
|
|
279
|
+
*,
|
|
280
|
+
globals: dict | None = None,
|
|
281
|
+
use_eval: bool | None = None,
|
|
282
|
+
) -> Template:
|
|
283
|
+
"""
|
|
284
|
+
Constructs a Template object from a string and a context.
|
|
285
|
+
|
|
286
|
+
This function provides an alternative to t-string syntax, especially useful for
|
|
287
|
+
older Python versions that don't support t-strings. It allows you to create
|
|
288
|
+
Template objects dynamically at runtime by parsing a string, evaluating expressions
|
|
289
|
+
found in the string against the provided context, and building a Template object.
|
|
290
|
+
|
|
291
|
+
Note: This is less safe than using the t-string syntax directly, as
|
|
292
|
+
expressions are evaluated at runtime. If an expression is not a simple
|
|
293
|
+
variable name in the context, it attempts to evaluate the expression
|
|
294
|
+
using eval by default (configurable with use_eval).
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
string (str): A string containing template to be parsed.
|
|
298
|
+
context (dict): A mapping of variable names to values that
|
|
299
|
+
will be used to evaluate expressions in the string. This parameter
|
|
300
|
+
functions similarly to the locals parameter in Python's eval function.
|
|
301
|
+
globals (dict, optional): Global variables to use for expression evaluation.
|
|
302
|
+
use_eval (bool, optional): If True, expressions that aren't simple variable names
|
|
303
|
+
will be evaluated using Python's eval function. If False, expressions must be
|
|
304
|
+
simple variable names in the context dictionary. Defaults to False if context
|
|
305
|
+
is provided, otherwise defaults to True.
|
|
306
|
+
|
|
307
|
+
Returns:
|
|
308
|
+
Template: A Template object constructed from the parsed string.
|
|
309
|
+
|
|
310
|
+
Raises:
|
|
311
|
+
TemplateGenerationError: If use_eval=False and a variable cannot be found in the context.
|
|
312
|
+
|
|
313
|
+
Example:
|
|
314
|
+
```python
|
|
315
|
+
name = "world"
|
|
316
|
+
template = generate_template("Hello {name}!")
|
|
317
|
+
assert f(template) == "Hello world!"
|
|
318
|
+
|
|
319
|
+
# With explicit context
|
|
320
|
+
context = {"name": "universe"}
|
|
321
|
+
template = generate_template("Hello {name}!", context)
|
|
322
|
+
assert f(template) == "Hello universe!"
|
|
323
|
+
```
|
|
324
|
+
"""
|
|
325
|
+
if context is None:
|
|
326
|
+
if use_eval is None:
|
|
327
|
+
use_eval = False
|
|
328
|
+
if (frame := inspect.currentframe()) and (parent_frame := frame.f_back):
|
|
329
|
+
vars = parent_frame.f_locals
|
|
330
|
+
else:
|
|
331
|
+
vars = {}
|
|
332
|
+
else:
|
|
333
|
+
if use_eval is None:
|
|
334
|
+
use_eval = False
|
|
335
|
+
vars = context
|
|
336
|
+
|
|
337
|
+
parts = []
|
|
338
|
+
for value, expr, format_spec, conv in _formatter.parse(string):
|
|
339
|
+
parts.append(value)
|
|
340
|
+
if expr is not None:
|
|
341
|
+
try:
|
|
342
|
+
value = vars[expr]
|
|
343
|
+
except Exception:
|
|
344
|
+
if use_eval:
|
|
345
|
+
value = eval(expr, globals=globals, locals=context)
|
|
346
|
+
else:
|
|
347
|
+
raise TemplateGenerationError(f"'{expr}' is not defined or expression.")
|
|
348
|
+
parts.append(Interpolation(value, expr, conv, format_spec)) # type: ignore
|
|
349
|
+
return Template(*parts) # type: ignore
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
class _FrameVariables:
|
|
353
|
+
"""
|
|
354
|
+
A class for accessing variables from the current frame and its parent frames (ancestors).
|
|
355
|
+
|
|
356
|
+
This class allows retrieving both local and non-local variables by traversing up the stack frame hierarchy,
|
|
357
|
+
enabling access to variables that are defined in parent scopes.
|
|
358
|
+
"""
|
|
359
|
+
|
|
360
|
+
def __init__(self, frame: types.FrameType) -> None:
|
|
361
|
+
self._first_frame = frame
|
|
362
|
+
self._current_frame = frame
|
|
363
|
+
self._variables = frame.f_locals
|
|
364
|
+
self._reach_end = False
|
|
365
|
+
|
|
366
|
+
def __getitem__(self, key: str) -> object:
|
|
367
|
+
try:
|
|
368
|
+
return self._variables[key]
|
|
369
|
+
except KeyError:
|
|
370
|
+
if self._reach_end:
|
|
371
|
+
raise
|
|
372
|
+
|
|
373
|
+
self._retrieve_parent_frame()
|
|
374
|
+
return self[key]
|
|
375
|
+
|
|
376
|
+
def _retrieve_parent_frame(self) -> None:
|
|
377
|
+
parent_frame = self._current_frame.f_back
|
|
378
|
+
if parent_frame is None:
|
|
379
|
+
self._reach_end = True
|
|
380
|
+
return
|
|
381
|
+
self._current_frame = parent_frame
|
|
382
|
+
self._variables.update(parent_frame.f_locals)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
t = generate_template
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tstr
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Template string utilities and backports
|
|
5
|
+
Project-URL: Repository, https://github.com/ilotoki0804/tstr
|
|
6
|
+
Author-email: ilotoki0804 <ilotoki0804@gmail.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: backport,string,template,utility
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Requires-Python: >=3.13
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# tstr
|
|
18
|
+
|
|
19
|
+
`tstr` is a Python library that provides convenient utility functions for working with [PEP 750 template strings](https://peps.python.org/pep-0750/). While template strings (`t"..."`) are powerful on their own, `tstr` makes them even easier to use by providing common processing patterns and utilities.
|
|
20
|
+
|
|
21
|
+
For Python versions older than 3.14, `tstr` includes a backport implementation allowing you to use template strings functionality in earlier Python versions.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install tstr
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Requirements
|
|
30
|
+
|
|
31
|
+
- Python 3.14+ (template strings were introduced in Python 3.14 via PEP 750)
|
|
32
|
+
|
|
33
|
+
## Quick Start
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from tstr import f
|
|
37
|
+
|
|
38
|
+
# Use template strings
|
|
39
|
+
name = "world"
|
|
40
|
+
template = t"Hello, {name}!"
|
|
41
|
+
|
|
42
|
+
# Convert to a string (just like f-strings)
|
|
43
|
+
result = f(template) # "Hello, world!"
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Core Functions
|
|
47
|
+
|
|
48
|
+
### Working with Template Strings
|
|
49
|
+
|
|
50
|
+
- **`f(template)` / `evaluate(template)`**: Convert a template to a string (like f-strings)
|
|
51
|
+
- **`normalize(interpolation)`**: Process an interpolation to get its value or string representation
|
|
52
|
+
- **`normalize_str(interpolation)`**: Convert an interpolation to a formatted string
|
|
53
|
+
|
|
54
|
+
### Template Processing
|
|
55
|
+
|
|
56
|
+
- **`bind(template, binder, *, joiner="".join)`**: Apply a function to each interpolation in a template
|
|
57
|
+
- **`binder(function, joiner="".join)`**: Create a reusable template processor function
|
|
58
|
+
- **`converter(conversion)`**: Get a conversion function (ascii, repr, str) for a conversion specifier
|
|
59
|
+
- **`convert(value, conversion)`**: Apply a conversion to a value
|
|
60
|
+
|
|
61
|
+
## Examples
|
|
62
|
+
|
|
63
|
+
### Basic Usage: Template to String
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from tstr import f, evaluate
|
|
67
|
+
|
|
68
|
+
name = "world"
|
|
69
|
+
template = t"Hello, {name}!"
|
|
70
|
+
|
|
71
|
+
# Both functions do the same thing
|
|
72
|
+
result1 = f(template) # "Hello, world!"
|
|
73
|
+
result2 = evaluate(template) # "Hello, world!"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Creating Custom Template Processors
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from tstr import bind, normalize_str
|
|
80
|
+
|
|
81
|
+
def html_escape(text):
|
|
82
|
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
83
|
+
|
|
84
|
+
def safe_html(template):
|
|
85
|
+
# Apply HTML escaping to each interpolation
|
|
86
|
+
return bind(template, lambda i: html_escape(normalize_str(i)))
|
|
87
|
+
|
|
88
|
+
user_content = "<script>alert('XSS attack')</script>"
|
|
89
|
+
template = t"<div>{user_content}</div>"
|
|
90
|
+
safe_output = safe_html(template)
|
|
91
|
+
# "<div><script>alert('XSS attack')</script></div>"
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Using Binders for Reusable Processors
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from tstr import binder, normalize_str
|
|
98
|
+
|
|
99
|
+
# Create a custom template processor
|
|
100
|
+
uppercase = binder(lambda i: normalize_str(i).upper())
|
|
101
|
+
|
|
102
|
+
# Use it on multiple templates
|
|
103
|
+
name = "world"
|
|
104
|
+
place = "Python"
|
|
105
|
+
template1 = t"Hello, {name}!"
|
|
106
|
+
template2 = t"Welcome to {place}!"
|
|
107
|
+
|
|
108
|
+
result1 = uppercase(template1) # "Hello, WORLD!"
|
|
109
|
+
result2 = uppercase(template2) # "Welcome to PYTHON!"
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Advanced Template Comparison
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from tstr import template_equivalent
|
|
116
|
+
|
|
117
|
+
name = "World"
|
|
118
|
+
template1 = t"Hello {name}"
|
|
119
|
+
template2 = t"Hello {name}"
|
|
120
|
+
|
|
121
|
+
# Compare templates with full equality check
|
|
122
|
+
assert template_equivalent(template1, template2)
|
|
123
|
+
|
|
124
|
+
# Compare only structure, not values
|
|
125
|
+
template3 = t"Hello {name}"
|
|
126
|
+
name = "Python"
|
|
127
|
+
template4 = t"Hello {name}"
|
|
128
|
+
assert template_equivalent(template3, template4, compare_value=False)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Why Use Template Strings?
|
|
132
|
+
|
|
133
|
+
Template strings allow you to work with both the literal string parts and interpolated values before they're combined. This enables:
|
|
134
|
+
|
|
135
|
+
1. **Security**: Sanitize user input before rendering (prevent XSS, SQL injection)
|
|
136
|
+
2. **Custom formatting**: Format values based on their types or context
|
|
137
|
+
3. **Domain-specific languages**: Build HTML, SQL, or other languages safely
|
|
138
|
+
4. **Structural analysis**: Examine template structure for validation or optimization
|
|
139
|
+
|
|
140
|
+
## Documentation
|
|
141
|
+
|
|
142
|
+
For more detailed documentation, see the [API Reference](https://tstr.readthedocs.io/).
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
Apache License 2.0
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
tstr/__init__.py,sha256=a_xcHwtQBclzWZo2hn2tAKiuXwaOXdUDCn6Boyn3hU4,559
|
|
2
|
+
tstr/_compat.py,sha256=Gizkr2G1y-60nqbdoBrRnvYxvUx3U5eGmKm9KoKZhcY,4446
|
|
3
|
+
tstr/_html.py,sha256=iHuw6EqUvJwkFJJzSmApvOlA8S1_kIQ4Y1VhFqAs71A,1936
|
|
4
|
+
tstr/_sqlite.py,sha256=9gE6QOp5-A4MB02YK9lrA302IktpCXDKcvT6cMBlHiI,1071
|
|
5
|
+
tstr/_template.py,sha256=oaaF7gIXFBfArc89VzUOO5cmaQs51DVovHNT1xq7jwc,454
|
|
6
|
+
tstr/_template.pyi,sha256=HraiYGXxfPwgryReRO-54KaJ14_vkrpxTU0Y2qe6qoA,2129
|
|
7
|
+
tstr/_utils.py,sha256=eBu9OSEp_fjnL3ABjT0THPx4-g2u7CKtlieqwKkpSLw,12901
|
|
8
|
+
tstr-0.1.0.dist-info/METADATA,sha256=_zAD_oErEBmLMU0jeNWegEBcSXorLkzO_Ps8SF-oE0g,4394
|
|
9
|
+
tstr-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
10
|
+
tstr-0.1.0.dist-info/licenses/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
|
|
11
|
+
tstr-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|