Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/_yaml/__init__.py +33 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/METADATA +59 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/RECORD +24 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/WHEEL +7 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/licenses/LICENSE +20 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/top_level.txt +2 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/__init__.py +390 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/composer.py +139 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/constructor.py +748 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/cyaml.py +101 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/dumper.py +62 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/emitter.py +1137 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/error.py +75 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/events.py +86 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/loader.py +63 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/nodes.py +49 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/parser.py +589 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/reader.py +185 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/representer.py +389 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/resolver.py +227 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/scanner.py +1435 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/serializer.py +111 -0
- .cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/tokens.py +104 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore-1.0.9.dist-info/METADATA +625 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore-1.0.9.dist-info/RECORD +36 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore-1.0.9.dist-info/WHEEL +4 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore-1.0.9.dist-info/licenses/LICENSE.md +27 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/__init__.py +141 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_api.py +94 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/__init__.py +39 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/connection.py +222 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/connection_pool.py +420 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/http11.py +379 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/http2.py +592 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/http_proxy.py +367 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/interfaces.py +137 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/socks_proxy.py +341 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/__init__.py +0 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/anyio.py +146 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/auto.py +52 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/base.py +101 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/mock.py +143 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/sync.py +241 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/trio.py +159 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_exceptions.py +81 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_models.py +516 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_ssl.py +9 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_sync/__init__.py +39 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_sync/connection.py +222 -0
- .cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_sync/connection_pool.py +420 -0
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/_yaml/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a stub package designed to roughly emulate the _yaml
|
| 2 |
+
# extension module, which previously existed as a standalone module
|
| 3 |
+
# and has been moved into the `yaml` package namespace.
|
| 4 |
+
# It does not perfectly mimic its old counterpart, but should get
|
| 5 |
+
# close enough for anyone who's relying on it even when they shouldn't.
|
| 6 |
+
import yaml
|
| 7 |
+
|
| 8 |
+
# in some circumstances, the yaml module we imoprted may be from a different version, so we need
|
| 9 |
+
# to tread carefully when poking at it here (it may not have the attributes we expect)
|
| 10 |
+
if not getattr(yaml, '__with_libyaml__', False):
|
| 11 |
+
from sys import version_info
|
| 12 |
+
|
| 13 |
+
exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError
|
| 14 |
+
raise exc("No module named '_yaml'")
|
| 15 |
+
else:
|
| 16 |
+
from yaml._yaml import *
|
| 17 |
+
import warnings
|
| 18 |
+
warnings.warn(
|
| 19 |
+
'The _yaml extension module is now located at yaml._yaml'
|
| 20 |
+
' and its location is subject to change. To use the'
|
| 21 |
+
' LibYAML-based parser and emitter, import from `yaml`:'
|
| 22 |
+
' `from yaml import CLoader as Loader, CDumper as Dumper`.',
|
| 23 |
+
DeprecationWarning
|
| 24 |
+
)
|
| 25 |
+
del warnings
|
| 26 |
+
# Don't `del yaml` here because yaml is actually an existing
|
| 27 |
+
# namespace member of _yaml.
|
| 28 |
+
|
| 29 |
+
__name__ = '_yaml'
|
| 30 |
+
# If the module is top-level (i.e. not a part of any specific package)
|
| 31 |
+
# then the attribute should be set to ''.
|
| 32 |
+
# https://docs.python.org/3.8/library/types.html
|
| 33 |
+
__package__ = ''
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/METADATA
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: PyYAML
|
| 3 |
+
Version: 6.0.3
|
| 4 |
+
Summary: YAML parser and emitter for Python
|
| 5 |
+
Home-page: https://pyyaml.org/
|
| 6 |
+
Download-URL: https://pypi.org/project/PyYAML/
|
| 7 |
+
Author: Kirill Simonov
|
| 8 |
+
Author-email: xi@resolvent.net
|
| 9 |
+
License: MIT
|
| 10 |
+
Project-URL: Bug Tracker, https://github.com/yaml/pyyaml/issues
|
| 11 |
+
Project-URL: CI, https://github.com/yaml/pyyaml/actions
|
| 12 |
+
Project-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentation
|
| 13 |
+
Project-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-core
|
| 14 |
+
Project-URL: Source Code, https://github.com/yaml/pyyaml
|
| 15 |
+
Platform: Any
|
| 16 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 17 |
+
Classifier: Intended Audience :: Developers
|
| 18 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 19 |
+
Classifier: Operating System :: OS Independent
|
| 20 |
+
Classifier: Programming Language :: Cython
|
| 21 |
+
Classifier: Programming Language :: Python
|
| 22 |
+
Classifier: Programming Language :: Python :: 3
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 27 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 28 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 29 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 30 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 31 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 32 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 33 |
+
Classifier: Topic :: Text Processing :: Markup
|
| 34 |
+
Requires-Python: >=3.8
|
| 35 |
+
License-File: LICENSE
|
| 36 |
+
Dynamic: author
|
| 37 |
+
Dynamic: author-email
|
| 38 |
+
Dynamic: classifier
|
| 39 |
+
Dynamic: description
|
| 40 |
+
Dynamic: download-url
|
| 41 |
+
Dynamic: home-page
|
| 42 |
+
Dynamic: license
|
| 43 |
+
Dynamic: license-file
|
| 44 |
+
Dynamic: platform
|
| 45 |
+
Dynamic: project-url
|
| 46 |
+
Dynamic: requires-python
|
| 47 |
+
Dynamic: summary
|
| 48 |
+
|
| 49 |
+
YAML is a data serialization format designed for human readability
|
| 50 |
+
and interaction with scripting languages. PyYAML is a YAML parser
|
| 51 |
+
and emitter for Python.
|
| 52 |
+
|
| 53 |
+
PyYAML features a complete YAML 1.1 parser, Unicode support, pickle
|
| 54 |
+
support, capable extension API, and sensible error messages. PyYAML
|
| 55 |
+
supports standard YAML tags and provides Python-specific tags that
|
| 56 |
+
allow to represent an arbitrary Python object.
|
| 57 |
+
|
| 58 |
+
PyYAML is applicable for a broad range of tasks from complex
|
| 59 |
+
configuration files to object serialization and persistence.
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/RECORD
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402
|
| 2 |
+
yaml/__init__.py,sha256=sZ38wzPWp139cwc5ARZFByUvJxtB07X32FUQAzoFR6c,12311
|
| 3 |
+
yaml/_yaml.cpython-312-x86_64-linux-gnu.so,sha256=lXoJmkUhwfdmkwb7b3nKY_pLmgtMRj98rIM6ZaXFwMs,2679264
|
| 4 |
+
yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883
|
| 5 |
+
yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639
|
| 6 |
+
yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851
|
| 7 |
+
yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837
|
| 8 |
+
yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006
|
| 9 |
+
yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533
|
| 10 |
+
yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445
|
| 11 |
+
yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061
|
| 12 |
+
yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440
|
| 13 |
+
yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495
|
| 14 |
+
yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794
|
| 15 |
+
yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190
|
| 16 |
+
yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004
|
| 17 |
+
yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279
|
| 18 |
+
yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165
|
| 19 |
+
yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573
|
| 20 |
+
pyyaml-6.0.3.dist-info/METADATA,sha256=A8O0Fe040J-u3Ek2DpMHabQMWPaFhebeAOLkkWqFjTQ,2351
|
| 21 |
+
pyyaml-6.0.3.dist-info/WHEEL,sha256=DxRnWQz-Kp9-4a4hdDHsSv0KUC3H7sN9Nbef3-8RjXU,190
|
| 22 |
+
pyyaml-6.0.3.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11
|
| 23 |
+
pyyaml-6.0.3.dist-info/RECORD,,
|
| 24 |
+
pyyaml-6.0.3.dist-info/licenses/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (80.9.0)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp312-cp312-manylinux_2_17_x86_64
|
| 5 |
+
Tag: cp312-cp312-manylinux2014_x86_64
|
| 6 |
+
Tag: cp312-cp312-manylinux_2_28_x86_64
|
| 7 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2017-2021 Ingy döt Net
|
| 2 |
+
Copyright (c) 2006-2016 Kirill Simonov
|
| 3 |
+
|
| 4 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
| 5 |
+
this software and associated documentation files (the "Software"), to deal in
|
| 6 |
+
the Software without restriction, including without limitation the rights to
|
| 7 |
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
| 8 |
+
of the Software, and to permit persons to whom the Software is furnished to do
|
| 9 |
+
so, subject to the following conditions:
|
| 10 |
+
|
| 11 |
+
The above copyright notice and this permission notice shall be included in all
|
| 12 |
+
copies or substantial portions of the Software.
|
| 13 |
+
|
| 14 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 15 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 16 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 17 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 18 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 19 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 20 |
+
SOFTWARE.
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/pyyaml-6.0.3.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_yaml
|
| 2 |
+
yaml
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/__init__.py
ADDED
|
@@ -0,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from .error import *
|
| 3 |
+
|
| 4 |
+
from .tokens import *
|
| 5 |
+
from .events import *
|
| 6 |
+
from .nodes import *
|
| 7 |
+
|
| 8 |
+
from .loader import *
|
| 9 |
+
from .dumper import *
|
| 10 |
+
|
| 11 |
+
__version__ = '6.0.3'
|
| 12 |
+
try:
|
| 13 |
+
from .cyaml import *
|
| 14 |
+
__with_libyaml__ = True
|
| 15 |
+
except ImportError:
|
| 16 |
+
__with_libyaml__ = False
|
| 17 |
+
|
| 18 |
+
import io
|
| 19 |
+
|
| 20 |
+
#------------------------------------------------------------------------------
|
| 21 |
+
# XXX "Warnings control" is now deprecated. Leaving in the API function to not
|
| 22 |
+
# break code that uses it.
|
| 23 |
+
#------------------------------------------------------------------------------
|
| 24 |
+
def warnings(settings=None):
|
| 25 |
+
if settings is None:
|
| 26 |
+
return {}
|
| 27 |
+
|
| 28 |
+
#------------------------------------------------------------------------------
|
| 29 |
+
def scan(stream, Loader=Loader):
|
| 30 |
+
"""
|
| 31 |
+
Scan a YAML stream and produce scanning tokens.
|
| 32 |
+
"""
|
| 33 |
+
loader = Loader(stream)
|
| 34 |
+
try:
|
| 35 |
+
while loader.check_token():
|
| 36 |
+
yield loader.get_token()
|
| 37 |
+
finally:
|
| 38 |
+
loader.dispose()
|
| 39 |
+
|
| 40 |
+
def parse(stream, Loader=Loader):
|
| 41 |
+
"""
|
| 42 |
+
Parse a YAML stream and produce parsing events.
|
| 43 |
+
"""
|
| 44 |
+
loader = Loader(stream)
|
| 45 |
+
try:
|
| 46 |
+
while loader.check_event():
|
| 47 |
+
yield loader.get_event()
|
| 48 |
+
finally:
|
| 49 |
+
loader.dispose()
|
| 50 |
+
|
| 51 |
+
def compose(stream, Loader=Loader):
|
| 52 |
+
"""
|
| 53 |
+
Parse the first YAML document in a stream
|
| 54 |
+
and produce the corresponding representation tree.
|
| 55 |
+
"""
|
| 56 |
+
loader = Loader(stream)
|
| 57 |
+
try:
|
| 58 |
+
return loader.get_single_node()
|
| 59 |
+
finally:
|
| 60 |
+
loader.dispose()
|
| 61 |
+
|
| 62 |
+
def compose_all(stream, Loader=Loader):
|
| 63 |
+
"""
|
| 64 |
+
Parse all YAML documents in a stream
|
| 65 |
+
and produce corresponding representation trees.
|
| 66 |
+
"""
|
| 67 |
+
loader = Loader(stream)
|
| 68 |
+
try:
|
| 69 |
+
while loader.check_node():
|
| 70 |
+
yield loader.get_node()
|
| 71 |
+
finally:
|
| 72 |
+
loader.dispose()
|
| 73 |
+
|
| 74 |
+
def load(stream, Loader):
|
| 75 |
+
"""
|
| 76 |
+
Parse the first YAML document in a stream
|
| 77 |
+
and produce the corresponding Python object.
|
| 78 |
+
"""
|
| 79 |
+
loader = Loader(stream)
|
| 80 |
+
try:
|
| 81 |
+
return loader.get_single_data()
|
| 82 |
+
finally:
|
| 83 |
+
loader.dispose()
|
| 84 |
+
|
| 85 |
+
def load_all(stream, Loader):
|
| 86 |
+
"""
|
| 87 |
+
Parse all YAML documents in a stream
|
| 88 |
+
and produce corresponding Python objects.
|
| 89 |
+
"""
|
| 90 |
+
loader = Loader(stream)
|
| 91 |
+
try:
|
| 92 |
+
while loader.check_data():
|
| 93 |
+
yield loader.get_data()
|
| 94 |
+
finally:
|
| 95 |
+
loader.dispose()
|
| 96 |
+
|
| 97 |
+
def full_load(stream):
|
| 98 |
+
"""
|
| 99 |
+
Parse the first YAML document in a stream
|
| 100 |
+
and produce the corresponding Python object.
|
| 101 |
+
|
| 102 |
+
Resolve all tags except those known to be
|
| 103 |
+
unsafe on untrusted input.
|
| 104 |
+
"""
|
| 105 |
+
return load(stream, FullLoader)
|
| 106 |
+
|
| 107 |
+
def full_load_all(stream):
|
| 108 |
+
"""
|
| 109 |
+
Parse all YAML documents in a stream
|
| 110 |
+
and produce corresponding Python objects.
|
| 111 |
+
|
| 112 |
+
Resolve all tags except those known to be
|
| 113 |
+
unsafe on untrusted input.
|
| 114 |
+
"""
|
| 115 |
+
return load_all(stream, FullLoader)
|
| 116 |
+
|
| 117 |
+
def safe_load(stream):
|
| 118 |
+
"""
|
| 119 |
+
Parse the first YAML document in a stream
|
| 120 |
+
and produce the corresponding Python object.
|
| 121 |
+
|
| 122 |
+
Resolve only basic YAML tags. This is known
|
| 123 |
+
to be safe for untrusted input.
|
| 124 |
+
"""
|
| 125 |
+
return load(stream, SafeLoader)
|
| 126 |
+
|
| 127 |
+
def safe_load_all(stream):
|
| 128 |
+
"""
|
| 129 |
+
Parse all YAML documents in a stream
|
| 130 |
+
and produce corresponding Python objects.
|
| 131 |
+
|
| 132 |
+
Resolve only basic YAML tags. This is known
|
| 133 |
+
to be safe for untrusted input.
|
| 134 |
+
"""
|
| 135 |
+
return load_all(stream, SafeLoader)
|
| 136 |
+
|
| 137 |
+
def unsafe_load(stream):
|
| 138 |
+
"""
|
| 139 |
+
Parse the first YAML document in a stream
|
| 140 |
+
and produce the corresponding Python object.
|
| 141 |
+
|
| 142 |
+
Resolve all tags, even those known to be
|
| 143 |
+
unsafe on untrusted input.
|
| 144 |
+
"""
|
| 145 |
+
return load(stream, UnsafeLoader)
|
| 146 |
+
|
| 147 |
+
def unsafe_load_all(stream):
|
| 148 |
+
"""
|
| 149 |
+
Parse all YAML documents in a stream
|
| 150 |
+
and produce corresponding Python objects.
|
| 151 |
+
|
| 152 |
+
Resolve all tags, even those known to be
|
| 153 |
+
unsafe on untrusted input.
|
| 154 |
+
"""
|
| 155 |
+
return load_all(stream, UnsafeLoader)
|
| 156 |
+
|
| 157 |
+
def emit(events, stream=None, Dumper=Dumper,
|
| 158 |
+
canonical=None, indent=None, width=None,
|
| 159 |
+
allow_unicode=None, line_break=None):
|
| 160 |
+
"""
|
| 161 |
+
Emit YAML parsing events into a stream.
|
| 162 |
+
If stream is None, return the produced string instead.
|
| 163 |
+
"""
|
| 164 |
+
getvalue = None
|
| 165 |
+
if stream is None:
|
| 166 |
+
stream = io.StringIO()
|
| 167 |
+
getvalue = stream.getvalue
|
| 168 |
+
dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
|
| 169 |
+
allow_unicode=allow_unicode, line_break=line_break)
|
| 170 |
+
try:
|
| 171 |
+
for event in events:
|
| 172 |
+
dumper.emit(event)
|
| 173 |
+
finally:
|
| 174 |
+
dumper.dispose()
|
| 175 |
+
if getvalue:
|
| 176 |
+
return getvalue()
|
| 177 |
+
|
| 178 |
+
def serialize_all(nodes, stream=None, Dumper=Dumper,
|
| 179 |
+
canonical=None, indent=None, width=None,
|
| 180 |
+
allow_unicode=None, line_break=None,
|
| 181 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
| 182 |
+
version=None, tags=None):
|
| 183 |
+
"""
|
| 184 |
+
Serialize a sequence of representation trees into a YAML stream.
|
| 185 |
+
If stream is None, return the produced string instead.
|
| 186 |
+
"""
|
| 187 |
+
getvalue = None
|
| 188 |
+
if stream is None:
|
| 189 |
+
if encoding is None:
|
| 190 |
+
stream = io.StringIO()
|
| 191 |
+
else:
|
| 192 |
+
stream = io.BytesIO()
|
| 193 |
+
getvalue = stream.getvalue
|
| 194 |
+
dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
|
| 195 |
+
allow_unicode=allow_unicode, line_break=line_break,
|
| 196 |
+
encoding=encoding, version=version, tags=tags,
|
| 197 |
+
explicit_start=explicit_start, explicit_end=explicit_end)
|
| 198 |
+
try:
|
| 199 |
+
dumper.open()
|
| 200 |
+
for node in nodes:
|
| 201 |
+
dumper.serialize(node)
|
| 202 |
+
dumper.close()
|
| 203 |
+
finally:
|
| 204 |
+
dumper.dispose()
|
| 205 |
+
if getvalue:
|
| 206 |
+
return getvalue()
|
| 207 |
+
|
| 208 |
+
def serialize(node, stream=None, Dumper=Dumper, **kwds):
|
| 209 |
+
"""
|
| 210 |
+
Serialize a representation tree into a YAML stream.
|
| 211 |
+
If stream is None, return the produced string instead.
|
| 212 |
+
"""
|
| 213 |
+
return serialize_all([node], stream, Dumper=Dumper, **kwds)
|
| 214 |
+
|
| 215 |
+
def dump_all(documents, stream=None, Dumper=Dumper,
|
| 216 |
+
default_style=None, default_flow_style=False,
|
| 217 |
+
canonical=None, indent=None, width=None,
|
| 218 |
+
allow_unicode=None, line_break=None,
|
| 219 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
| 220 |
+
version=None, tags=None, sort_keys=True):
|
| 221 |
+
"""
|
| 222 |
+
Serialize a sequence of Python objects into a YAML stream.
|
| 223 |
+
If stream is None, return the produced string instead.
|
| 224 |
+
"""
|
| 225 |
+
getvalue = None
|
| 226 |
+
if stream is None:
|
| 227 |
+
if encoding is None:
|
| 228 |
+
stream = io.StringIO()
|
| 229 |
+
else:
|
| 230 |
+
stream = io.BytesIO()
|
| 231 |
+
getvalue = stream.getvalue
|
| 232 |
+
dumper = Dumper(stream, default_style=default_style,
|
| 233 |
+
default_flow_style=default_flow_style,
|
| 234 |
+
canonical=canonical, indent=indent, width=width,
|
| 235 |
+
allow_unicode=allow_unicode, line_break=line_break,
|
| 236 |
+
encoding=encoding, version=version, tags=tags,
|
| 237 |
+
explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys)
|
| 238 |
+
try:
|
| 239 |
+
dumper.open()
|
| 240 |
+
for data in documents:
|
| 241 |
+
dumper.represent(data)
|
| 242 |
+
dumper.close()
|
| 243 |
+
finally:
|
| 244 |
+
dumper.dispose()
|
| 245 |
+
if getvalue:
|
| 246 |
+
return getvalue()
|
| 247 |
+
|
| 248 |
+
def dump(data, stream=None, Dumper=Dumper, **kwds):
|
| 249 |
+
"""
|
| 250 |
+
Serialize a Python object into a YAML stream.
|
| 251 |
+
If stream is None, return the produced string instead.
|
| 252 |
+
"""
|
| 253 |
+
return dump_all([data], stream, Dumper=Dumper, **kwds)
|
| 254 |
+
|
| 255 |
+
def safe_dump_all(documents, stream=None, **kwds):
|
| 256 |
+
"""
|
| 257 |
+
Serialize a sequence of Python objects into a YAML stream.
|
| 258 |
+
Produce only basic YAML tags.
|
| 259 |
+
If stream is None, return the produced string instead.
|
| 260 |
+
"""
|
| 261 |
+
return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
|
| 262 |
+
|
| 263 |
+
def safe_dump(data, stream=None, **kwds):
|
| 264 |
+
"""
|
| 265 |
+
Serialize a Python object into a YAML stream.
|
| 266 |
+
Produce only basic YAML tags.
|
| 267 |
+
If stream is None, return the produced string instead.
|
| 268 |
+
"""
|
| 269 |
+
return dump_all([data], stream, Dumper=SafeDumper, **kwds)
|
| 270 |
+
|
| 271 |
+
def add_implicit_resolver(tag, regexp, first=None,
|
| 272 |
+
Loader=None, Dumper=Dumper):
|
| 273 |
+
"""
|
| 274 |
+
Add an implicit scalar detector.
|
| 275 |
+
If an implicit scalar value matches the given regexp,
|
| 276 |
+
the corresponding tag is assigned to the scalar.
|
| 277 |
+
first is a sequence of possible initial characters or None.
|
| 278 |
+
"""
|
| 279 |
+
if Loader is None:
|
| 280 |
+
loader.Loader.add_implicit_resolver(tag, regexp, first)
|
| 281 |
+
loader.FullLoader.add_implicit_resolver(tag, regexp, first)
|
| 282 |
+
loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first)
|
| 283 |
+
else:
|
| 284 |
+
Loader.add_implicit_resolver(tag, regexp, first)
|
| 285 |
+
Dumper.add_implicit_resolver(tag, regexp, first)
|
| 286 |
+
|
| 287 |
+
def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper):
|
| 288 |
+
"""
|
| 289 |
+
Add a path based resolver for the given tag.
|
| 290 |
+
A path is a list of keys that forms a path
|
| 291 |
+
to a node in the representation tree.
|
| 292 |
+
Keys can be string values, integers, or None.
|
| 293 |
+
"""
|
| 294 |
+
if Loader is None:
|
| 295 |
+
loader.Loader.add_path_resolver(tag, path, kind)
|
| 296 |
+
loader.FullLoader.add_path_resolver(tag, path, kind)
|
| 297 |
+
loader.UnsafeLoader.add_path_resolver(tag, path, kind)
|
| 298 |
+
else:
|
| 299 |
+
Loader.add_path_resolver(tag, path, kind)
|
| 300 |
+
Dumper.add_path_resolver(tag, path, kind)
|
| 301 |
+
|
| 302 |
+
def add_constructor(tag, constructor, Loader=None):
|
| 303 |
+
"""
|
| 304 |
+
Add a constructor for the given tag.
|
| 305 |
+
Constructor is a function that accepts a Loader instance
|
| 306 |
+
and a node object and produces the corresponding Python object.
|
| 307 |
+
"""
|
| 308 |
+
if Loader is None:
|
| 309 |
+
loader.Loader.add_constructor(tag, constructor)
|
| 310 |
+
loader.FullLoader.add_constructor(tag, constructor)
|
| 311 |
+
loader.UnsafeLoader.add_constructor(tag, constructor)
|
| 312 |
+
else:
|
| 313 |
+
Loader.add_constructor(tag, constructor)
|
| 314 |
+
|
| 315 |
+
def add_multi_constructor(tag_prefix, multi_constructor, Loader=None):
|
| 316 |
+
"""
|
| 317 |
+
Add a multi-constructor for the given tag prefix.
|
| 318 |
+
Multi-constructor is called for a node if its tag starts with tag_prefix.
|
| 319 |
+
Multi-constructor accepts a Loader instance, a tag suffix,
|
| 320 |
+
and a node object and produces the corresponding Python object.
|
| 321 |
+
"""
|
| 322 |
+
if Loader is None:
|
| 323 |
+
loader.Loader.add_multi_constructor(tag_prefix, multi_constructor)
|
| 324 |
+
loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor)
|
| 325 |
+
loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor)
|
| 326 |
+
else:
|
| 327 |
+
Loader.add_multi_constructor(tag_prefix, multi_constructor)
|
| 328 |
+
|
| 329 |
+
def add_representer(data_type, representer, Dumper=Dumper):
|
| 330 |
+
"""
|
| 331 |
+
Add a representer for the given type.
|
| 332 |
+
Representer is a function accepting a Dumper instance
|
| 333 |
+
and an instance of the given data type
|
| 334 |
+
and producing the corresponding representation node.
|
| 335 |
+
"""
|
| 336 |
+
Dumper.add_representer(data_type, representer)
|
| 337 |
+
|
| 338 |
+
def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
|
| 339 |
+
"""
|
| 340 |
+
Add a representer for the given type.
|
| 341 |
+
Multi-representer is a function accepting a Dumper instance
|
| 342 |
+
and an instance of the given data type or subtype
|
| 343 |
+
and producing the corresponding representation node.
|
| 344 |
+
"""
|
| 345 |
+
Dumper.add_multi_representer(data_type, multi_representer)
|
| 346 |
+
|
| 347 |
+
class YAMLObjectMetaclass(type):
|
| 348 |
+
"""
|
| 349 |
+
The metaclass for YAMLObject.
|
| 350 |
+
"""
|
| 351 |
+
def __init__(cls, name, bases, kwds):
|
| 352 |
+
super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
|
| 353 |
+
if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
|
| 354 |
+
if isinstance(cls.yaml_loader, list):
|
| 355 |
+
for loader in cls.yaml_loader:
|
| 356 |
+
loader.add_constructor(cls.yaml_tag, cls.from_yaml)
|
| 357 |
+
else:
|
| 358 |
+
cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
|
| 359 |
+
|
| 360 |
+
cls.yaml_dumper.add_representer(cls, cls.to_yaml)
|
| 361 |
+
|
| 362 |
+
class YAMLObject(metaclass=YAMLObjectMetaclass):
|
| 363 |
+
"""
|
| 364 |
+
An object that can dump itself to a YAML stream
|
| 365 |
+
and load itself from a YAML stream.
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
__slots__ = () # no direct instantiation, so allow immutable subclasses
|
| 369 |
+
|
| 370 |
+
yaml_loader = [Loader, FullLoader, UnsafeLoader]
|
| 371 |
+
yaml_dumper = Dumper
|
| 372 |
+
|
| 373 |
+
yaml_tag = None
|
| 374 |
+
yaml_flow_style = None
|
| 375 |
+
|
| 376 |
+
@classmethod
|
| 377 |
+
def from_yaml(cls, loader, node):
|
| 378 |
+
"""
|
| 379 |
+
Convert a representation node to a Python object.
|
| 380 |
+
"""
|
| 381 |
+
return loader.construct_yaml_object(node, cls)
|
| 382 |
+
|
| 383 |
+
@classmethod
|
| 384 |
+
def to_yaml(cls, dumper, data):
|
| 385 |
+
"""
|
| 386 |
+
Convert a Python object to a representation node.
|
| 387 |
+
"""
|
| 388 |
+
return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
|
| 389 |
+
flow_style=cls.yaml_flow_style)
|
| 390 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/composer.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
__all__ = ['Composer', 'ComposerError']
|
| 3 |
+
|
| 4 |
+
from .error import MarkedYAMLError
|
| 5 |
+
from .events import *
|
| 6 |
+
from .nodes import *
|
| 7 |
+
|
| 8 |
+
class ComposerError(MarkedYAMLError):
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
class Composer:
|
| 12 |
+
|
| 13 |
+
def __init__(self):
|
| 14 |
+
self.anchors = {}
|
| 15 |
+
|
| 16 |
+
def check_node(self):
|
| 17 |
+
# Drop the STREAM-START event.
|
| 18 |
+
if self.check_event(StreamStartEvent):
|
| 19 |
+
self.get_event()
|
| 20 |
+
|
| 21 |
+
# If there are more documents available?
|
| 22 |
+
return not self.check_event(StreamEndEvent)
|
| 23 |
+
|
| 24 |
+
def get_node(self):
|
| 25 |
+
# Get the root node of the next document.
|
| 26 |
+
if not self.check_event(StreamEndEvent):
|
| 27 |
+
return self.compose_document()
|
| 28 |
+
|
| 29 |
+
def get_single_node(self):
|
| 30 |
+
# Drop the STREAM-START event.
|
| 31 |
+
self.get_event()
|
| 32 |
+
|
| 33 |
+
# Compose a document if the stream is not empty.
|
| 34 |
+
document = None
|
| 35 |
+
if not self.check_event(StreamEndEvent):
|
| 36 |
+
document = self.compose_document()
|
| 37 |
+
|
| 38 |
+
# Ensure that the stream contains no more documents.
|
| 39 |
+
if not self.check_event(StreamEndEvent):
|
| 40 |
+
event = self.get_event()
|
| 41 |
+
raise ComposerError("expected a single document in the stream",
|
| 42 |
+
document.start_mark, "but found another document",
|
| 43 |
+
event.start_mark)
|
| 44 |
+
|
| 45 |
+
# Drop the STREAM-END event.
|
| 46 |
+
self.get_event()
|
| 47 |
+
|
| 48 |
+
return document
|
| 49 |
+
|
| 50 |
+
def compose_document(self):
|
| 51 |
+
# Drop the DOCUMENT-START event.
|
| 52 |
+
self.get_event()
|
| 53 |
+
|
| 54 |
+
# Compose the root node.
|
| 55 |
+
node = self.compose_node(None, None)
|
| 56 |
+
|
| 57 |
+
# Drop the DOCUMENT-END event.
|
| 58 |
+
self.get_event()
|
| 59 |
+
|
| 60 |
+
self.anchors = {}
|
| 61 |
+
return node
|
| 62 |
+
|
| 63 |
+
def compose_node(self, parent, index):
|
| 64 |
+
if self.check_event(AliasEvent):
|
| 65 |
+
event = self.get_event()
|
| 66 |
+
anchor = event.anchor
|
| 67 |
+
if anchor not in self.anchors:
|
| 68 |
+
raise ComposerError(None, None, "found undefined alias %r"
|
| 69 |
+
% anchor, event.start_mark)
|
| 70 |
+
return self.anchors[anchor]
|
| 71 |
+
event = self.peek_event()
|
| 72 |
+
anchor = event.anchor
|
| 73 |
+
if anchor is not None:
|
| 74 |
+
if anchor in self.anchors:
|
| 75 |
+
raise ComposerError("found duplicate anchor %r; first occurrence"
|
| 76 |
+
% anchor, self.anchors[anchor].start_mark,
|
| 77 |
+
"second occurrence", event.start_mark)
|
| 78 |
+
self.descend_resolver(parent, index)
|
| 79 |
+
if self.check_event(ScalarEvent):
|
| 80 |
+
node = self.compose_scalar_node(anchor)
|
| 81 |
+
elif self.check_event(SequenceStartEvent):
|
| 82 |
+
node = self.compose_sequence_node(anchor)
|
| 83 |
+
elif self.check_event(MappingStartEvent):
|
| 84 |
+
node = self.compose_mapping_node(anchor)
|
| 85 |
+
self.ascend_resolver()
|
| 86 |
+
return node
|
| 87 |
+
|
| 88 |
+
def compose_scalar_node(self, anchor):
|
| 89 |
+
event = self.get_event()
|
| 90 |
+
tag = event.tag
|
| 91 |
+
if tag is None or tag == '!':
|
| 92 |
+
tag = self.resolve(ScalarNode, event.value, event.implicit)
|
| 93 |
+
node = ScalarNode(tag, event.value,
|
| 94 |
+
event.start_mark, event.end_mark, style=event.style)
|
| 95 |
+
if anchor is not None:
|
| 96 |
+
self.anchors[anchor] = node
|
| 97 |
+
return node
|
| 98 |
+
|
| 99 |
+
def compose_sequence_node(self, anchor):
|
| 100 |
+
start_event = self.get_event()
|
| 101 |
+
tag = start_event.tag
|
| 102 |
+
if tag is None or tag == '!':
|
| 103 |
+
tag = self.resolve(SequenceNode, None, start_event.implicit)
|
| 104 |
+
node = SequenceNode(tag, [],
|
| 105 |
+
start_event.start_mark, None,
|
| 106 |
+
flow_style=start_event.flow_style)
|
| 107 |
+
if anchor is not None:
|
| 108 |
+
self.anchors[anchor] = node
|
| 109 |
+
index = 0
|
| 110 |
+
while not self.check_event(SequenceEndEvent):
|
| 111 |
+
node.value.append(self.compose_node(node, index))
|
| 112 |
+
index += 1
|
| 113 |
+
end_event = self.get_event()
|
| 114 |
+
node.end_mark = end_event.end_mark
|
| 115 |
+
return node
|
| 116 |
+
|
| 117 |
+
def compose_mapping_node(self, anchor):
|
| 118 |
+
start_event = self.get_event()
|
| 119 |
+
tag = start_event.tag
|
| 120 |
+
if tag is None or tag == '!':
|
| 121 |
+
tag = self.resolve(MappingNode, None, start_event.implicit)
|
| 122 |
+
node = MappingNode(tag, [],
|
| 123 |
+
start_event.start_mark, None,
|
| 124 |
+
flow_style=start_event.flow_style)
|
| 125 |
+
if anchor is not None:
|
| 126 |
+
self.anchors[anchor] = node
|
| 127 |
+
while not self.check_event(MappingEndEvent):
|
| 128 |
+
#key_event = self.peek_event()
|
| 129 |
+
item_key = self.compose_node(node, None)
|
| 130 |
+
#if item_key in node.value:
|
| 131 |
+
# raise ComposerError("while composing a mapping", start_event.start_mark,
|
| 132 |
+
# "found duplicate key", key_event.start_mark)
|
| 133 |
+
item_value = self.compose_node(node, item_key)
|
| 134 |
+
#node.value[item_key] = item_value
|
| 135 |
+
node.value.append((item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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
__all__ = [
|
| 3 |
+
'BaseConstructor',
|
| 4 |
+
'SafeConstructor',
|
| 5 |
+
'FullConstructor',
|
| 6 |
+
'UnsafeConstructor',
|
| 7 |
+
'Constructor',
|
| 8 |
+
'ConstructorError'
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
from .error import *
|
| 12 |
+
from .nodes import *
|
| 13 |
+
|
| 14 |
+
import collections.abc, datetime, base64, binascii, re, sys, types
|
| 15 |
+
|
| 16 |
+
class ConstructorError(MarkedYAMLError):
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
class BaseConstructor:
|
| 20 |
+
|
| 21 |
+
yaml_constructors = {}
|
| 22 |
+
yaml_multi_constructors = {}
|
| 23 |
+
|
| 24 |
+
def __init__(self):
|
| 25 |
+
self.constructed_objects = {}
|
| 26 |
+
self.recursive_objects = {}
|
| 27 |
+
self.state_generators = []
|
| 28 |
+
self.deep_construct = False
|
| 29 |
+
|
| 30 |
+
def check_data(self):
|
| 31 |
+
# If there are more documents available?
|
| 32 |
+
return self.check_node()
|
| 33 |
+
|
| 34 |
+
def check_state_key(self, key):
|
| 35 |
+
"""Block special attributes/methods from being set in a newly created
|
| 36 |
+
object, to prevent user-controlled methods from being called during
|
| 37 |
+
deserialization"""
|
| 38 |
+
if self.get_state_keys_blacklist_regexp().match(key):
|
| 39 |
+
raise ConstructorError(None, None,
|
| 40 |
+
"blacklisted key '%s' in instance state found" % (key,), None)
|
| 41 |
+
|
| 42 |
+
def get_data(self):
|
| 43 |
+
# Construct and return the next document.
|
| 44 |
+
if self.check_node():
|
| 45 |
+
return self.construct_document(self.get_node())
|
| 46 |
+
|
| 47 |
+
def get_single_data(self):
|
| 48 |
+
# Ensure that the stream contains a single document and construct it.
|
| 49 |
+
node = self.get_single_node()
|
| 50 |
+
if node is not None:
|
| 51 |
+
return self.construct_document(node)
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
def construct_document(self, node):
|
| 55 |
+
data = self.construct_object(node)
|
| 56 |
+
while self.state_generators:
|
| 57 |
+
state_generators = self.state_generators
|
| 58 |
+
self.state_generators = []
|
| 59 |
+
for generator in state_generators:
|
| 60 |
+
for dummy in generator:
|
| 61 |
+
pass
|
| 62 |
+
self.constructed_objects = {}
|
| 63 |
+
self.recursive_objects = {}
|
| 64 |
+
self.deep_construct = False
|
| 65 |
+
return data
|
| 66 |
+
|
| 67 |
+
def construct_object(self, node, deep=False):
|
| 68 |
+
if node in self.constructed_objects:
|
| 69 |
+
return self.constructed_objects[node]
|
| 70 |
+
if deep:
|
| 71 |
+
old_deep = self.deep_construct
|
| 72 |
+
self.deep_construct = True
|
| 73 |
+
if node in self.recursive_objects:
|
| 74 |
+
raise ConstructorError(None, None,
|
| 75 |
+
"found unconstructable recursive node", node.start_mark)
|
| 76 |
+
self.recursive_objects[node] = None
|
| 77 |
+
constructor = None
|
| 78 |
+
tag_suffix = None
|
| 79 |
+
if node.tag in self.yaml_constructors:
|
| 80 |
+
constructor = self.yaml_constructors[node.tag]
|
| 81 |
+
else:
|
| 82 |
+
for tag_prefix in self.yaml_multi_constructors:
|
| 83 |
+
if tag_prefix is not None and node.tag.startswith(tag_prefix):
|
| 84 |
+
tag_suffix = node.tag[len(tag_prefix):]
|
| 85 |
+
constructor = self.yaml_multi_constructors[tag_prefix]
|
| 86 |
+
break
|
| 87 |
+
else:
|
| 88 |
+
if None in self.yaml_multi_constructors:
|
| 89 |
+
tag_suffix = node.tag
|
| 90 |
+
constructor = self.yaml_multi_constructors[None]
|
| 91 |
+
elif None in self.yaml_constructors:
|
| 92 |
+
constructor = self.yaml_constructors[None]
|
| 93 |
+
elif isinstance(node, ScalarNode):
|
| 94 |
+
constructor = self.__class__.construct_scalar
|
| 95 |
+
elif isinstance(node, SequenceNode):
|
| 96 |
+
constructor = self.__class__.construct_sequence
|
| 97 |
+
elif isinstance(node, MappingNode):
|
| 98 |
+
constructor = self.__class__.construct_mapping
|
| 99 |
+
if tag_suffix is None:
|
| 100 |
+
data = constructor(self, node)
|
| 101 |
+
else:
|
| 102 |
+
data = constructor(self, tag_suffix, node)
|
| 103 |
+
if isinstance(data, types.GeneratorType):
|
| 104 |
+
generator = data
|
| 105 |
+
data = next(generator)
|
| 106 |
+
if self.deep_construct:
|
| 107 |
+
for dummy in generator:
|
| 108 |
+
pass
|
| 109 |
+
else:
|
| 110 |
+
self.state_generators.append(generator)
|
| 111 |
+
self.constructed_objects[node] = data
|
| 112 |
+
del self.recursive_objects[node]
|
| 113 |
+
if deep:
|
| 114 |
+
self.deep_construct = old_deep
|
| 115 |
+
return data
|
| 116 |
+
|
| 117 |
+
def construct_scalar(self, node):
|
| 118 |
+
if not isinstance(node, ScalarNode):
|
| 119 |
+
raise ConstructorError(None, None,
|
| 120 |
+
"expected a scalar node, but found %s" % node.id,
|
| 121 |
+
node.start_mark)
|
| 122 |
+
return node.value
|
| 123 |
+
|
| 124 |
+
def construct_sequence(self, node, deep=False):
|
| 125 |
+
if not isinstance(node, SequenceNode):
|
| 126 |
+
raise ConstructorError(None, None,
|
| 127 |
+
"expected a sequence node, but found %s" % node.id,
|
| 128 |
+
node.start_mark)
|
| 129 |
+
return [self.construct_object(child, deep=deep)
|
| 130 |
+
for child in node.value]
|
| 131 |
+
|
| 132 |
+
def construct_mapping(self, node, deep=False):
|
| 133 |
+
if not isinstance(node, MappingNode):
|
| 134 |
+
raise ConstructorError(None, None,
|
| 135 |
+
"expected a mapping node, but found %s" % node.id,
|
| 136 |
+
node.start_mark)
|
| 137 |
+
mapping = {}
|
| 138 |
+
for key_node, value_node in node.value:
|
| 139 |
+
key = self.construct_object(key_node, deep=deep)
|
| 140 |
+
if not isinstance(key, collections.abc.Hashable):
|
| 141 |
+
raise ConstructorError("while constructing a mapping", node.start_mark,
|
| 142 |
+
"found unhashable key", key_node.start_mark)
|
| 143 |
+
value = self.construct_object(value_node, deep=deep)
|
| 144 |
+
mapping[key] = value
|
| 145 |
+
return mapping
|
| 146 |
+
|
| 147 |
+
def construct_pairs(self, node, deep=False):
|
| 148 |
+
if not isinstance(node, MappingNode):
|
| 149 |
+
raise ConstructorError(None, None,
|
| 150 |
+
"expected a mapping node, but found %s" % node.id,
|
| 151 |
+
node.start_mark)
|
| 152 |
+
pairs = []
|
| 153 |
+
for key_node, value_node in node.value:
|
| 154 |
+
key = self.construct_object(key_node, deep=deep)
|
| 155 |
+
value = self.construct_object(value_node, deep=deep)
|
| 156 |
+
pairs.append((key, value))
|
| 157 |
+
return pairs
|
| 158 |
+
|
| 159 |
+
@classmethod
|
| 160 |
+
def add_constructor(cls, tag, constructor):
|
| 161 |
+
if not 'yaml_constructors' in cls.__dict__:
|
| 162 |
+
cls.yaml_constructors = cls.yaml_constructors.copy()
|
| 163 |
+
cls.yaml_constructors[tag] = constructor
|
| 164 |
+
|
| 165 |
+
@classmethod
|
| 166 |
+
def add_multi_constructor(cls, tag_prefix, multi_constructor):
|
| 167 |
+
if not 'yaml_multi_constructors' in cls.__dict__:
|
| 168 |
+
cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy()
|
| 169 |
+
cls.yaml_multi_constructors[tag_prefix] = multi_constructor
|
| 170 |
+
|
| 171 |
+
class SafeConstructor(BaseConstructor):
|
| 172 |
+
|
| 173 |
+
def construct_scalar(self, node):
|
| 174 |
+
if isinstance(node, MappingNode):
|
| 175 |
+
for key_node, value_node in node.value:
|
| 176 |
+
if key_node.tag == 'tag:yaml.org,2002:value':
|
| 177 |
+
return self.construct_scalar(value_node)
|
| 178 |
+
return super().construct_scalar(node)
|
| 179 |
+
|
| 180 |
+
def flatten_mapping(self, node):
|
| 181 |
+
merge = []
|
| 182 |
+
index = 0
|
| 183 |
+
while index < len(node.value):
|
| 184 |
+
key_node, value_node = node.value[index]
|
| 185 |
+
if key_node.tag == 'tag:yaml.org,2002:merge':
|
| 186 |
+
del node.value[index]
|
| 187 |
+
if isinstance(value_node, MappingNode):
|
| 188 |
+
self.flatten_mapping(value_node)
|
| 189 |
+
merge.extend(value_node.value)
|
| 190 |
+
elif isinstance(value_node, SequenceNode):
|
| 191 |
+
submerge = []
|
| 192 |
+
for subnode in value_node.value:
|
| 193 |
+
if not isinstance(subnode, MappingNode):
|
| 194 |
+
raise ConstructorError("while constructing a mapping",
|
| 195 |
+
node.start_mark,
|
| 196 |
+
"expected a mapping for merging, but found %s"
|
| 197 |
+
% subnode.id, subnode.start_mark)
|
| 198 |
+
self.flatten_mapping(subnode)
|
| 199 |
+
submerge.append(subnode.value)
|
| 200 |
+
submerge.reverse()
|
| 201 |
+
for value in submerge:
|
| 202 |
+
merge.extend(value)
|
| 203 |
+
else:
|
| 204 |
+
raise ConstructorError("while constructing a mapping", node.start_mark,
|
| 205 |
+
"expected a mapping or list of mappings for merging, but found %s"
|
| 206 |
+
% value_node.id, value_node.start_mark)
|
| 207 |
+
elif key_node.tag == 'tag:yaml.org,2002:value':
|
| 208 |
+
key_node.tag = 'tag:yaml.org,2002:str'
|
| 209 |
+
index += 1
|
| 210 |
+
else:
|
| 211 |
+
index += 1
|
| 212 |
+
if merge:
|
| 213 |
+
node.value = merge + node.value
|
| 214 |
+
|
| 215 |
+
def construct_mapping(self, node, deep=False):
|
| 216 |
+
if isinstance(node, MappingNode):
|
| 217 |
+
self.flatten_mapping(node)
|
| 218 |
+
return super().construct_mapping(node, deep=deep)
|
| 219 |
+
|
| 220 |
+
def construct_yaml_null(self, node):
|
| 221 |
+
self.construct_scalar(node)
|
| 222 |
+
return None
|
| 223 |
+
|
| 224 |
+
bool_values = {
|
| 225 |
+
'yes': True,
|
| 226 |
+
'no': False,
|
| 227 |
+
'true': True,
|
| 228 |
+
'false': False,
|
| 229 |
+
'on': True,
|
| 230 |
+
'off': False,
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
def construct_yaml_bool(self, node):
|
| 234 |
+
value = self.construct_scalar(node)
|
| 235 |
+
return self.bool_values[value.lower()]
|
| 236 |
+
|
| 237 |
+
def construct_yaml_int(self, node):
|
| 238 |
+
value = self.construct_scalar(node)
|
| 239 |
+
value = value.replace('_', '')
|
| 240 |
+
sign = +1
|
| 241 |
+
if value[0] == '-':
|
| 242 |
+
sign = -1
|
| 243 |
+
if value[0] in '+-':
|
| 244 |
+
value = value[1:]
|
| 245 |
+
if value == '0':
|
| 246 |
+
return 0
|
| 247 |
+
elif value.startswith('0b'):
|
| 248 |
+
return sign*int(value[2:], 2)
|
| 249 |
+
elif value.startswith('0x'):
|
| 250 |
+
return sign*int(value[2:], 16)
|
| 251 |
+
elif value[0] == '0':
|
| 252 |
+
return sign*int(value, 8)
|
| 253 |
+
elif ':' in value:
|
| 254 |
+
digits = [int(part) for part in value.split(':')]
|
| 255 |
+
digits.reverse()
|
| 256 |
+
base = 1
|
| 257 |
+
value = 0
|
| 258 |
+
for digit in digits:
|
| 259 |
+
value += digit*base
|
| 260 |
+
base *= 60
|
| 261 |
+
return sign*value
|
| 262 |
+
else:
|
| 263 |
+
return sign*int(value)
|
| 264 |
+
|
| 265 |
+
inf_value = 1e300
|
| 266 |
+
while inf_value != inf_value*inf_value:
|
| 267 |
+
inf_value *= inf_value
|
| 268 |
+
nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99).
|
| 269 |
+
|
| 270 |
+
def construct_yaml_float(self, node):
|
| 271 |
+
value = self.construct_scalar(node)
|
| 272 |
+
value = value.replace('_', '').lower()
|
| 273 |
+
sign = +1
|
| 274 |
+
if value[0] == '-':
|
| 275 |
+
sign = -1
|
| 276 |
+
if value[0] in '+-':
|
| 277 |
+
value = value[1:]
|
| 278 |
+
if value == '.inf':
|
| 279 |
+
return sign*self.inf_value
|
| 280 |
+
elif value == '.nan':
|
| 281 |
+
return self.nan_value
|
| 282 |
+
elif ':' in value:
|
| 283 |
+
digits = [float(part) for part in value.split(':')]
|
| 284 |
+
digits.reverse()
|
| 285 |
+
base = 1
|
| 286 |
+
value = 0.0
|
| 287 |
+
for digit in digits:
|
| 288 |
+
value += digit*base
|
| 289 |
+
base *= 60
|
| 290 |
+
return sign*value
|
| 291 |
+
else:
|
| 292 |
+
return sign*float(value)
|
| 293 |
+
|
| 294 |
+
def construct_yaml_binary(self, node):
|
| 295 |
+
try:
|
| 296 |
+
value = self.construct_scalar(node).encode('ascii')
|
| 297 |
+
except UnicodeEncodeError as exc:
|
| 298 |
+
raise ConstructorError(None, None,
|
| 299 |
+
"failed to convert base64 data into ascii: %s" % exc,
|
| 300 |
+
node.start_mark)
|
| 301 |
+
try:
|
| 302 |
+
if hasattr(base64, 'decodebytes'):
|
| 303 |
+
return base64.decodebytes(value)
|
| 304 |
+
else:
|
| 305 |
+
return base64.decodestring(value)
|
| 306 |
+
except binascii.Error as exc:
|
| 307 |
+
raise ConstructorError(None, None,
|
| 308 |
+
"failed to decode base64 data: %s" % exc, node.start_mark)
|
| 309 |
+
|
| 310 |
+
timestamp_regexp = re.compile(
|
| 311 |
+
r'''^(?P<year>[0-9][0-9][0-9][0-9])
|
| 312 |
+
-(?P<month>[0-9][0-9]?)
|
| 313 |
+
-(?P<day>[0-9][0-9]?)
|
| 314 |
+
(?:(?:[Tt]|[ \t]+)
|
| 315 |
+
(?P<hour>[0-9][0-9]?)
|
| 316 |
+
:(?P<minute>[0-9][0-9])
|
| 317 |
+
:(?P<second>[0-9][0-9])
|
| 318 |
+
(?:\.(?P<fraction>[0-9]*))?
|
| 319 |
+
(?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
|
| 320 |
+
(?::(?P<tz_minute>[0-9][0-9]))?))?)?$''', re.X)
|
| 321 |
+
|
| 322 |
+
def construct_yaml_timestamp(self, node):
|
| 323 |
+
value = self.construct_scalar(node)
|
| 324 |
+
match = self.timestamp_regexp.match(node.value)
|
| 325 |
+
values = match.groupdict()
|
| 326 |
+
year = int(values['year'])
|
| 327 |
+
month = int(values['month'])
|
| 328 |
+
day = int(values['day'])
|
| 329 |
+
if not values['hour']:
|
| 330 |
+
return datetime.date(year, month, day)
|
| 331 |
+
hour = int(values['hour'])
|
| 332 |
+
minute = int(values['minute'])
|
| 333 |
+
second = int(values['second'])
|
| 334 |
+
fraction = 0
|
| 335 |
+
tzinfo = None
|
| 336 |
+
if values['fraction']:
|
| 337 |
+
fraction = values['fraction'][:6]
|
| 338 |
+
while len(fraction) < 6:
|
| 339 |
+
fraction += '0'
|
| 340 |
+
fraction = int(fraction)
|
| 341 |
+
if values['tz_sign']:
|
| 342 |
+
tz_hour = int(values['tz_hour'])
|
| 343 |
+
tz_minute = int(values['tz_minute'] or 0)
|
| 344 |
+
delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
|
| 345 |
+
if values['tz_sign'] == '-':
|
| 346 |
+
delta = -delta
|
| 347 |
+
tzinfo = datetime.timezone(delta)
|
| 348 |
+
elif values['tz']:
|
| 349 |
+
tzinfo = datetime.timezone.utc
|
| 350 |
+
return datetime.datetime(year, month, day, hour, minute, second, fraction,
|
| 351 |
+
tzinfo=tzinfo)
|
| 352 |
+
|
| 353 |
+
def construct_yaml_omap(self, node):
|
| 354 |
+
# Note: we do not check for duplicate keys, because it's too
|
| 355 |
+
# CPU-expensive.
|
| 356 |
+
omap = []
|
| 357 |
+
yield omap
|
| 358 |
+
if not isinstance(node, SequenceNode):
|
| 359 |
+
raise ConstructorError("while constructing an ordered map", node.start_mark,
|
| 360 |
+
"expected a sequence, but found %s" % node.id, node.start_mark)
|
| 361 |
+
for subnode in node.value:
|
| 362 |
+
if not isinstance(subnode, MappingNode):
|
| 363 |
+
raise ConstructorError("while constructing an ordered map", node.start_mark,
|
| 364 |
+
"expected a mapping of length 1, but found %s" % subnode.id,
|
| 365 |
+
subnode.start_mark)
|
| 366 |
+
if len(subnode.value) != 1:
|
| 367 |
+
raise ConstructorError("while constructing an ordered map", node.start_mark,
|
| 368 |
+
"expected a single mapping item, but found %d items" % len(subnode.value),
|
| 369 |
+
subnode.start_mark)
|
| 370 |
+
key_node, value_node = subnode.value[0]
|
| 371 |
+
key = self.construct_object(key_node)
|
| 372 |
+
value = self.construct_object(value_node)
|
| 373 |
+
omap.append((key, value))
|
| 374 |
+
|
| 375 |
+
def construct_yaml_pairs(self, node):
|
| 376 |
+
# Note: the same code as `construct_yaml_omap`.
|
| 377 |
+
pairs = []
|
| 378 |
+
yield pairs
|
| 379 |
+
if not isinstance(node, SequenceNode):
|
| 380 |
+
raise ConstructorError("while constructing pairs", node.start_mark,
|
| 381 |
+
"expected a sequence, but found %s" % node.id, node.start_mark)
|
| 382 |
+
for subnode in node.value:
|
| 383 |
+
if not isinstance(subnode, MappingNode):
|
| 384 |
+
raise ConstructorError("while constructing pairs", node.start_mark,
|
| 385 |
+
"expected a mapping of length 1, but found %s" % subnode.id,
|
| 386 |
+
subnode.start_mark)
|
| 387 |
+
if len(subnode.value) != 1:
|
| 388 |
+
raise ConstructorError("while constructing pairs", node.start_mark,
|
| 389 |
+
"expected a single mapping item, but found %d items" % len(subnode.value),
|
| 390 |
+
subnode.start_mark)
|
| 391 |
+
key_node, value_node = subnode.value[0]
|
| 392 |
+
key = self.construct_object(key_node)
|
| 393 |
+
value = self.construct_object(value_node)
|
| 394 |
+
pairs.append((key, value))
|
| 395 |
+
|
| 396 |
+
def construct_yaml_set(self, node):
|
| 397 |
+
data = set()
|
| 398 |
+
yield data
|
| 399 |
+
value = self.construct_mapping(node)
|
| 400 |
+
data.update(value)
|
| 401 |
+
|
| 402 |
+
def construct_yaml_str(self, node):
|
| 403 |
+
return self.construct_scalar(node)
|
| 404 |
+
|
| 405 |
+
def construct_yaml_seq(self, node):
|
| 406 |
+
data = []
|
| 407 |
+
yield data
|
| 408 |
+
data.extend(self.construct_sequence(node))
|
| 409 |
+
|
| 410 |
+
def construct_yaml_map(self, node):
|
| 411 |
+
data = {}
|
| 412 |
+
yield data
|
| 413 |
+
value = self.construct_mapping(node)
|
| 414 |
+
data.update(value)
|
| 415 |
+
|
| 416 |
+
def construct_yaml_object(self, node, cls):
|
| 417 |
+
data = cls.__new__(cls)
|
| 418 |
+
yield data
|
| 419 |
+
if hasattr(data, '__setstate__'):
|
| 420 |
+
state = self.construct_mapping(node, deep=True)
|
| 421 |
+
data.__setstate__(state)
|
| 422 |
+
else:
|
| 423 |
+
state = self.construct_mapping(node)
|
| 424 |
+
data.__dict__.update(state)
|
| 425 |
+
|
| 426 |
+
def construct_undefined(self, node):
|
| 427 |
+
raise ConstructorError(None, None,
|
| 428 |
+
"could not determine a constructor for the tag %r" % node.tag,
|
| 429 |
+
node.start_mark)
|
| 430 |
+
|
| 431 |
+
SafeConstructor.add_constructor(
|
| 432 |
+
'tag:yaml.org,2002:null',
|
| 433 |
+
SafeConstructor.construct_yaml_null)
|
| 434 |
+
|
| 435 |
+
SafeConstructor.add_constructor(
|
| 436 |
+
'tag:yaml.org,2002:bool',
|
| 437 |
+
SafeConstructor.construct_yaml_bool)
|
| 438 |
+
|
| 439 |
+
SafeConstructor.add_constructor(
|
| 440 |
+
'tag:yaml.org,2002:int',
|
| 441 |
+
SafeConstructor.construct_yaml_int)
|
| 442 |
+
|
| 443 |
+
SafeConstructor.add_constructor(
|
| 444 |
+
'tag:yaml.org,2002:float',
|
| 445 |
+
SafeConstructor.construct_yaml_float)
|
| 446 |
+
|
| 447 |
+
SafeConstructor.add_constructor(
|
| 448 |
+
'tag:yaml.org,2002:binary',
|
| 449 |
+
SafeConstructor.construct_yaml_binary)
|
| 450 |
+
|
| 451 |
+
SafeConstructor.add_constructor(
|
| 452 |
+
'tag:yaml.org,2002:timestamp',
|
| 453 |
+
SafeConstructor.construct_yaml_timestamp)
|
| 454 |
+
|
| 455 |
+
SafeConstructor.add_constructor(
|
| 456 |
+
'tag:yaml.org,2002:omap',
|
| 457 |
+
SafeConstructor.construct_yaml_omap)
|
| 458 |
+
|
| 459 |
+
SafeConstructor.add_constructor(
|
| 460 |
+
'tag:yaml.org,2002:pairs',
|
| 461 |
+
SafeConstructor.construct_yaml_pairs)
|
| 462 |
+
|
| 463 |
+
SafeConstructor.add_constructor(
|
| 464 |
+
'tag:yaml.org,2002:set',
|
| 465 |
+
SafeConstructor.construct_yaml_set)
|
| 466 |
+
|
| 467 |
+
SafeConstructor.add_constructor(
|
| 468 |
+
'tag:yaml.org,2002:str',
|
| 469 |
+
SafeConstructor.construct_yaml_str)
|
| 470 |
+
|
| 471 |
+
SafeConstructor.add_constructor(
|
| 472 |
+
'tag:yaml.org,2002:seq',
|
| 473 |
+
SafeConstructor.construct_yaml_seq)
|
| 474 |
+
|
| 475 |
+
SafeConstructor.add_constructor(
|
| 476 |
+
'tag:yaml.org,2002:map',
|
| 477 |
+
SafeConstructor.construct_yaml_map)
|
| 478 |
+
|
| 479 |
+
SafeConstructor.add_constructor(None,
|
| 480 |
+
SafeConstructor.construct_undefined)
|
| 481 |
+
|
| 482 |
+
class FullConstructor(SafeConstructor):
|
| 483 |
+
# 'extend' is blacklisted because it is used by
|
| 484 |
+
# construct_python_object_apply to add `listitems` to a newly generate
|
| 485 |
+
# python instance
|
| 486 |
+
def get_state_keys_blacklist(self):
|
| 487 |
+
return ['^extend$', '^__.*__$']
|
| 488 |
+
|
| 489 |
+
def get_state_keys_blacklist_regexp(self):
|
| 490 |
+
if not hasattr(self, 'state_keys_blacklist_regexp'):
|
| 491 |
+
self.state_keys_blacklist_regexp = re.compile('(' + '|'.join(self.get_state_keys_blacklist()) + ')')
|
| 492 |
+
return self.state_keys_blacklist_regexp
|
| 493 |
+
|
| 494 |
+
def construct_python_str(self, node):
|
| 495 |
+
return self.construct_scalar(node)
|
| 496 |
+
|
| 497 |
+
def construct_python_unicode(self, node):
|
| 498 |
+
return self.construct_scalar(node)
|
| 499 |
+
|
| 500 |
+
def construct_python_bytes(self, node):
|
| 501 |
+
try:
|
| 502 |
+
value = self.construct_scalar(node).encode('ascii')
|
| 503 |
+
except UnicodeEncodeError as exc:
|
| 504 |
+
raise ConstructorError(None, None,
|
| 505 |
+
"failed to convert base64 data into ascii: %s" % exc,
|
| 506 |
+
node.start_mark)
|
| 507 |
+
try:
|
| 508 |
+
if hasattr(base64, 'decodebytes'):
|
| 509 |
+
return base64.decodebytes(value)
|
| 510 |
+
else:
|
| 511 |
+
return base64.decodestring(value)
|
| 512 |
+
except binascii.Error as exc:
|
| 513 |
+
raise ConstructorError(None, None,
|
| 514 |
+
"failed to decode base64 data: %s" % exc, node.start_mark)
|
| 515 |
+
|
| 516 |
+
def construct_python_long(self, node):
|
| 517 |
+
return self.construct_yaml_int(node)
|
| 518 |
+
|
| 519 |
+
def construct_python_complex(self, node):
|
| 520 |
+
return complex(self.construct_scalar(node))
|
| 521 |
+
|
| 522 |
+
def construct_python_tuple(self, node):
|
| 523 |
+
return tuple(self.construct_sequence(node))
|
| 524 |
+
|
| 525 |
+
def find_python_module(self, name, mark, unsafe=False):
|
| 526 |
+
if not name:
|
| 527 |
+
raise ConstructorError("while constructing a Python module", mark,
|
| 528 |
+
"expected non-empty name appended to the tag", mark)
|
| 529 |
+
if unsafe:
|
| 530 |
+
try:
|
| 531 |
+
__import__(name)
|
| 532 |
+
except ImportError as exc:
|
| 533 |
+
raise ConstructorError("while constructing a Python module", mark,
|
| 534 |
+
"cannot find module %r (%s)" % (name, exc), mark)
|
| 535 |
+
if name not in sys.modules:
|
| 536 |
+
raise ConstructorError("while constructing a Python module", mark,
|
| 537 |
+
"module %r is not imported" % name, mark)
|
| 538 |
+
return sys.modules[name]
|
| 539 |
+
|
| 540 |
+
def find_python_name(self, name, mark, unsafe=False):
|
| 541 |
+
if not name:
|
| 542 |
+
raise ConstructorError("while constructing a Python object", mark,
|
| 543 |
+
"expected non-empty name appended to the tag", mark)
|
| 544 |
+
if '.' in name:
|
| 545 |
+
module_name, object_name = name.rsplit('.', 1)
|
| 546 |
+
else:
|
| 547 |
+
module_name = 'builtins'
|
| 548 |
+
object_name = name
|
| 549 |
+
if unsafe:
|
| 550 |
+
try:
|
| 551 |
+
__import__(module_name)
|
| 552 |
+
except ImportError as exc:
|
| 553 |
+
raise ConstructorError("while constructing a Python object", mark,
|
| 554 |
+
"cannot find module %r (%s)" % (module_name, exc), mark)
|
| 555 |
+
if module_name not in sys.modules:
|
| 556 |
+
raise ConstructorError("while constructing a Python object", mark,
|
| 557 |
+
"module %r is not imported" % module_name, mark)
|
| 558 |
+
module = sys.modules[module_name]
|
| 559 |
+
if not hasattr(module, object_name):
|
| 560 |
+
raise ConstructorError("while constructing a Python object", mark,
|
| 561 |
+
"cannot find %r in the module %r"
|
| 562 |
+
% (object_name, module.__name__), mark)
|
| 563 |
+
return getattr(module, object_name)
|
| 564 |
+
|
| 565 |
+
def construct_python_name(self, suffix, node):
|
| 566 |
+
value = self.construct_scalar(node)
|
| 567 |
+
if value:
|
| 568 |
+
raise ConstructorError("while constructing a Python name", node.start_mark,
|
| 569 |
+
"expected the empty value, but found %r" % value, node.start_mark)
|
| 570 |
+
return self.find_python_name(suffix, node.start_mark)
|
| 571 |
+
|
| 572 |
+
def construct_python_module(self, suffix, node):
|
| 573 |
+
value = self.construct_scalar(node)
|
| 574 |
+
if value:
|
| 575 |
+
raise ConstructorError("while constructing a Python module", node.start_mark,
|
| 576 |
+
"expected the empty value, but found %r" % value, node.start_mark)
|
| 577 |
+
return self.find_python_module(suffix, node.start_mark)
|
| 578 |
+
|
| 579 |
+
def make_python_instance(self, suffix, node,
|
| 580 |
+
args=None, kwds=None, newobj=False, unsafe=False):
|
| 581 |
+
if not args:
|
| 582 |
+
args = []
|
| 583 |
+
if not kwds:
|
| 584 |
+
kwds = {}
|
| 585 |
+
cls = self.find_python_name(suffix, node.start_mark)
|
| 586 |
+
if not (unsafe or isinstance(cls, type)):
|
| 587 |
+
raise ConstructorError("while constructing a Python instance", node.start_mark,
|
| 588 |
+
"expected a class, but found %r" % type(cls),
|
| 589 |
+
node.start_mark)
|
| 590 |
+
if newobj and isinstance(cls, type):
|
| 591 |
+
return cls.__new__(cls, *args, **kwds)
|
| 592 |
+
else:
|
| 593 |
+
return cls(*args, **kwds)
|
| 594 |
+
|
| 595 |
+
def set_python_instance_state(self, instance, state, unsafe=False):
|
| 596 |
+
if hasattr(instance, '__setstate__'):
|
| 597 |
+
instance.__setstate__(state)
|
| 598 |
+
else:
|
| 599 |
+
slotstate = {}
|
| 600 |
+
if isinstance(state, tuple) and len(state) == 2:
|
| 601 |
+
state, slotstate = state
|
| 602 |
+
if hasattr(instance, '__dict__'):
|
| 603 |
+
if not unsafe and state:
|
| 604 |
+
for key in state.keys():
|
| 605 |
+
self.check_state_key(key)
|
| 606 |
+
instance.__dict__.update(state)
|
| 607 |
+
elif state:
|
| 608 |
+
slotstate.update(state)
|
| 609 |
+
for key, value in slotstate.items():
|
| 610 |
+
if not unsafe:
|
| 611 |
+
self.check_state_key(key)
|
| 612 |
+
setattr(instance, key, value)
|
| 613 |
+
|
| 614 |
+
def construct_python_object(self, suffix, node):
|
| 615 |
+
# Format:
|
| 616 |
+
# !!python/object:module.name { ... state ... }
|
| 617 |
+
instance = self.make_python_instance(suffix, node, newobj=True)
|
| 618 |
+
yield instance
|
| 619 |
+
deep = hasattr(instance, '__setstate__')
|
| 620 |
+
state = self.construct_mapping(node, deep=deep)
|
| 621 |
+
self.set_python_instance_state(instance, state)
|
| 622 |
+
|
| 623 |
+
def construct_python_object_apply(self, suffix, node, newobj=False):
|
| 624 |
+
# Format:
|
| 625 |
+
# !!python/object/apply # (or !!python/object/new)
|
| 626 |
+
# args: [ ... arguments ... ]
|
| 627 |
+
# kwds: { ... keywords ... }
|
| 628 |
+
# state: ... state ...
|
| 629 |
+
# listitems: [ ... listitems ... ]
|
| 630 |
+
# dictitems: { ... dictitems ... }
|
| 631 |
+
# or short format:
|
| 632 |
+
# !!python/object/apply [ ... arguments ... ]
|
| 633 |
+
# The difference between !!python/object/apply and !!python/object/new
|
| 634 |
+
# is how an object is created, check make_python_instance for details.
|
| 635 |
+
if isinstance(node, SequenceNode):
|
| 636 |
+
args = self.construct_sequence(node, deep=True)
|
| 637 |
+
kwds = {}
|
| 638 |
+
state = {}
|
| 639 |
+
listitems = []
|
| 640 |
+
dictitems = {}
|
| 641 |
+
else:
|
| 642 |
+
value = self.construct_mapping(node, deep=True)
|
| 643 |
+
args = value.get('args', [])
|
| 644 |
+
kwds = value.get('kwds', {})
|
| 645 |
+
state = value.get('state', {})
|
| 646 |
+
listitems = value.get('listitems', [])
|
| 647 |
+
dictitems = value.get('dictitems', {})
|
| 648 |
+
instance = self.make_python_instance(suffix, node, args, kwds, newobj)
|
| 649 |
+
if state:
|
| 650 |
+
self.set_python_instance_state(instance, state)
|
| 651 |
+
if listitems:
|
| 652 |
+
instance.extend(listitems)
|
| 653 |
+
if dictitems:
|
| 654 |
+
for key in dictitems:
|
| 655 |
+
instance[key] = dictitems[key]
|
| 656 |
+
return instance
|
| 657 |
+
|
| 658 |
+
def construct_python_object_new(self, suffix, node):
|
| 659 |
+
return self.construct_python_object_apply(suffix, node, newobj=True)
|
| 660 |
+
|
| 661 |
+
FullConstructor.add_constructor(
|
| 662 |
+
'tag:yaml.org,2002:python/none',
|
| 663 |
+
FullConstructor.construct_yaml_null)
|
| 664 |
+
|
| 665 |
+
FullConstructor.add_constructor(
|
| 666 |
+
'tag:yaml.org,2002:python/bool',
|
| 667 |
+
FullConstructor.construct_yaml_bool)
|
| 668 |
+
|
| 669 |
+
FullConstructor.add_constructor(
|
| 670 |
+
'tag:yaml.org,2002:python/str',
|
| 671 |
+
FullConstructor.construct_python_str)
|
| 672 |
+
|
| 673 |
+
FullConstructor.add_constructor(
|
| 674 |
+
'tag:yaml.org,2002:python/unicode',
|
| 675 |
+
FullConstructor.construct_python_unicode)
|
| 676 |
+
|
| 677 |
+
FullConstructor.add_constructor(
|
| 678 |
+
'tag:yaml.org,2002:python/bytes',
|
| 679 |
+
FullConstructor.construct_python_bytes)
|
| 680 |
+
|
| 681 |
+
FullConstructor.add_constructor(
|
| 682 |
+
'tag:yaml.org,2002:python/int',
|
| 683 |
+
FullConstructor.construct_yaml_int)
|
| 684 |
+
|
| 685 |
+
FullConstructor.add_constructor(
|
| 686 |
+
'tag:yaml.org,2002:python/long',
|
| 687 |
+
FullConstructor.construct_python_long)
|
| 688 |
+
|
| 689 |
+
FullConstructor.add_constructor(
|
| 690 |
+
'tag:yaml.org,2002:python/float',
|
| 691 |
+
FullConstructor.construct_yaml_float)
|
| 692 |
+
|
| 693 |
+
FullConstructor.add_constructor(
|
| 694 |
+
'tag:yaml.org,2002:python/complex',
|
| 695 |
+
FullConstructor.construct_python_complex)
|
| 696 |
+
|
| 697 |
+
FullConstructor.add_constructor(
|
| 698 |
+
'tag:yaml.org,2002:python/list',
|
| 699 |
+
FullConstructor.construct_yaml_seq)
|
| 700 |
+
|
| 701 |
+
FullConstructor.add_constructor(
|
| 702 |
+
'tag:yaml.org,2002:python/tuple',
|
| 703 |
+
FullConstructor.construct_python_tuple)
|
| 704 |
+
|
| 705 |
+
FullConstructor.add_constructor(
|
| 706 |
+
'tag:yaml.org,2002:python/dict',
|
| 707 |
+
FullConstructor.construct_yaml_map)
|
| 708 |
+
|
| 709 |
+
FullConstructor.add_multi_constructor(
|
| 710 |
+
'tag:yaml.org,2002:python/name:',
|
| 711 |
+
FullConstructor.construct_python_name)
|
| 712 |
+
|
| 713 |
+
class UnsafeConstructor(FullConstructor):
|
| 714 |
+
|
| 715 |
+
def find_python_module(self, name, mark):
|
| 716 |
+
return super(UnsafeConstructor, self).find_python_module(name, mark, unsafe=True)
|
| 717 |
+
|
| 718 |
+
def find_python_name(self, name, mark):
|
| 719 |
+
return super(UnsafeConstructor, self).find_python_name(name, mark, unsafe=True)
|
| 720 |
+
|
| 721 |
+
def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False):
|
| 722 |
+
return super(UnsafeConstructor, self).make_python_instance(
|
| 723 |
+
suffix, node, args, kwds, newobj, unsafe=True)
|
| 724 |
+
|
| 725 |
+
def set_python_instance_state(self, instance, state):
|
| 726 |
+
return super(UnsafeConstructor, self).set_python_instance_state(
|
| 727 |
+
instance, state, unsafe=True)
|
| 728 |
+
|
| 729 |
+
UnsafeConstructor.add_multi_constructor(
|
| 730 |
+
'tag:yaml.org,2002:python/module:',
|
| 731 |
+
UnsafeConstructor.construct_python_module)
|
| 732 |
+
|
| 733 |
+
UnsafeConstructor.add_multi_constructor(
|
| 734 |
+
'tag:yaml.org,2002:python/object:',
|
| 735 |
+
UnsafeConstructor.construct_python_object)
|
| 736 |
+
|
| 737 |
+
UnsafeConstructor.add_multi_constructor(
|
| 738 |
+
'tag:yaml.org,2002:python/object/new:',
|
| 739 |
+
UnsafeConstructor.construct_python_object_new)
|
| 740 |
+
|
| 741 |
+
UnsafeConstructor.add_multi_constructor(
|
| 742 |
+
'tag:yaml.org,2002:python/object/apply:',
|
| 743 |
+
UnsafeConstructor.construct_python_object_apply)
|
| 744 |
+
|
| 745 |
+
# Constructor is same as UnsafeConstructor. Need to leave this in place in case
|
| 746 |
+
# people have extended it directly.
|
| 747 |
+
class Constructor(UnsafeConstructor):
|
| 748 |
+
pass
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/cyaml.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
__all__ = [
|
| 3 |
+
'CBaseLoader', 'CSafeLoader', 'CFullLoader', 'CUnsafeLoader', 'CLoader',
|
| 4 |
+
'CBaseDumper', 'CSafeDumper', 'CDumper'
|
| 5 |
+
]
|
| 6 |
+
|
| 7 |
+
from yaml._yaml import CParser, CEmitter
|
| 8 |
+
|
| 9 |
+
from .constructor import *
|
| 10 |
+
|
| 11 |
+
from .serializer import *
|
| 12 |
+
from .representer import *
|
| 13 |
+
|
| 14 |
+
from .resolver import *
|
| 15 |
+
|
| 16 |
+
class CBaseLoader(CParser, BaseConstructor, BaseResolver):
|
| 17 |
+
|
| 18 |
+
def __init__(self, stream):
|
| 19 |
+
CParser.__init__(self, stream)
|
| 20 |
+
BaseConstructor.__init__(self)
|
| 21 |
+
BaseResolver.__init__(self)
|
| 22 |
+
|
| 23 |
+
class CSafeLoader(CParser, SafeConstructor, Resolver):
|
| 24 |
+
|
| 25 |
+
def __init__(self, stream):
|
| 26 |
+
CParser.__init__(self, stream)
|
| 27 |
+
SafeConstructor.__init__(self)
|
| 28 |
+
Resolver.__init__(self)
|
| 29 |
+
|
| 30 |
+
class CFullLoader(CParser, FullConstructor, Resolver):
|
| 31 |
+
|
| 32 |
+
def __init__(self, stream):
|
| 33 |
+
CParser.__init__(self, stream)
|
| 34 |
+
FullConstructor.__init__(self)
|
| 35 |
+
Resolver.__init__(self)
|
| 36 |
+
|
| 37 |
+
class CUnsafeLoader(CParser, UnsafeConstructor, Resolver):
|
| 38 |
+
|
| 39 |
+
def __init__(self, stream):
|
| 40 |
+
CParser.__init__(self, stream)
|
| 41 |
+
UnsafeConstructor.__init__(self)
|
| 42 |
+
Resolver.__init__(self)
|
| 43 |
+
|
| 44 |
+
class CLoader(CParser, Constructor, Resolver):
|
| 45 |
+
|
| 46 |
+
def __init__(self, stream):
|
| 47 |
+
CParser.__init__(self, stream)
|
| 48 |
+
Constructor.__init__(self)
|
| 49 |
+
Resolver.__init__(self)
|
| 50 |
+
|
| 51 |
+
class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver):
|
| 52 |
+
|
| 53 |
+
def __init__(self, stream,
|
| 54 |
+
default_style=None, default_flow_style=False,
|
| 55 |
+
canonical=None, indent=None, width=None,
|
| 56 |
+
allow_unicode=None, line_break=None,
|
| 57 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
| 58 |
+
version=None, tags=None, sort_keys=True):
|
| 59 |
+
CEmitter.__init__(self, stream, canonical=canonical,
|
| 60 |
+
indent=indent, width=width, encoding=encoding,
|
| 61 |
+
allow_unicode=allow_unicode, line_break=line_break,
|
| 62 |
+
explicit_start=explicit_start, explicit_end=explicit_end,
|
| 63 |
+
version=version, tags=tags)
|
| 64 |
+
Representer.__init__(self, default_style=default_style,
|
| 65 |
+
default_flow_style=default_flow_style, sort_keys=sort_keys)
|
| 66 |
+
Resolver.__init__(self)
|
| 67 |
+
|
| 68 |
+
class CSafeDumper(CEmitter, SafeRepresenter, Resolver):
|
| 69 |
+
|
| 70 |
+
def __init__(self, stream,
|
| 71 |
+
default_style=None, default_flow_style=False,
|
| 72 |
+
canonical=None, indent=None, width=None,
|
| 73 |
+
allow_unicode=None, line_break=None,
|
| 74 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
| 75 |
+
version=None, tags=None, sort_keys=True):
|
| 76 |
+
CEmitter.__init__(self, stream, canonical=canonical,
|
| 77 |
+
indent=indent, width=width, encoding=encoding,
|
| 78 |
+
allow_unicode=allow_unicode, line_break=line_break,
|
| 79 |
+
explicit_start=explicit_start, explicit_end=explicit_end,
|
| 80 |
+
version=version, tags=tags)
|
| 81 |
+
SafeRepresenter.__init__(self, default_style=default_style,
|
| 82 |
+
default_flow_style=default_flow_style, sort_keys=sort_keys)
|
| 83 |
+
Resolver.__init__(self)
|
| 84 |
+
|
| 85 |
+
class CDumper(CEmitter, Serializer, Representer, Resolver):
|
| 86 |
+
|
| 87 |
+
def __init__(self, stream,
|
| 88 |
+
default_style=None, default_flow_style=False,
|
| 89 |
+
canonical=None, indent=None, width=None,
|
| 90 |
+
allow_unicode=None, line_break=None,
|
| 91 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
| 92 |
+
version=None, tags=None, sort_keys=True):
|
| 93 |
+
CEmitter.__init__(self, stream, canonical=canonical,
|
| 94 |
+
indent=indent, width=width, encoding=encoding,
|
| 95 |
+
allow_unicode=allow_unicode, line_break=line_break,
|
| 96 |
+
explicit_start=explicit_start, explicit_end=explicit_end,
|
| 97 |
+
version=version, tags=tags)
|
| 98 |
+
Representer.__init__(self, default_style=default_style,
|
| 99 |
+
default_flow_style=default_flow_style, sort_keys=sort_keys)
|
| 100 |
+
Resolver.__init__(self)
|
| 101 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/dumper.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
__all__ = ['BaseDumper', 'SafeDumper', 'Dumper']
|
| 3 |
+
|
| 4 |
+
from .emitter import *
|
| 5 |
+
from .serializer import *
|
| 6 |
+
from .representer import *
|
| 7 |
+
from .resolver import *
|
| 8 |
+
|
| 9 |
+
class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver):
|
| 10 |
+
|
| 11 |
+
def __init__(self, stream,
|
| 12 |
+
default_style=None, default_flow_style=False,
|
| 13 |
+
canonical=None, indent=None, width=None,
|
| 14 |
+
allow_unicode=None, line_break=None,
|
| 15 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
| 16 |
+
version=None, tags=None, sort_keys=True):
|
| 17 |
+
Emitter.__init__(self, stream, canonical=canonical,
|
| 18 |
+
indent=indent, width=width,
|
| 19 |
+
allow_unicode=allow_unicode, line_break=line_break)
|
| 20 |
+
Serializer.__init__(self, encoding=encoding,
|
| 21 |
+
explicit_start=explicit_start, explicit_end=explicit_end,
|
| 22 |
+
version=version, tags=tags)
|
| 23 |
+
Representer.__init__(self, default_style=default_style,
|
| 24 |
+
default_flow_style=default_flow_style, sort_keys=sort_keys)
|
| 25 |
+
Resolver.__init__(self)
|
| 26 |
+
|
| 27 |
+
class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver):
|
| 28 |
+
|
| 29 |
+
def __init__(self, stream,
|
| 30 |
+
default_style=None, default_flow_style=False,
|
| 31 |
+
canonical=None, indent=None, width=None,
|
| 32 |
+
allow_unicode=None, line_break=None,
|
| 33 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
| 34 |
+
version=None, tags=None, sort_keys=True):
|
| 35 |
+
Emitter.__init__(self, stream, canonical=canonical,
|
| 36 |
+
indent=indent, width=width,
|
| 37 |
+
allow_unicode=allow_unicode, line_break=line_break)
|
| 38 |
+
Serializer.__init__(self, encoding=encoding,
|
| 39 |
+
explicit_start=explicit_start, explicit_end=explicit_end,
|
| 40 |
+
version=version, tags=tags)
|
| 41 |
+
SafeRepresenter.__init__(self, default_style=default_style,
|
| 42 |
+
default_flow_style=default_flow_style, sort_keys=sort_keys)
|
| 43 |
+
Resolver.__init__(self)
|
| 44 |
+
|
| 45 |
+
class Dumper(Emitter, Serializer, Representer, Resolver):
|
| 46 |
+
|
| 47 |
+
def __init__(self, stream,
|
| 48 |
+
default_style=None, default_flow_style=False,
|
| 49 |
+
canonical=None, indent=None, width=None,
|
| 50 |
+
allow_unicode=None, line_break=None,
|
| 51 |
+
encoding=None, explicit_start=None, explicit_end=None,
|
| 52 |
+
version=None, tags=None, sort_keys=True):
|
| 53 |
+
Emitter.__init__(self, stream, canonical=canonical,
|
| 54 |
+
indent=indent, width=width,
|
| 55 |
+
allow_unicode=allow_unicode, line_break=line_break)
|
| 56 |
+
Serializer.__init__(self, encoding=encoding,
|
| 57 |
+
explicit_start=explicit_start, explicit_end=explicit_end,
|
| 58 |
+
version=version, tags=tags)
|
| 59 |
+
Representer.__init__(self, default_style=default_style,
|
| 60 |
+
default_flow_style=default_flow_style, sort_keys=sort_keys)
|
| 61 |
+
Resolver.__init__(self)
|
| 62 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/emitter.py
AD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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Emitter expects events obeying the following grammar:
|
| 3 |
+
# stream ::= STREAM-START document* STREAM-END
|
| 4 |
+
# document ::= DOCUMENT-START node DOCUMENT-END
|
| 5 |
+
# node ::= SCALAR | sequence | mapping
|
| 6 |
+
# sequence ::= SEQUENCE-START node* SEQUENCE-END
|
| 7 |
+
# mapping ::= MAPPING-START (node node)* MAPPING-END
|
| 8 |
+
|
| 9 |
+
__all__ = ['Emitter', 'EmitterError']
|
| 10 |
+
|
| 11 |
+
from .error import YAMLError
|
| 12 |
+
from .events import *
|
| 13 |
+
|
| 14 |
+
class EmitterError(YAMLError):
|
| 15 |
+
pass
|
| 16 |
+
|
| 17 |
+
class ScalarAnalysis:
|
| 18 |
+
def __init__(self, scalar, empty, multiline,
|
| 19 |
+
allow_flow_plain, allow_block_plain,
|
| 20 |
+
allow_single_quoted, allow_double_quoted,
|
| 21 |
+
allow_block):
|
| 22 |
+
self.scalar = scalar
|
| 23 |
+
self.empty = empty
|
| 24 |
+
self.multiline = multiline
|
| 25 |
+
self.allow_flow_plain = allow_flow_plain
|
| 26 |
+
self.allow_block_plain = allow_block_plain
|
| 27 |
+
self.allow_single_quoted = allow_single_quoted
|
| 28 |
+
self.allow_double_quoted = allow_double_quoted
|
| 29 |
+
self.allow_block = allow_block
|
| 30 |
+
|
| 31 |
+
class Emitter:
|
| 32 |
+
|
| 33 |
+
DEFAULT_TAG_PREFIXES = {
|
| 34 |
+
'!' : '!',
|
| 35 |
+
'tag:yaml.org,2002:' : '!!',
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
def __init__(self, stream, canonical=None, indent=None, width=None,
|
| 39 |
+
allow_unicode=None, line_break=None):
|
| 40 |
+
|
| 41 |
+
# The stream should have the methods `write` and possibly `flush`.
|
| 42 |
+
self.stream = stream
|
| 43 |
+
|
| 44 |
+
# Encoding can be overridden by STREAM-START.
|
| 45 |
+
self.encoding = None
|
| 46 |
+
|
| 47 |
+
# Emitter is a state machine with a stack of states to handle nested
|
| 48 |
+
# structures.
|
| 49 |
+
self.states = []
|
| 50 |
+
self.state = self.expect_stream_start
|
| 51 |
+
|
| 52 |
+
# Current event and the event queue.
|
| 53 |
+
self.events = []
|
| 54 |
+
self.event = None
|
| 55 |
+
|
| 56 |
+
# The current indentation level and the stack of previous indents.
|
| 57 |
+
self.indents = []
|
| 58 |
+
self.indent = None
|
| 59 |
+
|
| 60 |
+
# Flow level.
|
| 61 |
+
self.flow_level = 0
|
| 62 |
+
|
| 63 |
+
# Contexts.
|
| 64 |
+
self.root_context = False
|
| 65 |
+
self.sequence_context = False
|
| 66 |
+
self.mapping_context = False
|
| 67 |
+
self.simple_key_context = False
|
| 68 |
+
|
| 69 |
+
# Characteristics of the last emitted character:
|
| 70 |
+
# - current position.
|
| 71 |
+
# - is it a whitespace?
|
| 72 |
+
# - is it an indention character
|
| 73 |
+
# (indentation space, '-', '?', or ':')?
|
| 74 |
+
self.line = 0
|
| 75 |
+
self.column = 0
|
| 76 |
+
self.whitespace = True
|
| 77 |
+
self.indention = True
|
| 78 |
+
|
| 79 |
+
# Whether the document requires an explicit document indicator
|
| 80 |
+
self.open_ended = False
|
| 81 |
+
|
| 82 |
+
# Formatting details.
|
| 83 |
+
self.canonical = canonical
|
| 84 |
+
self.allow_unicode = allow_unicode
|
| 85 |
+
self.best_indent = 2
|
| 86 |
+
if indent and 1 < indent < 10:
|
| 87 |
+
self.best_indent = indent
|
| 88 |
+
self.best_width = 80
|
| 89 |
+
if width and width > self.best_indent*2:
|
| 90 |
+
self.best_width = width
|
| 91 |
+
self.best_line_break = '\n'
|
| 92 |
+
if line_break in ['\r', '\n', '\r\n']:
|
| 93 |
+
self.best_line_break = line_break
|
| 94 |
+
|
| 95 |
+
# Tag prefixes.
|
| 96 |
+
self.tag_prefixes = None
|
| 97 |
+
|
| 98 |
+
# Prepared anchor and tag.
|
| 99 |
+
self.prepared_anchor = None
|
| 100 |
+
self.prepared_tag = None
|
| 101 |
+
|
| 102 |
+
# Scalar analysis and style.
|
| 103 |
+
self.analysis = None
|
| 104 |
+
self.style = None
|
| 105 |
+
|
| 106 |
+
def dispose(self):
|
| 107 |
+
# Reset the state attributes (to clear self-references)
|
| 108 |
+
self.states = []
|
| 109 |
+
self.state = None
|
| 110 |
+
|
| 111 |
+
def emit(self, event):
|
| 112 |
+
self.events.append(event)
|
| 113 |
+
while not self.need_more_events():
|
| 114 |
+
self.event = self.events.pop(0)
|
| 115 |
+
self.state()
|
| 116 |
+
self.event = None
|
| 117 |
+
|
| 118 |
+
# In some cases, we wait for a few next events before emitting.
|
| 119 |
+
|
| 120 |
+
def need_more_events(self):
|
| 121 |
+
if not self.events:
|
| 122 |
+
return True
|
| 123 |
+
event = self.events[0]
|
| 124 |
+
if isinstance(event, DocumentStartEvent):
|
| 125 |
+
return self.need_events(1)
|
| 126 |
+
elif isinstance(event, SequenceStartEvent):
|
| 127 |
+
return self.need_events(2)
|
| 128 |
+
elif isinstance(event, MappingStartEvent):
|
| 129 |
+
return self.need_events(3)
|
| 130 |
+
else:
|
| 131 |
+
return False
|
| 132 |
+
|
| 133 |
+
def need_events(self, count):
|
| 134 |
+
level = 0
|
| 135 |
+
for event in self.events[1:]:
|
| 136 |
+
if isinstance(event, (DocumentStartEvent, CollectionStartEvent)):
|
| 137 |
+
level += 1
|
| 138 |
+
elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)):
|
| 139 |
+
level -= 1
|
| 140 |
+
elif isinstance(event, StreamEndEvent):
|
| 141 |
+
level = -1
|
| 142 |
+
if level < 0:
|
| 143 |
+
return False
|
| 144 |
+
return (len(self.events) < count+1)
|
| 145 |
+
|
| 146 |
+
def increase_indent(self, flow=False, indentless=False):
|
| 147 |
+
self.indents.append(self.indent)
|
| 148 |
+
if self.indent is None:
|
| 149 |
+
if flow:
|
| 150 |
+
self.indent = self.best_indent
|
| 151 |
+
else:
|
| 152 |
+
self.indent = 0
|
| 153 |
+
elif not indentless:
|
| 154 |
+
self.indent += self.best_indent
|
| 155 |
+
|
| 156 |
+
# States.
|
| 157 |
+
|
| 158 |
+
# Stream handlers.
|
| 159 |
+
|
| 160 |
+
def expect_stream_start(self):
|
| 161 |
+
if isinstance(self.event, StreamStartEvent):
|
| 162 |
+
if self.event.encoding and not hasattr(self.stream, 'encoding'):
|
| 163 |
+
self.encoding = self.event.encoding
|
| 164 |
+
self.write_stream_start()
|
| 165 |
+
self.state = self.expect_first_document_start
|
| 166 |
+
else:
|
| 167 |
+
raise EmitterError("expected StreamStartEvent, but got %s"
|
| 168 |
+
% self.event)
|
| 169 |
+
|
| 170 |
+
def expect_nothing(self):
|
| 171 |
+
raise EmitterError("expected nothing, but got %s" % self.event)
|
| 172 |
+
|
| 173 |
+
# Document handlers.
|
| 174 |
+
|
| 175 |
+
def expect_first_document_start(self):
|
| 176 |
+
return self.expect_document_start(first=True)
|
| 177 |
+
|
| 178 |
+
def expect_document_start(self, first=False):
|
| 179 |
+
if isinstance(self.event, DocumentStartEvent):
|
| 180 |
+
if (self.event.version or self.event.tags) and self.open_ended:
|
| 181 |
+
self.write_indicator('...', True)
|
| 182 |
+
self.write_indent()
|
| 183 |
+
if self.event.version:
|
| 184 |
+
version_text = self.prepare_version(self.event.version)
|
| 185 |
+
self.write_version_directive(version_text)
|
| 186 |
+
self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy()
|
| 187 |
+
if self.event.tags:
|
| 188 |
+
handles = sorted(self.event.tags.keys())
|
| 189 |
+
for handle in handles:
|
| 190 |
+
prefix = self.event.tags[handle]
|
| 191 |
+
self.tag_prefixes[prefix] = handle
|
| 192 |
+
handle_text = self.prepare_tag_handle(handle)
|
| 193 |
+
prefix_text = self.prepare_tag_prefix(prefix)
|
| 194 |
+
self.write_tag_directive(handle_text, prefix_text)
|
| 195 |
+
implicit = (first and not self.event.explicit and not self.canonical
|
| 196 |
+
and not self.event.version and not self.event.tags
|
| 197 |
+
and not self.check_empty_document())
|
| 198 |
+
if not implicit:
|
| 199 |
+
self.write_indent()
|
| 200 |
+
self.write_indicator('---', True)
|
| 201 |
+
if self.canonical:
|
| 202 |
+
self.write_indent()
|
| 203 |
+
self.state = self.expect_document_root
|
| 204 |
+
elif isinstance(self.event, StreamEndEvent):
|
| 205 |
+
if self.open_ended:
|
| 206 |
+
self.write_indicator('...', True)
|
| 207 |
+
self.write_indent()
|
| 208 |
+
self.write_stream_end()
|
| 209 |
+
self.state = self.expect_nothing
|
| 210 |
+
else:
|
| 211 |
+
raise EmitterError("expected DocumentStartEvent, but got %s"
|
| 212 |
+
% self.event)
|
| 213 |
+
|
| 214 |
+
def expect_document_end(self):
|
| 215 |
+
if isinstance(self.event, DocumentEndEvent):
|
| 216 |
+
self.write_indent()
|
| 217 |
+
if self.event.explicit:
|
| 218 |
+
self.write_indicator('...', True)
|
| 219 |
+
self.write_indent()
|
| 220 |
+
self.flush_stream()
|
| 221 |
+
self.state = self.expect_document_start
|
| 222 |
+
else:
|
| 223 |
+
raise EmitterError("expected DocumentEndEvent, but got %s"
|
| 224 |
+
% self.event)
|
| 225 |
+
|
| 226 |
+
def expect_document_root(self):
|
| 227 |
+
self.states.append(self.expect_document_end)
|
| 228 |
+
self.expect_node(root=True)
|
| 229 |
+
|
| 230 |
+
# Node handlers.
|
| 231 |
+
|
| 232 |
+
def expect_node(self, root=False, sequence=False, mapping=False,
|
| 233 |
+
simple_key=False):
|
| 234 |
+
self.root_context = root
|
| 235 |
+
self.sequence_context = sequence
|
| 236 |
+
self.mapping_context = mapping
|
| 237 |
+
self.simple_key_context = simple_key
|
| 238 |
+
if isinstance(self.event, AliasEvent):
|
| 239 |
+
self.expect_alias()
|
| 240 |
+
elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)):
|
| 241 |
+
self.process_anchor('&')
|
| 242 |
+
self.process_tag()
|
| 243 |
+
if isinstance(self.event, ScalarEvent):
|
| 244 |
+
self.expect_scalar()
|
| 245 |
+
elif isinstance(self.event, SequenceStartEvent):
|
| 246 |
+
if self.flow_level or self.canonical or self.event.flow_style \
|
| 247 |
+
or self.check_empty_sequence():
|
| 248 |
+
self.expect_flow_sequence()
|
| 249 |
+
else:
|
| 250 |
+
self.expect_block_sequence()
|
| 251 |
+
elif isinstance(self.event, MappingStartEvent):
|
| 252 |
+
if self.flow_level or self.canonical or self.event.flow_style \
|
| 253 |
+
or self.check_empty_mapping():
|
| 254 |
+
self.expect_flow_mapping()
|
| 255 |
+
else:
|
| 256 |
+
self.expect_block_mapping()
|
| 257 |
+
else:
|
| 258 |
+
raise EmitterError("expected NodeEvent, but got %s" % self.event)
|
| 259 |
+
|
| 260 |
+
def expect_alias(self):
|
| 261 |
+
if self.event.anchor is None:
|
| 262 |
+
raise EmitterError("anchor is not specified for alias")
|
| 263 |
+
self.process_anchor('*')
|
| 264 |
+
self.state = self.states.pop()
|
| 265 |
+
|
| 266 |
+
def expect_scalar(self):
|
| 267 |
+
self.increase_indent(flow=True)
|
| 268 |
+
self.process_scalar()
|
| 269 |
+
self.indent = self.indents.pop()
|
| 270 |
+
self.state = self.states.pop()
|
| 271 |
+
|
| 272 |
+
# Flow sequence handlers.
|
| 273 |
+
|
| 274 |
+
def expect_flow_sequence(self):
|
| 275 |
+
self.write_indicator('[', True, whitespace=True)
|
| 276 |
+
self.flow_level += 1
|
| 277 |
+
self.increase_indent(flow=True)
|
| 278 |
+
self.state = self.expect_first_flow_sequence_item
|
| 279 |
+
|
| 280 |
+
def expect_first_flow_sequence_item(self):
|
| 281 |
+
if isinstance(self.event, SequenceEndEvent):
|
| 282 |
+
self.indent = self.indents.pop()
|
| 283 |
+
self.flow_level -= 1
|
| 284 |
+
self.write_indicator(']', False)
|
| 285 |
+
self.state = self.states.pop()
|
| 286 |
+
else:
|
| 287 |
+
if self.canonical or self.column > self.best_width:
|
| 288 |
+
self.write_indent()
|
| 289 |
+
self.states.append(self.expect_flow_sequence_item)
|
| 290 |
+
self.expect_node(sequence=True)
|
| 291 |
+
|
| 292 |
+
def expect_flow_sequence_item(self):
|
| 293 |
+
if isinstance(self.event, SequenceEndEvent):
|
| 294 |
+
self.indent = self.indents.pop()
|
| 295 |
+
self.flow_level -= 1
|
| 296 |
+
if self.canonical:
|
| 297 |
+
self.write_indicator(',', False)
|
| 298 |
+
self.write_indent()
|
| 299 |
+
self.write_indicator(']', False)
|
| 300 |
+
self.state = self.states.pop()
|
| 301 |
+
else:
|
| 302 |
+
self.write_indicator(',', False)
|
| 303 |
+
if self.canonical or self.column > self.best_width:
|
| 304 |
+
self.write_indent()
|
| 305 |
+
self.states.append(self.expect_flow_sequence_item)
|
| 306 |
+
self.expect_node(sequence=True)
|
| 307 |
+
|
| 308 |
+
# Flow mapping handlers.
|
| 309 |
+
|
| 310 |
+
def expect_flow_mapping(self):
|
| 311 |
+
self.write_indicator('{', True, whitespace=True)
|
| 312 |
+
self.flow_level += 1
|
| 313 |
+
self.increase_indent(flow=True)
|
| 314 |
+
self.state = self.expect_first_flow_mapping_key
|
| 315 |
+
|
| 316 |
+
def expect_first_flow_mapping_key(self):
|
| 317 |
+
if isinstance(self.event, MappingEndEvent):
|
| 318 |
+
self.indent = self.indents.pop()
|
| 319 |
+
self.flow_level -= 1
|
| 320 |
+
self.write_indicator('}', False)
|
| 321 |
+
self.state = self.states.pop()
|
| 322 |
+
else:
|
| 323 |
+
if self.canonical or self.column > self.best_width:
|
| 324 |
+
self.write_indent()
|
| 325 |
+
if not self.canonical and self.check_simple_key():
|
| 326 |
+
self.states.append(self.expect_flow_mapping_simple_value)
|
| 327 |
+
self.expect_node(mapping=True, simple_key=True)
|
| 328 |
+
else:
|
| 329 |
+
self.write_indicator('?', True)
|
| 330 |
+
self.states.append(self.expect_flow_mapping_value)
|
| 331 |
+
self.expect_node(mapping=True)
|
| 332 |
+
|
| 333 |
+
def expect_flow_mapping_key(self):
|
| 334 |
+
if isinstance(self.event, MappingEndEvent):
|
| 335 |
+
self.indent = self.indents.pop()
|
| 336 |
+
self.flow_level -= 1
|
| 337 |
+
if self.canonical:
|
| 338 |
+
self.write_indicator(',', False)
|
| 339 |
+
self.write_indent()
|
| 340 |
+
self.write_indicator('}', False)
|
| 341 |
+
self.state = self.states.pop()
|
| 342 |
+
else:
|
| 343 |
+
self.write_indicator(',', False)
|
| 344 |
+
if self.canonical or self.column > self.best_width:
|
| 345 |
+
self.write_indent()
|
| 346 |
+
if not self.canonical and self.check_simple_key():
|
| 347 |
+
self.states.append(self.expect_flow_mapping_simple_value)
|
| 348 |
+
self.expect_node(mapping=True, simple_key=True)
|
| 349 |
+
else:
|
| 350 |
+
self.write_indicator('?', True)
|
| 351 |
+
self.states.append(self.expect_flow_mapping_value)
|
| 352 |
+
self.expect_node(mapping=True)
|
| 353 |
+
|
| 354 |
+
def expect_flow_mapping_simple_value(self):
|
| 355 |
+
self.write_indicator(':', False)
|
| 356 |
+
self.states.append(self.expect_flow_mapping_key)
|
| 357 |
+
self.expect_node(mapping=True)
|
| 358 |
+
|
| 359 |
+
def expect_flow_mapping_value(self):
|
| 360 |
+
if self.canonical or self.column > self.best_width:
|
| 361 |
+
self.write_indent()
|
| 362 |
+
self.write_indicator(':', True)
|
| 363 |
+
self.states.append(self.expect_flow_mapping_key)
|
| 364 |
+
self.expect_node(mapping=True)
|
| 365 |
+
|
| 366 |
+
# Block sequence handlers.
|
| 367 |
+
|
| 368 |
+
def expect_block_sequence(self):
|
| 369 |
+
indentless = (self.mapping_context and not self.indention)
|
| 370 |
+
self.increase_indent(flow=False, indentless=indentless)
|
| 371 |
+
self.state = self.expect_first_block_sequence_item
|
| 372 |
+
|
| 373 |
+
def expect_first_block_sequence_item(self):
|
| 374 |
+
return self.expect_block_sequence_item(first=True)
|
| 375 |
+
|
| 376 |
+
def expect_block_sequence_item(self, first=False):
|
| 377 |
+
if not first and isinstance(self.event, SequenceEndEvent):
|
| 378 |
+
self.indent = self.indents.pop()
|
| 379 |
+
self.state = self.states.pop()
|
| 380 |
+
else:
|
| 381 |
+
self.write_indent()
|
| 382 |
+
self.write_indicator('-', True, indention=True)
|
| 383 |
+
self.states.append(self.expect_block_sequence_item)
|
| 384 |
+
self.expect_node(sequence=True)
|
| 385 |
+
|
| 386 |
+
# Block mapping handlers.
|
| 387 |
+
|
| 388 |
+
def expect_block_mapping(self):
|
| 389 |
+
self.increase_indent(flow=False)
|
| 390 |
+
self.state = self.expect_first_block_mapping_key
|
| 391 |
+
|
| 392 |
+
def expect_first_block_mapping_key(self):
|
| 393 |
+
return self.expect_block_mapping_key(first=True)
|
| 394 |
+
|
| 395 |
+
def expect_block_mapping_key(self, first=False):
|
| 396 |
+
if not first and isinstance(self.event, MappingEndEvent):
|
| 397 |
+
self.indent = self.indents.pop()
|
| 398 |
+
self.state = self.states.pop()
|
| 399 |
+
else:
|
| 400 |
+
self.write_indent()
|
| 401 |
+
if self.check_simple_key():
|
| 402 |
+
self.states.append(self.expect_block_mapping_simple_value)
|
| 403 |
+
self.expect_node(mapping=True, simple_key=True)
|
| 404 |
+
else:
|
| 405 |
+
self.write_indicator('?', True, indention=True)
|
| 406 |
+
self.states.append(self.expect_block_mapping_value)
|
| 407 |
+
self.expect_node(mapping=True)
|
| 408 |
+
|
| 409 |
+
def expect_block_mapping_simple_value(self):
|
| 410 |
+
self.write_indicator(':', False)
|
| 411 |
+
self.states.append(self.expect_block_mapping_key)
|
| 412 |
+
self.expect_node(mapping=True)
|
| 413 |
+
|
| 414 |
+
def expect_block_mapping_value(self):
|
| 415 |
+
self.write_indent()
|
| 416 |
+
self.write_indicator(':', True, indention=True)
|
| 417 |
+
self.states.append(self.expect_block_mapping_key)
|
| 418 |
+
self.expect_node(mapping=True)
|
| 419 |
+
|
| 420 |
+
# Checkers.
|
| 421 |
+
|
| 422 |
+
def check_empty_sequence(self):
|
| 423 |
+
return (isinstance(self.event, SequenceStartEvent) and self.events
|
| 424 |
+
and isinstance(self.events[0], SequenceEndEvent))
|
| 425 |
+
|
| 426 |
+
def check_empty_mapping(self):
|
| 427 |
+
return (isinstance(self.event, MappingStartEvent) and self.events
|
| 428 |
+
and isinstance(self.events[0], MappingEndEvent))
|
| 429 |
+
|
| 430 |
+
def check_empty_document(self):
|
| 431 |
+
if not isinstance(self.event, DocumentStartEvent) or not self.events:
|
| 432 |
+
return False
|
| 433 |
+
event = self.events[0]
|
| 434 |
+
return (isinstance(event, ScalarEvent) and event.anchor is None
|
| 435 |
+
and event.tag is None and event.implicit and event.value == '')
|
| 436 |
+
|
| 437 |
+
def check_simple_key(self):
|
| 438 |
+
length = 0
|
| 439 |
+
if isinstance(self.event, NodeEvent) and self.event.anchor is not None:
|
| 440 |
+
if self.prepared_anchor is None:
|
| 441 |
+
self.prepared_anchor = self.prepare_anchor(self.event.anchor)
|
| 442 |
+
length += len(self.prepared_anchor)
|
| 443 |
+
if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \
|
| 444 |
+
and self.event.tag is not None:
|
| 445 |
+
if self.prepared_tag is None:
|
| 446 |
+
self.prepared_tag = self.prepare_tag(self.event.tag)
|
| 447 |
+
length += len(self.prepared_tag)
|
| 448 |
+
if isinstance(self.event, ScalarEvent):
|
| 449 |
+
if self.analysis is None:
|
| 450 |
+
self.analysis = self.analyze_scalar(self.event.value)
|
| 451 |
+
length += len(self.analysis.scalar)
|
| 452 |
+
return (length < 128 and (isinstance(self.event, AliasEvent)
|
| 453 |
+
or (isinstance(self.event, ScalarEvent)
|
| 454 |
+
and not self.analysis.empty and not self.analysis.multiline)
|
| 455 |
+
or self.check_empty_sequence() or self.check_empty_mapping()))
|
| 456 |
+
|
| 457 |
+
# Anchor, Tag, and Scalar processors.
|
| 458 |
+
|
| 459 |
+
def process_anchor(self, indicator):
|
| 460 |
+
if self.event.anchor is None:
|
| 461 |
+
self.prepared_anchor = None
|
| 462 |
+
return
|
| 463 |
+
if self.prepared_anchor is None:
|
| 464 |
+
self.prepared_anchor = self.prepare_anchor(self.event.anchor)
|
| 465 |
+
if self.prepared_anchor:
|
| 466 |
+
self.write_indicator(indicator+self.prepared_anchor, True)
|
| 467 |
+
self.prepared_anchor = None
|
| 468 |
+
|
| 469 |
+
def process_tag(self):
|
| 470 |
+
tag = self.event.tag
|
| 471 |
+
if isinstance(self.event, ScalarEvent):
|
| 472 |
+
if self.style is None:
|
| 473 |
+
self.style = self.choose_scalar_style()
|
| 474 |
+
if ((not self.canonical or tag is None) and
|
| 475 |
+
((self.style == '' and self.event.implicit[0])
|
| 476 |
+
or (self.style != '' and self.event.implicit[1]))):
|
| 477 |
+
self.prepared_tag = None
|
| 478 |
+
return
|
| 479 |
+
if self.event.implicit[0] and tag is None:
|
| 480 |
+
tag = '!'
|
| 481 |
+
self.prepared_tag = None
|
| 482 |
+
else:
|
| 483 |
+
if (not self.canonical or tag is None) and self.event.implicit:
|
| 484 |
+
self.prepared_tag = None
|
| 485 |
+
return
|
| 486 |
+
if tag is None:
|
| 487 |
+
raise EmitterError("tag is not specified")
|
| 488 |
+
if self.prepared_tag is None:
|
| 489 |
+
self.prepared_tag = self.prepare_tag(tag)
|
| 490 |
+
if self.prepared_tag:
|
| 491 |
+
self.write_indicator(self.prepared_tag, True)
|
| 492 |
+
self.prepared_tag = None
|
| 493 |
+
|
| 494 |
+
def choose_scalar_style(self):
|
| 495 |
+
if self.analysis is None:
|
| 496 |
+
self.analysis = self.analyze_scalar(self.event.value)
|
| 497 |
+
if self.event.style == '"' or self.canonical:
|
| 498 |
+
return '"'
|
| 499 |
+
if not self.event.style and self.event.implicit[0]:
|
| 500 |
+
if (not (self.simple_key_context and
|
| 501 |
+
(self.analysis.empty or self.analysis.multiline))
|
| 502 |
+
and (self.flow_level and self.analysis.allow_flow_plain
|
| 503 |
+
or (not self.flow_level and self.analysis.allow_block_plain))):
|
| 504 |
+
return ''
|
| 505 |
+
if self.event.style and self.event.style in '|>':
|
| 506 |
+
if (not self.flow_level and not self.simple_key_context
|
| 507 |
+
and self.analysis.allow_block):
|
| 508 |
+
return self.event.style
|
| 509 |
+
if not self.event.style or self.event.style == '\'':
|
| 510 |
+
if (self.analysis.allow_single_quoted and
|
| 511 |
+
not (self.simple_key_context and self.analysis.multiline)):
|
| 512 |
+
return '\''
|
| 513 |
+
return '"'
|
| 514 |
+
|
| 515 |
+
def process_scalar(self):
|
| 516 |
+
if self.analysis is None:
|
| 517 |
+
self.analysis = self.analyze_scalar(self.event.value)
|
| 518 |
+
if self.style is None:
|
| 519 |
+
self.style = self.choose_scalar_style()
|
| 520 |
+
split = (not self.simple_key_context)
|
| 521 |
+
#if self.analysis.multiline and split \
|
| 522 |
+
# and (not self.style or self.style in '\'\"'):
|
| 523 |
+
# self.write_indent()
|
| 524 |
+
if self.style == '"':
|
| 525 |
+
self.write_double_quoted(self.analysis.scalar, split)
|
| 526 |
+
elif self.style == '\'':
|
| 527 |
+
self.write_single_quoted(self.analysis.scalar, split)
|
| 528 |
+
elif self.style == '>':
|
| 529 |
+
self.write_folded(self.analysis.scalar)
|
| 530 |
+
elif self.style == '|':
|
| 531 |
+
self.write_literal(self.analysis.scalar)
|
| 532 |
+
else:
|
| 533 |
+
self.write_plain(self.analysis.scalar, split)
|
| 534 |
+
self.analysis = None
|
| 535 |
+
self.style = None
|
| 536 |
+
|
| 537 |
+
# Analyzers.
|
| 538 |
+
|
| 539 |
+
def prepare_version(self, version):
|
| 540 |
+
major, minor = version
|
| 541 |
+
if major != 1:
|
| 542 |
+
raise EmitterError("unsupported YAML version: %d.%d" % (major, minor))
|
| 543 |
+
return '%d.%d' % (major, minor)
|
| 544 |
+
|
| 545 |
+
def prepare_tag_handle(self, handle):
|
| 546 |
+
if not handle:
|
| 547 |
+
raise EmitterError("tag handle must not be empty")
|
| 548 |
+
if handle[0] != '!' or handle[-1] != '!':
|
| 549 |
+
raise EmitterError("tag handle must start and end with '!': %r" % handle)
|
| 550 |
+
for ch in handle[1:-1]:
|
| 551 |
+
if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
|
| 552 |
+
or ch in '-_'):
|
| 553 |
+
raise EmitterError("invalid character %r in the tag handle: %r"
|
| 554 |
+
% (ch, handle))
|
| 555 |
+
return handle
|
| 556 |
+
|
| 557 |
+
def prepare_tag_prefix(self, prefix):
|
| 558 |
+
if not prefix:
|
| 559 |
+
raise EmitterError("tag prefix must not be empty")
|
| 560 |
+
chunks = []
|
| 561 |
+
start = end = 0
|
| 562 |
+
if prefix[0] == '!':
|
| 563 |
+
end = 1
|
| 564 |
+
while end < len(prefix):
|
| 565 |
+
ch = prefix[end]
|
| 566 |
+
if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
|
| 567 |
+
or ch in '-;/?!:@&=+$,_.~*\'()[]':
|
| 568 |
+
end += 1
|
| 569 |
+
else:
|
| 570 |
+
if start < end:
|
| 571 |
+
chunks.append(prefix[start:end])
|
| 572 |
+
start = end = end+1
|
| 573 |
+
data = ch.encode('utf-8')
|
| 574 |
+
for ch in data:
|
| 575 |
+
chunks.append('%%%02X' % ord(ch))
|
| 576 |
+
if start < end:
|
| 577 |
+
chunks.append(prefix[start:end])
|
| 578 |
+
return ''.join(chunks)
|
| 579 |
+
|
| 580 |
+
def prepare_tag(self, tag):
|
| 581 |
+
if not tag:
|
| 582 |
+
raise EmitterError("tag must not be empty")
|
| 583 |
+
if tag == '!':
|
| 584 |
+
return tag
|
| 585 |
+
handle = None
|
| 586 |
+
suffix = tag
|
| 587 |
+
prefixes = sorted(self.tag_prefixes.keys())
|
| 588 |
+
for prefix in prefixes:
|
| 589 |
+
if tag.startswith(prefix) \
|
| 590 |
+
and (prefix == '!' or len(prefix) < len(tag)):
|
| 591 |
+
handle = self.tag_prefixes[prefix]
|
| 592 |
+
suffix = tag[len(prefix):]
|
| 593 |
+
chunks = []
|
| 594 |
+
start = end = 0
|
| 595 |
+
while end < len(suffix):
|
| 596 |
+
ch = suffix[end]
|
| 597 |
+
if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
|
| 598 |
+
or ch in '-;/?:@&=+$,_.~*\'()[]' \
|
| 599 |
+
or (ch == '!' and handle != '!'):
|
| 600 |
+
end += 1
|
| 601 |
+
else:
|
| 602 |
+
if start < end:
|
| 603 |
+
chunks.append(suffix[start:end])
|
| 604 |
+
start = end = end+1
|
| 605 |
+
data = ch.encode('utf-8')
|
| 606 |
+
for ch in data:
|
| 607 |
+
chunks.append('%%%02X' % ch)
|
| 608 |
+
if start < end:
|
| 609 |
+
chunks.append(suffix[start:end])
|
| 610 |
+
suffix_text = ''.join(chunks)
|
| 611 |
+
if handle:
|
| 612 |
+
return '%s%s' % (handle, suffix_text)
|
| 613 |
+
else:
|
| 614 |
+
return '!<%s>' % suffix_text
|
| 615 |
+
|
| 616 |
+
def prepare_anchor(self, anchor):
|
| 617 |
+
if not anchor:
|
| 618 |
+
raise EmitterError("anchor must not be empty")
|
| 619 |
+
for ch in anchor:
|
| 620 |
+
if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
|
| 621 |
+
or ch in '-_'):
|
| 622 |
+
raise EmitterError("invalid character %r in the anchor: %r"
|
| 623 |
+
% (ch, anchor))
|
| 624 |
+
return anchor
|
| 625 |
+
|
| 626 |
+
def analyze_scalar(self, scalar):
|
| 627 |
+
|
| 628 |
+
# Empty scalar is a special case.
|
| 629 |
+
if not scalar:
|
| 630 |
+
return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
|
| 631 |
+
allow_flow_plain=False, allow_block_plain=True,
|
| 632 |
+
allow_single_quoted=True, allow_double_quoted=True,
|
| 633 |
+
allow_block=False)
|
| 634 |
+
|
| 635 |
+
# Indicators and special characters.
|
| 636 |
+
block_indicators = False
|
| 637 |
+
flow_indicators = False
|
| 638 |
+
line_breaks = False
|
| 639 |
+
special_characters = False
|
| 640 |
+
|
| 641 |
+
# Important whitespace combinations.
|
| 642 |
+
leading_space = False
|
| 643 |
+
leading_break = False
|
| 644 |
+
trailing_space = False
|
| 645 |
+
trailing_break = False
|
| 646 |
+
break_space = False
|
| 647 |
+
space_break = False
|
| 648 |
+
|
| 649 |
+
# Check document indicators.
|
| 650 |
+
if scalar.startswith('---') or scalar.startswith('...'):
|
| 651 |
+
block_indicators = True
|
| 652 |
+
flow_indicators = True
|
| 653 |
+
|
| 654 |
+
# First character or preceded by a whitespace.
|
| 655 |
+
preceded_by_whitespace = True
|
| 656 |
+
|
| 657 |
+
# Last character or followed by a whitespace.
|
| 658 |
+
followed_by_whitespace = (len(scalar) == 1 or
|
| 659 |
+
scalar[1] in '\0 \t\r\n\x85\u2028\u2029')
|
| 660 |
+
|
| 661 |
+
# The previous character is a space.
|
| 662 |
+
previous_space = False
|
| 663 |
+
|
| 664 |
+
# The previous character is a break.
|
| 665 |
+
previous_break = False
|
| 666 |
+
|
| 667 |
+
index = 0
|
| 668 |
+
while index < len(scalar):
|
| 669 |
+
ch = scalar[index]
|
| 670 |
+
|
| 671 |
+
# Check for indicators.
|
| 672 |
+
if index == 0:
|
| 673 |
+
# Leading indicators are special characters.
|
| 674 |
+
if ch in '#,[]{}&*!|>\'\"%@`':
|
| 675 |
+
flow_indicators = True
|
| 676 |
+
block_indicators = True
|
| 677 |
+
if ch in '?:':
|
| 678 |
+
flow_indicators = True
|
| 679 |
+
if followed_by_whitespace:
|
| 680 |
+
block_indicators = True
|
| 681 |
+
if ch == '-' and followed_by_whitespace:
|
| 682 |
+
flow_indicators = True
|
| 683 |
+
block_indicators = True
|
| 684 |
+
else:
|
| 685 |
+
# Some indicators cannot appear within a scalar as well.
|
| 686 |
+
if ch in ',?[]{}':
|
| 687 |
+
flow_indicators = True
|
| 688 |
+
if ch == ':':
|
| 689 |
+
flow_indicators = True
|
| 690 |
+
if followed_by_whitespace:
|
| 691 |
+
block_indicators = True
|
| 692 |
+
if ch == '#' and preceded_by_whitespace:
|
| 693 |
+
flow_indicators = True
|
| 694 |
+
block_indicators = True
|
| 695 |
+
|
| 696 |
+
# Check for line breaks, special, and unicode characters.
|
| 697 |
+
if ch in '\n\x85\u2028\u2029':
|
| 698 |
+
line_breaks = True
|
| 699 |
+
if not (ch == '\n' or '\x20' <= ch <= '\x7E'):
|
| 700 |
+
if (ch == '\x85' or '\xA0' <= ch <= '\uD7FF'
|
| 701 |
+
or '\uE000' <= ch <= '\uFFFD'
|
| 702 |
+
or '\U00010000' <= ch < '\U0010ffff') and ch != '\uFEFF':
|
| 703 |
+
unicode_characters = True
|
| 704 |
+
if not self.allow_unicode:
|
| 705 |
+
special_characters = True
|
| 706 |
+
else:
|
| 707 |
+
special_characters = True
|
| 708 |
+
|
| 709 |
+
# Detect important whitespace combinations.
|
| 710 |
+
if ch == ' ':
|
| 711 |
+
if index == 0:
|
| 712 |
+
leading_space = True
|
| 713 |
+
if index == len(scalar)-1:
|
| 714 |
+
trailing_space = True
|
| 715 |
+
if previous_break:
|
| 716 |
+
break_space = True
|
| 717 |
+
previous_space = True
|
| 718 |
+
previous_break = False
|
| 719 |
+
elif ch in '\n\x85\u2028\u2029':
|
| 720 |
+
if index == 0:
|
| 721 |
+
leading_break = True
|
| 722 |
+
if index == len(scalar)-1:
|
| 723 |
+
trailing_break = True
|
| 724 |
+
if previous_space:
|
| 725 |
+
space_break = True
|
| 726 |
+
previous_space = False
|
| 727 |
+
previous_break = True
|
| 728 |
+
else:
|
| 729 |
+
previous_space = False
|
| 730 |
+
previous_break = False
|
| 731 |
+
|
| 732 |
+
# Prepare for the next character.
|
| 733 |
+
index += 1
|
| 734 |
+
preceded_by_whitespace = (ch in '\0 \t\r\n\x85\u2028\u2029')
|
| 735 |
+
followed_by_whitespace = (index+1 >= len(scalar) or
|
| 736 |
+
scalar[index+1] in '\0 \t\r\n\x85\u2028\u2029')
|
| 737 |
+
|
| 738 |
+
# Let's decide what styles are allowed.
|
| 739 |
+
allow_flow_plain = True
|
| 740 |
+
allow_block_plain = True
|
| 741 |
+
allow_single_quoted = True
|
| 742 |
+
allow_double_quoted = True
|
| 743 |
+
allow_block = True
|
| 744 |
+
|
| 745 |
+
# Leading and trailing whitespaces are bad for plain scalars.
|
| 746 |
+
if (leading_space or leading_break
|
| 747 |
+
or trailing_space or trailing_break):
|
| 748 |
+
allow_flow_plain = allow_block_plain = False
|
| 749 |
+
|
| 750 |
+
# We do not permit trailing spaces for block scalars.
|
| 751 |
+
if trailing_space:
|
| 752 |
+
allow_block = False
|
| 753 |
+
|
| 754 |
+
# Spaces at the beginning of a new line are only acceptable for block
|
| 755 |
+
# scalars.
|
| 756 |
+
if break_space:
|
| 757 |
+
allow_flow_plain = allow_block_plain = allow_single_quoted = False
|
| 758 |
+
|
| 759 |
+
# Spaces followed by breaks, as well as special character are only
|
| 760 |
+
# allowed for double quoted scalars.
|
| 761 |
+
if space_break or special_characters:
|
| 762 |
+
allow_flow_plain = allow_block_plain = \
|
| 763 |
+
allow_single_quoted = allow_block = False
|
| 764 |
+
|
| 765 |
+
# Although the plain scalar writer supports breaks, we never emit
|
| 766 |
+
# multiline plain scalars.
|
| 767 |
+
if line_breaks:
|
| 768 |
+
allow_flow_plain = allow_block_plain = False
|
| 769 |
+
|
| 770 |
+
# Flow indicators are forbidden for flow plain scalars.
|
| 771 |
+
if flow_indicators:
|
| 772 |
+
allow_flow_plain = False
|
| 773 |
+
|
| 774 |
+
# Block indicators are forbidden for block plain scalars.
|
| 775 |
+
if block_indicators:
|
| 776 |
+
allow_block_plain = False
|
| 777 |
+
|
| 778 |
+
return ScalarAnalysis(scalar=scalar,
|
| 779 |
+
empty=False, multiline=line_breaks,
|
| 780 |
+
allow_flow_plain=allow_flow_plain,
|
| 781 |
+
allow_block_plain=allow_block_plain,
|
| 782 |
+
allow_single_quoted=allow_single_quoted,
|
| 783 |
+
allow_double_quoted=allow_double_quoted,
|
| 784 |
+
allow_block=allow_block)
|
| 785 |
+
|
| 786 |
+
# Writers.
|
| 787 |
+
|
| 788 |
+
def flush_stream(self):
|
| 789 |
+
if hasattr(self.stream, 'flush'):
|
| 790 |
+
self.stream.flush()
|
| 791 |
+
|
| 792 |
+
def write_stream_start(self):
|
| 793 |
+
# Write BOM if needed.
|
| 794 |
+
if self.encoding and self.encoding.startswith('utf-16'):
|
| 795 |
+
self.stream.write('\uFEFF'.encode(self.encoding))
|
| 796 |
+
|
| 797 |
+
def write_stream_end(self):
|
| 798 |
+
self.flush_stream()
|
| 799 |
+
|
| 800 |
+
def write_indicator(self, indicator, need_whitespace,
|
| 801 |
+
whitespace=False, indention=False):
|
| 802 |
+
if self.whitespace or not need_whitespace:
|
| 803 |
+
data = indicator
|
| 804 |
+
else:
|
| 805 |
+
data = ' '+indicator
|
| 806 |
+
self.whitespace = whitespace
|
| 807 |
+
self.indention = self.indention and indention
|
| 808 |
+
self.column += len(data)
|
| 809 |
+
self.open_ended = False
|
| 810 |
+
if self.encoding:
|
| 811 |
+
data = data.encode(self.encoding)
|
| 812 |
+
self.stream.write(data)
|
| 813 |
+
|
| 814 |
+
def write_indent(self):
|
| 815 |
+
indent = self.indent or 0
|
| 816 |
+
if not self.indention or self.column > indent \
|
| 817 |
+
or (self.column == indent and not self.whitespace):
|
| 818 |
+
self.write_line_break()
|
| 819 |
+
if self.column < indent:
|
| 820 |
+
self.whitespace = True
|
| 821 |
+
data = ' '*(indent-self.column)
|
| 822 |
+
self.column = indent
|
| 823 |
+
if self.encoding:
|
| 824 |
+
data = data.encode(self.encoding)
|
| 825 |
+
self.stream.write(data)
|
| 826 |
+
|
| 827 |
+
def write_line_break(self, data=None):
|
| 828 |
+
if data is None:
|
| 829 |
+
data = self.best_line_break
|
| 830 |
+
self.whitespace = True
|
| 831 |
+
self.indention = True
|
| 832 |
+
self.line += 1
|
| 833 |
+
self.column = 0
|
| 834 |
+
if self.encoding:
|
| 835 |
+
data = data.encode(self.encoding)
|
| 836 |
+
self.stream.write(data)
|
| 837 |
+
|
| 838 |
+
def write_version_directive(self, version_text):
|
| 839 |
+
data = '%%YAML %s' % version_text
|
| 840 |
+
if self.encoding:
|
| 841 |
+
data = data.encode(self.encoding)
|
| 842 |
+
self.stream.write(data)
|
| 843 |
+
self.write_line_break()
|
| 844 |
+
|
| 845 |
+
def write_tag_directive(self, handle_text, prefix_text):
|
| 846 |
+
data = '%%TAG %s %s' % (handle_text, prefix_text)
|
| 847 |
+
if self.encoding:
|
| 848 |
+
data = data.encode(self.encoding)
|
| 849 |
+
self.stream.write(data)
|
| 850 |
+
self.write_line_break()
|
| 851 |
+
|
| 852 |
+
# Scalar streams.
|
| 853 |
+
|
| 854 |
+
def write_single_quoted(self, text, split=True):
|
| 855 |
+
self.write_indicator('\'', True)
|
| 856 |
+
spaces = False
|
| 857 |
+
breaks = False
|
| 858 |
+
start = end = 0
|
| 859 |
+
while end <= len(text):
|
| 860 |
+
ch = None
|
| 861 |
+
if end < len(text):
|
| 862 |
+
ch = text[end]
|
| 863 |
+
if spaces:
|
| 864 |
+
if ch is None or ch != ' ':
|
| 865 |
+
if start+1 == end and self.column > self.best_width and split \
|
| 866 |
+
and start != 0 and end != len(text):
|
| 867 |
+
self.write_indent()
|
| 868 |
+
else:
|
| 869 |
+
data = text[start:end]
|
| 870 |
+
self.column += len(data)
|
| 871 |
+
if self.encoding:
|
| 872 |
+
data = data.encode(self.encoding)
|
| 873 |
+
self.stream.write(data)
|
| 874 |
+
start = end
|
| 875 |
+
elif breaks:
|
| 876 |
+
if ch is None or ch not in '\n\x85\u2028\u2029':
|
| 877 |
+
if text[start] == '\n':
|
| 878 |
+
self.write_line_break()
|
| 879 |
+
for br in text[start:end]:
|
| 880 |
+
if br == '\n':
|
| 881 |
+
self.write_line_break()
|
| 882 |
+
else:
|
| 883 |
+
self.write_line_break(br)
|
| 884 |
+
self.write_indent()
|
| 885 |
+
start = end
|
| 886 |
+
else:
|
| 887 |
+
if ch is None or ch in ' \n\x85\u2028\u2029' or ch == '\'':
|
| 888 |
+
if start < end:
|
| 889 |
+
data = text[start:end]
|
| 890 |
+
self.column += len(data)
|
| 891 |
+
if self.encoding:
|
| 892 |
+
data = data.encode(self.encoding)
|
| 893 |
+
self.stream.write(data)
|
| 894 |
+
start = end
|
| 895 |
+
if ch == '\'':
|
| 896 |
+
data = '\'\''
|
| 897 |
+
self.column += 2
|
| 898 |
+
if self.encoding:
|
| 899 |
+
data = data.encode(self.encoding)
|
| 900 |
+
self.stream.write(data)
|
| 901 |
+
start = end + 1
|
| 902 |
+
if ch is not None:
|
| 903 |
+
spaces = (ch == ' ')
|
| 904 |
+
breaks = (ch in '\n\x85\u2028\u2029')
|
| 905 |
+
end += 1
|
| 906 |
+
self.write_indicator('\'', False)
|
| 907 |
+
|
| 908 |
+
ESCAPE_REPLACEMENTS = {
|
| 909 |
+
'\0': '0',
|
| 910 |
+
'\x07': 'a',
|
| 911 |
+
'\x08': 'b',
|
| 912 |
+
'\x09': 't',
|
| 913 |
+
'\x0A': 'n',
|
| 914 |
+
'\x0B': 'v',
|
| 915 |
+
'\x0C': 'f',
|
| 916 |
+
'\x0D': 'r',
|
| 917 |
+
'\x1B': 'e',
|
| 918 |
+
'\"': '\"',
|
| 919 |
+
'\\': '\\',
|
| 920 |
+
'\x85': 'N',
|
| 921 |
+
'\xA0': '_',
|
| 922 |
+
'\u2028': 'L',
|
| 923 |
+
'\u2029': 'P',
|
| 924 |
+
}
|
| 925 |
+
|
| 926 |
+
def write_double_quoted(self, text, split=True):
|
| 927 |
+
self.write_indicator('"', True)
|
| 928 |
+
start = end = 0
|
| 929 |
+
while end <= len(text):
|
| 930 |
+
ch = None
|
| 931 |
+
if end < len(text):
|
| 932 |
+
ch = text[end]
|
| 933 |
+
if ch is None or ch in '"\\\x85\u2028\u2029\uFEFF' \
|
| 934 |
+
or not ('\x20' <= ch <= '\x7E'
|
| 935 |
+
or (self.allow_unicode
|
| 936 |
+
and ('\xA0' <= ch <= '\uD7FF'
|
| 937 |
+
or '\uE000' <= ch <= '\uFFFD'))):
|
| 938 |
+
if start < end:
|
| 939 |
+
data = text[start:end]
|
| 940 |
+
self.column += len(data)
|
| 941 |
+
if self.encoding:
|
| 942 |
+
data = data.encode(self.encoding)
|
| 943 |
+
self.stream.write(data)
|
| 944 |
+
start = end
|
| 945 |
+
if ch is not None:
|
| 946 |
+
if ch in self.ESCAPE_REPLACEMENTS:
|
| 947 |
+
data = '\\'+self.ESCAPE_REPLACEMENTS[ch]
|
| 948 |
+
elif ch <= '\xFF':
|
| 949 |
+
data = '\\x%02X' % ord(ch)
|
| 950 |
+
elif ch <= '\uFFFF':
|
| 951 |
+
data = '\\u%04X' % ord(ch)
|
| 952 |
+
else:
|
| 953 |
+
data = '\\U%08X' % ord(ch)
|
| 954 |
+
self.column += len(data)
|
| 955 |
+
if self.encoding:
|
| 956 |
+
data = data.encode(self.encoding)
|
| 957 |
+
self.stream.write(data)
|
| 958 |
+
start = end+1
|
| 959 |
+
if 0 < end < len(text)-1 and (ch == ' ' or start >= end) \
|
| 960 |
+
and self.column+(end-start) > self.best_width and split:
|
| 961 |
+
data = text[start:end]+'\\'
|
| 962 |
+
if start < end:
|
| 963 |
+
start = end
|
| 964 |
+
self.column += len(data)
|
| 965 |
+
if self.encoding:
|
| 966 |
+
data = data.encode(self.encoding)
|
| 967 |
+
self.stream.write(data)
|
| 968 |
+
self.write_indent()
|
| 969 |
+
self.whitespace = False
|
| 970 |
+
self.indention = False
|
| 971 |
+
if text[start] == ' ':
|
| 972 |
+
data = '\\'
|
| 973 |
+
self.column += len(data)
|
| 974 |
+
if self.encoding:
|
| 975 |
+
data = data.encode(self.encoding)
|
| 976 |
+
self.stream.write(data)
|
| 977 |
+
end += 1
|
| 978 |
+
self.write_indicator('"', False)
|
| 979 |
+
|
| 980 |
+
def determine_block_hints(self, text):
|
| 981 |
+
hints = ''
|
| 982 |
+
if text:
|
| 983 |
+
if text[0] in ' \n\x85\u2028\u2029':
|
| 984 |
+
hints += str(self.best_indent)
|
| 985 |
+
if text[-1] not in '\n\x85\u2028\u2029':
|
| 986 |
+
hints += '-'
|
| 987 |
+
elif len(text) == 1 or text[-2] in '\n\x85\u2028\u2029':
|
| 988 |
+
hints += '+'
|
| 989 |
+
return hints
|
| 990 |
+
|
| 991 |
+
def write_folded(self, text):
|
| 992 |
+
hints = self.determine_block_hints(text)
|
| 993 |
+
self.write_indicator('>'+hints, True)
|
| 994 |
+
if hints[-1:] == '+':
|
| 995 |
+
self.open_ended = True
|
| 996 |
+
self.write_line_break()
|
| 997 |
+
leading_space = True
|
| 998 |
+
spaces = False
|
| 999 |
+
breaks = True
|
| 1000 |
+
start = end = 0
|
| 1001 |
+
while end <= len(text):
|
| 1002 |
+
ch = None
|
| 1003 |
+
if end < len(text):
|
| 1004 |
+
ch = text[end]
|
| 1005 |
+
if breaks:
|
| 1006 |
+
if ch is None or ch not in '\n\x85\u2028\u2029':
|
| 1007 |
+
if not leading_space and ch is not None and ch != ' ' \
|
| 1008 |
+
and text[start] == '\n':
|
| 1009 |
+
self.write_line_break()
|
| 1010 |
+
leading_space = (ch == ' ')
|
| 1011 |
+
for br in text[start:end]:
|
| 1012 |
+
if br == '\n':
|
| 1013 |
+
self.write_line_break()
|
| 1014 |
+
else:
|
| 1015 |
+
self.write_line_break(br)
|
| 1016 |
+
if ch is not None:
|
| 1017 |
+
self.write_indent()
|
| 1018 |
+
start = end
|
| 1019 |
+
elif spaces:
|
| 1020 |
+
if ch != ' ':
|
| 1021 |
+
if start+1 == end and self.column > self.best_width:
|
| 1022 |
+
self.write_indent()
|
| 1023 |
+
else:
|
| 1024 |
+
data = text[start:end]
|
| 1025 |
+
self.column += len(data)
|
| 1026 |
+
if self.encoding:
|
| 1027 |
+
data = data.encode(self.encoding)
|
| 1028 |
+
self.stream.write(data)
|
| 1029 |
+
start = end
|
| 1030 |
+
else:
|
| 1031 |
+
if ch is None or ch in ' \n\x85\u2028\u2029':
|
| 1032 |
+
data = text[start:end]
|
| 1033 |
+
self.column += len(data)
|
| 1034 |
+
if self.encoding:
|
| 1035 |
+
data = data.encode(self.encoding)
|
| 1036 |
+
self.stream.write(data)
|
| 1037 |
+
if ch is None:
|
| 1038 |
+
self.write_line_break()
|
| 1039 |
+
start = end
|
| 1040 |
+
if ch is not None:
|
| 1041 |
+
breaks = (ch in '\n\x85\u2028\u2029')
|
| 1042 |
+
spaces = (ch == ' ')
|
| 1043 |
+
end += 1
|
| 1044 |
+
|
| 1045 |
+
def write_literal(self, text):
|
| 1046 |
+
hints = self.determine_block_hints(text)
|
| 1047 |
+
self.write_indicator('|'+hints, True)
|
| 1048 |
+
if hints[-1:] == '+':
|
| 1049 |
+
self.open_ended = True
|
| 1050 |
+
self.write_line_break()
|
| 1051 |
+
breaks = True
|
| 1052 |
+
start = end = 0
|
| 1053 |
+
while end <= len(text):
|
| 1054 |
+
ch = None
|
| 1055 |
+
if end < len(text):
|
| 1056 |
+
ch = text[end]
|
| 1057 |
+
if breaks:
|
| 1058 |
+
if ch is None or ch not in '\n\x85\u2028\u2029':
|
| 1059 |
+
for br in text[start:end]:
|
| 1060 |
+
if br == '\n':
|
| 1061 |
+
self.write_line_break()
|
| 1062 |
+
else:
|
| 1063 |
+
self.write_line_break(br)
|
| 1064 |
+
if ch is not None:
|
| 1065 |
+
self.write_indent()
|
| 1066 |
+
start = end
|
| 1067 |
+
else:
|
| 1068 |
+
if ch is None or ch in '\n\x85\u2028\u2029':
|
| 1069 |
+
data = text[start:end]
|
| 1070 |
+
if self.encoding:
|
| 1071 |
+
data = data.encode(self.encoding)
|
| 1072 |
+
self.stream.write(data)
|
| 1073 |
+
if ch is None:
|
| 1074 |
+
self.write_line_break()
|
| 1075 |
+
start = end
|
| 1076 |
+
if ch is not None:
|
| 1077 |
+
breaks = (ch in '\n\x85\u2028\u2029')
|
| 1078 |
+
end += 1
|
| 1079 |
+
|
| 1080 |
+
def write_plain(self, text, split=True):
|
| 1081 |
+
if self.root_context:
|
| 1082 |
+
self.open_ended = True
|
| 1083 |
+
if not text:
|
| 1084 |
+
return
|
| 1085 |
+
if not self.whitespace:
|
| 1086 |
+
data = ' '
|
| 1087 |
+
self.column += len(data)
|
| 1088 |
+
if self.encoding:
|
| 1089 |
+
data = data.encode(self.encoding)
|
| 1090 |
+
self.stream.write(data)
|
| 1091 |
+
self.whitespace = False
|
| 1092 |
+
self.indention = False
|
| 1093 |
+
spaces = False
|
| 1094 |
+
breaks = False
|
| 1095 |
+
start = end = 0
|
| 1096 |
+
while end <= len(text):
|
| 1097 |
+
ch = None
|
| 1098 |
+
if end < len(text):
|
| 1099 |
+
ch = text[end]
|
| 1100 |
+
if spaces:
|
| 1101 |
+
if ch != ' ':
|
| 1102 |
+
if start+1 == end and self.column > self.best_width and split:
|
| 1103 |
+
self.write_indent()
|
| 1104 |
+
self.whitespace = False
|
| 1105 |
+
self.indention = False
|
| 1106 |
+
else:
|
| 1107 |
+
data = text[start:end]
|
| 1108 |
+
self.column += len(data)
|
| 1109 |
+
if self.encoding:
|
| 1110 |
+
data = data.encode(self.encoding)
|
| 1111 |
+
self.stream.write(data)
|
| 1112 |
+
start = end
|
| 1113 |
+
elif breaks:
|
| 1114 |
+
if ch not in '\n\x85\u2028\u2029':
|
| 1115 |
+
if text[start] == '\n':
|
| 1116 |
+
self.write_line_break()
|
| 1117 |
+
for br in text[start:end]:
|
| 1118 |
+
if br == '\n':
|
| 1119 |
+
self.write_line_break()
|
| 1120 |
+
else:
|
| 1121 |
+
self.write_line_break(br)
|
| 1122 |
+
self.write_indent()
|
| 1123 |
+
self.whitespace = False
|
| 1124 |
+
self.indention = False
|
| 1125 |
+
start = end
|
| 1126 |
+
else:
|
| 1127 |
+
if ch is None or ch in ' \n\x85\u2028\u2029':
|
| 1128 |
+
data = text[start:end]
|
| 1129 |
+
self.column += len(data)
|
| 1130 |
+
if self.encoding:
|
| 1131 |
+
data = data.encode(self.encoding)
|
| 1132 |
+
self.stream.write(data)
|
| 1133 |
+
start = end
|
| 1134 |
+
if ch is not None:
|
| 1135 |
+
spaces = (ch == ' ')
|
| 1136 |
+
breaks = (ch in '\n\x85\u2028\u2029')
|
| 1137 |
+
end += 1
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/error.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']
|
| 3 |
+
|
| 4 |
+
class Mark:
|
| 5 |
+
|
| 6 |
+
def __init__(self, name, index, line, column, buffer, pointer):
|
| 7 |
+
self.name = name
|
| 8 |
+
self.index = index
|
| 9 |
+
self.line = line
|
| 10 |
+
self.column = column
|
| 11 |
+
self.buffer = buffer
|
| 12 |
+
self.pointer = pointer
|
| 13 |
+
|
| 14 |
+
def get_snippet(self, indent=4, max_length=75):
|
| 15 |
+
if self.buffer is None:
|
| 16 |
+
return None
|
| 17 |
+
head = ''
|
| 18 |
+
start = self.pointer
|
| 19 |
+
while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029':
|
| 20 |
+
start -= 1
|
| 21 |
+
if self.pointer-start > max_length/2-1:
|
| 22 |
+
head = ' ... '
|
| 23 |
+
start += 5
|
| 24 |
+
break
|
| 25 |
+
tail = ''
|
| 26 |
+
end = self.pointer
|
| 27 |
+
while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029':
|
| 28 |
+
end += 1
|
| 29 |
+
if end-self.pointer > max_length/2-1:
|
| 30 |
+
tail = ' ... '
|
| 31 |
+
end -= 5
|
| 32 |
+
break
|
| 33 |
+
snippet = self.buffer[start:end]
|
| 34 |
+
return ' '*indent + head + snippet + tail + '\n' \
|
| 35 |
+
+ ' '*(indent+self.pointer-start+len(head)) + '^'
|
| 36 |
+
|
| 37 |
+
def __str__(self):
|
| 38 |
+
snippet = self.get_snippet()
|
| 39 |
+
where = " in \"%s\", line %d, column %d" \
|
| 40 |
+
% (self.name, self.line+1, self.column+1)
|
| 41 |
+
if snippet is not None:
|
| 42 |
+
where += ":\n"+snippet
|
| 43 |
+
return where
|
| 44 |
+
|
| 45 |
+
class YAMLError(Exception):
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
class MarkedYAMLError(YAMLError):
|
| 49 |
+
|
| 50 |
+
def __init__(self, context=None, context_mark=None,
|
| 51 |
+
problem=None, problem_mark=None, note=None):
|
| 52 |
+
self.context = context
|
| 53 |
+
self.context_mark = context_mark
|
| 54 |
+
self.problem = problem
|
| 55 |
+
self.problem_mark = problem_mark
|
| 56 |
+
self.note = note
|
| 57 |
+
|
| 58 |
+
def __str__(self):
|
| 59 |
+
lines = []
|
| 60 |
+
if self.context is not None:
|
| 61 |
+
lines.append(self.context)
|
| 62 |
+
if self.context_mark is not None \
|
| 63 |
+
and (self.problem is None or self.problem_mark is None
|
| 64 |
+
or self.context_mark.name != self.problem_mark.name
|
| 65 |
+
or self.context_mark.line != self.problem_mark.line
|
| 66 |
+
or self.context_mark.column != self.problem_mark.column):
|
| 67 |
+
lines.append(str(self.context_mark))
|
| 68 |
+
if self.problem is not None:
|
| 69 |
+
lines.append(self.problem)
|
| 70 |
+
if self.problem_mark is not None:
|
| 71 |
+
lines.append(str(self.problem_mark))
|
| 72 |
+
if self.note is not None:
|
| 73 |
+
lines.append(self.note)
|
| 74 |
+
return '\n'.join(lines)
|
| 75 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/events.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Abstract classes.
|
| 3 |
+
|
| 4 |
+
class Event(object):
|
| 5 |
+
def __init__(self, start_mark=None, end_mark=None):
|
| 6 |
+
self.start_mark = start_mark
|
| 7 |
+
self.end_mark = end_mark
|
| 8 |
+
def __repr__(self):
|
| 9 |
+
attributes = [key for key in ['anchor', 'tag', 'implicit', 'value']
|
| 10 |
+
if hasattr(self, key)]
|
| 11 |
+
arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
|
| 12 |
+
for key in attributes])
|
| 13 |
+
return '%s(%s)' % (self.__class__.__name__, arguments)
|
| 14 |
+
|
| 15 |
+
class NodeEvent(Event):
|
| 16 |
+
def __init__(self, anchor, start_mark=None, end_mark=None):
|
| 17 |
+
self.anchor = anchor
|
| 18 |
+
self.start_mark = start_mark
|
| 19 |
+
self.end_mark = end_mark
|
| 20 |
+
|
| 21 |
+
class CollectionStartEvent(NodeEvent):
|
| 22 |
+
def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None,
|
| 23 |
+
flow_style=None):
|
| 24 |
+
self.anchor = anchor
|
| 25 |
+
self.tag = tag
|
| 26 |
+
self.implicit = implicit
|
| 27 |
+
self.start_mark = start_mark
|
| 28 |
+
self.end_mark = end_mark
|
| 29 |
+
self.flow_style = flow_style
|
| 30 |
+
|
| 31 |
+
class CollectionEndEvent(Event):
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
# Implementations.
|
| 35 |
+
|
| 36 |
+
class StreamStartEvent(Event):
|
| 37 |
+
def __init__(self, start_mark=None, end_mark=None, encoding=None):
|
| 38 |
+
self.start_mark = start_mark
|
| 39 |
+
self.end_mark = end_mark
|
| 40 |
+
self.encoding = encoding
|
| 41 |
+
|
| 42 |
+
class StreamEndEvent(Event):
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
class DocumentStartEvent(Event):
|
| 46 |
+
def __init__(self, start_mark=None, end_mark=None,
|
| 47 |
+
explicit=None, version=None, tags=None):
|
| 48 |
+
self.start_mark = start_mark
|
| 49 |
+
self.end_mark = end_mark
|
| 50 |
+
self.explicit = explicit
|
| 51 |
+
self.version = version
|
| 52 |
+
self.tags = tags
|
| 53 |
+
|
| 54 |
+
class DocumentEndEvent(Event):
|
| 55 |
+
def __init__(self, start_mark=None, end_mark=None,
|
| 56 |
+
explicit=None):
|
| 57 |
+
self.start_mark = start_mark
|
| 58 |
+
self.end_mark = end_mark
|
| 59 |
+
self.explicit = explicit
|
| 60 |
+
|
| 61 |
+
class AliasEvent(NodeEvent):
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
class ScalarEvent(NodeEvent):
|
| 65 |
+
def __init__(self, anchor, tag, implicit, value,
|
| 66 |
+
start_mark=None, end_mark=None, style=None):
|
| 67 |
+
self.anchor = anchor
|
| 68 |
+
self.tag = tag
|
| 69 |
+
self.implicit = implicit
|
| 70 |
+
self.value = value
|
| 71 |
+
self.start_mark = start_mark
|
| 72 |
+
self.end_mark = end_mark
|
| 73 |
+
self.style = style
|
| 74 |
+
|
| 75 |
+
class SequenceStartEvent(CollectionStartEvent):
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
class SequenceEndEvent(CollectionEndEvent):
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
class MappingStartEvent(CollectionStartEvent):
|
| 82 |
+
pass
|
| 83 |
+
|
| 84 |
+
class MappingEndEvent(CollectionEndEvent):
|
| 85 |
+
pass
|
| 86 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/loader.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
__all__ = ['BaseLoader', 'FullLoader', 'SafeLoader', 'Loader', 'UnsafeLoader']
|
| 3 |
+
|
| 4 |
+
from .reader import *
|
| 5 |
+
from .scanner import *
|
| 6 |
+
from .parser import *
|
| 7 |
+
from .composer import *
|
| 8 |
+
from .constructor import *
|
| 9 |
+
from .resolver import *
|
| 10 |
+
|
| 11 |
+
class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver):
|
| 12 |
+
|
| 13 |
+
def __init__(self, stream):
|
| 14 |
+
Reader.__init__(self, stream)
|
| 15 |
+
Scanner.__init__(self)
|
| 16 |
+
Parser.__init__(self)
|
| 17 |
+
Composer.__init__(self)
|
| 18 |
+
BaseConstructor.__init__(self)
|
| 19 |
+
BaseResolver.__init__(self)
|
| 20 |
+
|
| 21 |
+
class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver):
|
| 22 |
+
|
| 23 |
+
def __init__(self, stream):
|
| 24 |
+
Reader.__init__(self, stream)
|
| 25 |
+
Scanner.__init__(self)
|
| 26 |
+
Parser.__init__(self)
|
| 27 |
+
Composer.__init__(self)
|
| 28 |
+
FullConstructor.__init__(self)
|
| 29 |
+
Resolver.__init__(self)
|
| 30 |
+
|
| 31 |
+
class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
|
| 32 |
+
|
| 33 |
+
def __init__(self, stream):
|
| 34 |
+
Reader.__init__(self, stream)
|
| 35 |
+
Scanner.__init__(self)
|
| 36 |
+
Parser.__init__(self)
|
| 37 |
+
Composer.__init__(self)
|
| 38 |
+
SafeConstructor.__init__(self)
|
| 39 |
+
Resolver.__init__(self)
|
| 40 |
+
|
| 41 |
+
class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
|
| 42 |
+
|
| 43 |
+
def __init__(self, stream):
|
| 44 |
+
Reader.__init__(self, stream)
|
| 45 |
+
Scanner.__init__(self)
|
| 46 |
+
Parser.__init__(self)
|
| 47 |
+
Composer.__init__(self)
|
| 48 |
+
Constructor.__init__(self)
|
| 49 |
+
Resolver.__init__(self)
|
| 50 |
+
|
| 51 |
+
# UnsafeLoader is the same as Loader (which is and was always unsafe on
|
| 52 |
+
# untrusted input). Use of either Loader or UnsafeLoader should be rare, since
|
| 53 |
+
# FullLoad should be able to load almost all YAML safely. Loader is left intact
|
| 54 |
+
# to ensure backwards compatibility.
|
| 55 |
+
class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
|
| 56 |
+
|
| 57 |
+
def __init__(self, stream):
|
| 58 |
+
Reader.__init__(self, stream)
|
| 59 |
+
Scanner.__init__(self)
|
| 60 |
+
Parser.__init__(self)
|
| 61 |
+
Composer.__init__(self)
|
| 62 |
+
Constructor.__init__(self)
|
| 63 |
+
Resolver.__init__(self)
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/nodes.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
class Node(object):
|
| 3 |
+
def __init__(self, tag, value, start_mark, end_mark):
|
| 4 |
+
self.tag = tag
|
| 5 |
+
self.value = value
|
| 6 |
+
self.start_mark = start_mark
|
| 7 |
+
self.end_mark = end_mark
|
| 8 |
+
def __repr__(self):
|
| 9 |
+
value = self.value
|
| 10 |
+
#if isinstance(value, list):
|
| 11 |
+
# if len(value) == 0:
|
| 12 |
+
# value = '<empty>'
|
| 13 |
+
# elif len(value) == 1:
|
| 14 |
+
# value = '<1 item>'
|
| 15 |
+
# else:
|
| 16 |
+
# value = '<%d items>' % len(value)
|
| 17 |
+
#else:
|
| 18 |
+
# if len(value) > 75:
|
| 19 |
+
# value = repr(value[:70]+u' ... ')
|
| 20 |
+
# else:
|
| 21 |
+
# value = repr(value)
|
| 22 |
+
value = repr(value)
|
| 23 |
+
return '%s(tag=%r, value=%s)' % (self.__class__.__name__, self.tag, value)
|
| 24 |
+
|
| 25 |
+
class ScalarNode(Node):
|
| 26 |
+
id = 'scalar'
|
| 27 |
+
def __init__(self, tag, value,
|
| 28 |
+
start_mark=None, end_mark=None, style=None):
|
| 29 |
+
self.tag = tag
|
| 30 |
+
self.value = value
|
| 31 |
+
self.start_mark = start_mark
|
| 32 |
+
self.end_mark = end_mark
|
| 33 |
+
self.style = style
|
| 34 |
+
|
| 35 |
+
class CollectionNode(Node):
|
| 36 |
+
def __init__(self, tag, value,
|
| 37 |
+
start_mark=None, end_mark=None, flow_style=None):
|
| 38 |
+
self.tag = tag
|
| 39 |
+
self.value = value
|
| 40 |
+
self.start_mark = start_mark
|
| 41 |
+
self.end_mark = end_mark
|
| 42 |
+
self.flow_style = flow_style
|
| 43 |
+
|
| 44 |
+
class SequenceNode(CollectionNode):
|
| 45 |
+
id = 'sequence'
|
| 46 |
+
|
| 47 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# The following YAML grammar is LL(1) and is parsed by a recursive descent
|
| 3 |
+
# parser.
|
| 4 |
+
#
|
| 5 |
+
# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
|
| 6 |
+
# implicit_document ::= block_node DOCUMENT-END*
|
| 7 |
+
# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
|
| 8 |
+
# block_node_or_indentless_sequence ::=
|
| 9 |
+
# ALIAS
|
| 10 |
+
# | properties (block_content | indentless_block_sequence)?
|
| 11 |
+
# | block_content
|
| 12 |
+
# | indentless_block_sequence
|
| 13 |
+
# block_node ::= ALIAS
|
| 14 |
+
# | properties block_content?
|
| 15 |
+
# | block_content
|
| 16 |
+
# flow_node ::= ALIAS
|
| 17 |
+
# | properties flow_content?
|
| 18 |
+
# | flow_content
|
| 19 |
+
# properties ::= TAG ANCHOR? | ANCHOR TAG?
|
| 20 |
+
# block_content ::= block_collection | flow_collection | SCALAR
|
| 21 |
+
# flow_content ::= flow_collection | SCALAR
|
| 22 |
+
# block_collection ::= block_sequence | block_mapping
|
| 23 |
+
# flow_collection ::= flow_sequence | flow_mapping
|
| 24 |
+
# block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
|
| 25 |
+
# indentless_sequence ::= (BLOCK-ENTRY block_node?)+
|
| 26 |
+
# block_mapping ::= BLOCK-MAPPING_START
|
| 27 |
+
# ((KEY block_node_or_indentless_sequence?)?
|
| 28 |
+
# (VALUE block_node_or_indentless_sequence?)?)*
|
| 29 |
+
# BLOCK-END
|
| 30 |
+
# flow_sequence ::= FLOW-SEQUENCE-START
|
| 31 |
+
# (flow_sequence_entry FLOW-ENTRY)*
|
| 32 |
+
# flow_sequence_entry?
|
| 33 |
+
# FLOW-SEQUENCE-END
|
| 34 |
+
# flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
|
| 35 |
+
# flow_mapping ::= FLOW-MAPPING-START
|
| 36 |
+
# (flow_mapping_entry FLOW-ENTRY)*
|
| 37 |
+
# flow_mapping_entry?
|
| 38 |
+
# FLOW-MAPPING-END
|
| 39 |
+
# flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
|
| 40 |
+
#
|
| 41 |
+
# FIRST sets:
|
| 42 |
+
#
|
| 43 |
+
# stream: { STREAM-START }
|
| 44 |
+
# explicit_document: { DIRECTIVE DOCUMENT-START }
|
| 45 |
+
# implicit_document: FIRST(block_node)
|
| 46 |
+
# block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START }
|
| 47 |
+
# flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START }
|
| 48 |
+
# block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
|
| 49 |
+
# flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
|
| 50 |
+
# block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START }
|
| 51 |
+
# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
|
| 52 |
+
# block_sequence: { BLOCK-SEQUENCE-START }
|
| 53 |
+
# block_mapping: { BLOCK-MAPPING-START }
|
| 54 |
+
# block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY }
|
| 55 |
+
# indentless_sequence: { ENTRY }
|
| 56 |
+
# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
|
| 57 |
+
# flow_sequence: { FLOW-SEQUENCE-START }
|
| 58 |
+
# flow_mapping: { FLOW-MAPPING-START }
|
| 59 |
+
# flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
|
| 60 |
+
# flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
|
| 61 |
+
|
| 62 |
+
__all__ = ['Parser', 'ParserError']
|
| 63 |
+
|
| 64 |
+
from .error import MarkedYAMLError
|
| 65 |
+
from .tokens import *
|
| 66 |
+
from .events import *
|
| 67 |
+
from .scanner import *
|
| 68 |
+
|
| 69 |
+
class ParserError(MarkedYAMLError):
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
class Parser:
|
| 73 |
+
# Since writing a recursive-descendant parser is a straightforward task, we
|
| 74 |
+
# do not give many comments here.
|
| 75 |
+
|
| 76 |
+
DEFAULT_TAGS = {
|
| 77 |
+
'!': '!',
|
| 78 |
+
'!!': 'tag:yaml.org,2002:',
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
def __init__(self):
|
| 82 |
+
self.current_event = None
|
| 83 |
+
self.yaml_version = None
|
| 84 |
+
self.tag_handles = {}
|
| 85 |
+
self.states = []
|
| 86 |
+
self.marks = []
|
| 87 |
+
self.state = self.parse_stream_start
|
| 88 |
+
|
| 89 |
+
def dispose(self):
|
| 90 |
+
# Reset the state attributes (to clear self-references)
|
| 91 |
+
self.states = []
|
| 92 |
+
self.state = None
|
| 93 |
+
|
| 94 |
+
def check_event(self, *choices):
|
| 95 |
+
# Check the type of the next event.
|
| 96 |
+
if self.current_event is None:
|
| 97 |
+
if self.state:
|
| 98 |
+
self.current_event = self.state()
|
| 99 |
+
if self.current_event is not None:
|
| 100 |
+
if not choices:
|
| 101 |
+
return True
|
| 102 |
+
for choice in choices:
|
| 103 |
+
if isinstance(self.current_event, choice):
|
| 104 |
+
return True
|
| 105 |
+
return False
|
| 106 |
+
|
| 107 |
+
def peek_event(self):
|
| 108 |
+
# Get the next event.
|
| 109 |
+
if self.current_event is None:
|
| 110 |
+
if self.state:
|
| 111 |
+
self.current_event = self.state()
|
| 112 |
+
return self.current_event
|
| 113 |
+
|
| 114 |
+
def get_event(self):
|
| 115 |
+
# Get the next event and proceed further.
|
| 116 |
+
if self.current_event is None:
|
| 117 |
+
if self.state:
|
| 118 |
+
self.current_event = self.state()
|
| 119 |
+
value = self.current_event
|
| 120 |
+
self.current_event = None
|
| 121 |
+
return value
|
| 122 |
+
|
| 123 |
+
# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
|
| 124 |
+
# implicit_document ::= block_node DOCUMENT-END*
|
| 125 |
+
# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
|
| 126 |
+
|
| 127 |
+
def parse_stream_start(self):
|
| 128 |
+
|
| 129 |
+
# Parse the stream start.
|
| 130 |
+
token = self.get_token()
|
| 131 |
+
event = StreamStartEvent(token.start_mark, token.end_mark,
|
| 132 |
+
encoding=token.encoding)
|
| 133 |
+
|
| 134 |
+
# Prepare the next state.
|
| 135 |
+
self.state = self.parse_implicit_document_start
|
| 136 |
+
|
| 137 |
+
return event
|
| 138 |
+
|
| 139 |
+
def parse_implicit_document_start(self):
|
| 140 |
+
|
| 141 |
+
# Parse an implicit document.
|
| 142 |
+
if not self.check_token(DirectiveToken, DocumentStartToken,
|
| 143 |
+
StreamEndToken):
|
| 144 |
+
self.tag_handles = self.DEFAULT_TAGS
|
| 145 |
+
token = self.peek_token()
|
| 146 |
+
start_mark = end_mark = token.start_mark
|
| 147 |
+
event = DocumentStartEvent(start_mark, end_mark,
|
| 148 |
+
explicit=False)
|
| 149 |
+
|
| 150 |
+
# Prepare the next state.
|
| 151 |
+
self.states.append(self.parse_document_end)
|
| 152 |
+
self.state = self.parse_block_node
|
| 153 |
+
|
| 154 |
+
return event
|
| 155 |
+
|
| 156 |
+
else:
|
| 157 |
+
return self.parse_document_start()
|
| 158 |
+
|
| 159 |
+
def parse_document_start(self):
|
| 160 |
+
|
| 161 |
+
# Parse any extra document end indicators.
|
| 162 |
+
while self.check_token(DocumentEndToken):
|
| 163 |
+
self.get_token()
|
| 164 |
+
|
| 165 |
+
# Parse an explicit document.
|
| 166 |
+
if not self.check_token(StreamEndToken):
|
| 167 |
+
token = self.peek_token()
|
| 168 |
+
start_mark = token.start_mark
|
| 169 |
+
version, tags = self.process_directives()
|
| 170 |
+
if not self.check_token(DocumentStartToken):
|
| 171 |
+
raise ParserError(None, None,
|
| 172 |
+
"expected '<document start>', but found %r"
|
| 173 |
+
% self.peek_token().id,
|
| 174 |
+
self.peek_token().start_mark)
|
| 175 |
+
token = self.get_token()
|
| 176 |
+
end_mark = token.end_mark
|
| 177 |
+
event = DocumentStartEvent(start_mark, end_mark,
|
| 178 |
+
explicit=True, version=version, tags=tags)
|
| 179 |
+
self.states.append(self.parse_document_end)
|
| 180 |
+
self.state = self.parse_document_content
|
| 181 |
+
else:
|
| 182 |
+
# Parse the end of the stream.
|
| 183 |
+
token = self.get_token()
|
| 184 |
+
event = StreamEndEvent(token.start_mark, token.end_mark)
|
| 185 |
+
assert not self.states
|
| 186 |
+
assert not self.marks
|
| 187 |
+
self.state = None
|
| 188 |
+
return event
|
| 189 |
+
|
| 190 |
+
def parse_document_end(self):
|
| 191 |
+
|
| 192 |
+
# Parse the document end.
|
| 193 |
+
token = self.peek_token()
|
| 194 |
+
start_mark = end_mark = token.start_mark
|
| 195 |
+
explicit = False
|
| 196 |
+
if self.check_token(DocumentEndToken):
|
| 197 |
+
token = self.get_token()
|
| 198 |
+
end_mark = token.end_mark
|
| 199 |
+
explicit = True
|
| 200 |
+
event = DocumentEndEvent(start_mark, end_mark,
|
| 201 |
+
explicit=explicit)
|
| 202 |
+
|
| 203 |
+
# Prepare the next state.
|
| 204 |
+
self.state = self.parse_document_start
|
| 205 |
+
|
| 206 |
+
return event
|
| 207 |
+
|
| 208 |
+
def parse_document_content(self):
|
| 209 |
+
if self.check_token(DirectiveToken,
|
| 210 |
+
DocumentStartToken, DocumentEndToken, StreamEndToken):
|
| 211 |
+
event = self.process_empty_scalar(self.peek_token().start_mark)
|
| 212 |
+
self.state = self.states.pop()
|
| 213 |
+
return event
|
| 214 |
+
else:
|
| 215 |
+
return self.parse_block_node()
|
| 216 |
+
|
| 217 |
+
def process_directives(self):
|
| 218 |
+
self.yaml_version = None
|
| 219 |
+
self.tag_handles = {}
|
| 220 |
+
while self.check_token(DirectiveToken):
|
| 221 |
+
token = self.get_token()
|
| 222 |
+
if token.name == 'YAML':
|
| 223 |
+
if self.yaml_version is not None:
|
| 224 |
+
raise ParserError(None, None,
|
| 225 |
+
"found duplicate YAML directive", token.start_mark)
|
| 226 |
+
major, minor = token.value
|
| 227 |
+
if major != 1:
|
| 228 |
+
raise ParserError(None, None,
|
| 229 |
+
"found incompatible YAML document (version 1.* is required)",
|
| 230 |
+
token.start_mark)
|
| 231 |
+
self.yaml_version = token.value
|
| 232 |
+
elif token.name == 'TAG':
|
| 233 |
+
handle, prefix = token.value
|
| 234 |
+
if handle in self.tag_handles:
|
| 235 |
+
raise ParserError(None, None,
|
| 236 |
+
"duplicate tag handle %r" % handle,
|
| 237 |
+
token.start_mark)
|
| 238 |
+
self.tag_handles[handle] = prefix
|
| 239 |
+
if self.tag_handles:
|
| 240 |
+
value = self.yaml_version, self.tag_handles.copy()
|
| 241 |
+
else:
|
| 242 |
+
value = self.yaml_version, None
|
| 243 |
+
for key in self.DEFAULT_TAGS:
|
| 244 |
+
if key not in self.tag_handles:
|
| 245 |
+
self.tag_handles[key] = self.DEFAULT_TAGS[key]
|
| 246 |
+
return value
|
| 247 |
+
|
| 248 |
+
# block_node_or_indentless_sequence ::= ALIAS
|
| 249 |
+
# | properties (block_content | indentless_block_sequence)?
|
| 250 |
+
# | block_content
|
| 251 |
+
# | indentless_block_sequence
|
| 252 |
+
# block_node ::= ALIAS
|
| 253 |
+
# | properties block_content?
|
| 254 |
+
# | block_content
|
| 255 |
+
# flow_node ::= ALIAS
|
| 256 |
+
# | properties flow_content?
|
| 257 |
+
# | flow_content
|
| 258 |
+
# properties ::= TAG ANCHOR? | ANCHOR TAG?
|
| 259 |
+
# block_content ::= block_collection | flow_collection | SCALAR
|
| 260 |
+
# flow_content ::= flow_collection | SCALAR
|
| 261 |
+
# block_collection ::= block_sequence | block_mapping
|
| 262 |
+
# flow_collection ::= flow_sequence | flow_mapping
|
| 263 |
+
|
| 264 |
+
def parse_block_node(self):
|
| 265 |
+
return self.parse_node(block=True)
|
| 266 |
+
|
| 267 |
+
def parse_flow_node(self):
|
| 268 |
+
return self.parse_node()
|
| 269 |
+
|
| 270 |
+
def parse_block_node_or_indentless_sequence(self):
|
| 271 |
+
return self.parse_node(block=True, indentless_sequence=True)
|
| 272 |
+
|
| 273 |
+
def parse_node(self, block=False, indentless_sequence=False):
|
| 274 |
+
if self.check_token(AliasToken):
|
| 275 |
+
token = self.get_token()
|
| 276 |
+
event = AliasEvent(token.value, token.start_mark, token.end_mark)
|
| 277 |
+
self.state = self.states.pop()
|
| 278 |
+
else:
|
| 279 |
+
anchor = None
|
| 280 |
+
tag = None
|
| 281 |
+
start_mark = end_mark = tag_mark = None
|
| 282 |
+
if self.check_token(AnchorToken):
|
| 283 |
+
token = self.get_token()
|
| 284 |
+
start_mark = token.start_mark
|
| 285 |
+
end_mark = token.end_mark
|
| 286 |
+
anchor = token.value
|
| 287 |
+
if self.check_token(TagToken):
|
| 288 |
+
token = self.get_token()
|
| 289 |
+
tag_mark = token.start_mark
|
| 290 |
+
end_mark = token.end_mark
|
| 291 |
+
tag = token.value
|
| 292 |
+
elif self.check_token(TagToken):
|
| 293 |
+
token = self.get_token()
|
| 294 |
+
start_mark = tag_mark = token.start_mark
|
| 295 |
+
end_mark = token.end_mark
|
| 296 |
+
tag = token.value
|
| 297 |
+
if self.check_token(AnchorToken):
|
| 298 |
+
token = self.get_token()
|
| 299 |
+
end_mark = token.end_mark
|
| 300 |
+
anchor = token.value
|
| 301 |
+
if tag is not None:
|
| 302 |
+
handle, suffix = tag
|
| 303 |
+
if handle is not None:
|
| 304 |
+
if handle not in self.tag_handles:
|
| 305 |
+
raise ParserError("while parsing a node", start_mark,
|
| 306 |
+
"found undefined tag handle %r" % handle,
|
| 307 |
+
tag_mark)
|
| 308 |
+
tag = self.tag_handles[handle]+suffix
|
| 309 |
+
else:
|
| 310 |
+
tag = suffix
|
| 311 |
+
#if tag == '!':
|
| 312 |
+
# raise ParserError("while parsing a node", start_mark,
|
| 313 |
+
# "found non-specific tag '!'", tag_mark,
|
| 314 |
+
# "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.")
|
| 315 |
+
if start_mark is None:
|
| 316 |
+
start_mark = end_mark = self.peek_token().start_mark
|
| 317 |
+
event = None
|
| 318 |
+
implicit = (tag is None or tag == '!')
|
| 319 |
+
if indentless_sequence and self.check_token(BlockEntryToken):
|
| 320 |
+
end_mark = self.peek_token().end_mark
|
| 321 |
+
event = SequenceStartEvent(anchor, tag, implicit,
|
| 322 |
+
start_mark, end_mark)
|
| 323 |
+
self.state = self.parse_indentless_sequence_entry
|
| 324 |
+
else:
|
| 325 |
+
if self.check_token(ScalarToken):
|
| 326 |
+
token = self.get_token()
|
| 327 |
+
end_mark = token.end_mark
|
| 328 |
+
if (token.plain and tag is None) or tag == '!':
|
| 329 |
+
implicit = (True, False)
|
| 330 |
+
elif tag is None:
|
| 331 |
+
implicit = (False, True)
|
| 332 |
+
else:
|
| 333 |
+
implicit = (False, False)
|
| 334 |
+
event = ScalarEvent(anchor, tag, implicit, token.value,
|
| 335 |
+
start_mark, end_mark, style=token.style)
|
| 336 |
+
self.state = self.states.pop()
|
| 337 |
+
elif self.check_token(FlowSequenceStartToken):
|
| 338 |
+
end_mark = self.peek_token().end_mark
|
| 339 |
+
event = SequenceStartEvent(anchor, tag, implicit,
|
| 340 |
+
start_mark, end_mark, flow_style=True)
|
| 341 |
+
self.state = self.parse_flow_sequence_first_entry
|
| 342 |
+
elif self.check_token(FlowMappingStartToken):
|
| 343 |
+
end_mark = self.peek_token().end_mark
|
| 344 |
+
event = MappingStartEvent(anchor, tag, implicit,
|
| 345 |
+
start_mark, end_mark, flow_style=True)
|
| 346 |
+
self.state = self.parse_flow_mapping_first_key
|
| 347 |
+
elif block and self.check_token(BlockSequenceStartToken):
|
| 348 |
+
end_mark = self.peek_token().start_mark
|
| 349 |
+
event = SequenceStartEvent(anchor, tag, implicit,
|
| 350 |
+
start_mark, end_mark, flow_style=False)
|
| 351 |
+
self.state = self.parse_block_sequence_first_entry
|
| 352 |
+
elif block and self.check_token(BlockMappingStartToken):
|
| 353 |
+
end_mark = self.peek_token().start_mark
|
| 354 |
+
event = MappingStartEvent(anchor, tag, implicit,
|
| 355 |
+
start_mark, end_mark, flow_style=False)
|
| 356 |
+
self.state = self.parse_block_mapping_first_key
|
| 357 |
+
elif anchor is not None or tag is not None:
|
| 358 |
+
# Empty scalars are allowed even if a tag or an anchor is
|
| 359 |
+
# specified.
|
| 360 |
+
event = ScalarEvent(anchor, tag, (implicit, False), '',
|
| 361 |
+
start_mark, end_mark)
|
| 362 |
+
self.state = self.states.pop()
|
| 363 |
+
else:
|
| 364 |
+
if block:
|
| 365 |
+
node = 'block'
|
| 366 |
+
else:
|
| 367 |
+
node = 'flow'
|
| 368 |
+
token = self.peek_token()
|
| 369 |
+
raise ParserError("while parsing a %s node" % node, start_mark,
|
| 370 |
+
"expected the node content, but found %r" % token.id,
|
| 371 |
+
token.start_mark)
|
| 372 |
+
return event
|
| 373 |
+
|
| 374 |
+
# block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
|
| 375 |
+
|
| 376 |
+
def parse_block_sequence_first_entry(self):
|
| 377 |
+
token = self.get_token()
|
| 378 |
+
self.marks.append(token.start_mark)
|
| 379 |
+
return self.parse_block_sequence_entry()
|
| 380 |
+
|
| 381 |
+
def parse_block_sequence_entry(self):
|
| 382 |
+
if self.check_token(BlockEntryToken):
|
| 383 |
+
token = self.get_token()
|
| 384 |
+
if not self.check_token(BlockEntryToken, BlockEndToken):
|
| 385 |
+
self.states.append(self.parse_block_sequence_entry)
|
| 386 |
+
return self.parse_block_node()
|
| 387 |
+
else:
|
| 388 |
+
self.state = self.parse_block_sequence_entry
|
| 389 |
+
return self.process_empty_scalar(token.end_mark)
|
| 390 |
+
if not self.check_token(BlockEndToken):
|
| 391 |
+
token = self.peek_token()
|
| 392 |
+
raise ParserError("while parsing a block collection", self.marks[-1],
|
| 393 |
+
"expected <block end>, but found %r" % token.id, token.start_mark)
|
| 394 |
+
token = self.get_token()
|
| 395 |
+
event = SequenceEndEvent(token.start_mark, token.end_mark)
|
| 396 |
+
self.state = self.states.pop()
|
| 397 |
+
self.marks.pop()
|
| 398 |
+
return event
|
| 399 |
+
|
| 400 |
+
# indentless_sequence ::= (BLOCK-ENTRY block_node?)+
|
| 401 |
+
|
| 402 |
+
def parse_indentless_sequence_entry(self):
|
| 403 |
+
if self.check_token(BlockEntryToken):
|
| 404 |
+
token = self.get_token()
|
| 405 |
+
if not self.check_token(BlockEntryToken,
|
| 406 |
+
KeyToken, ValueToken, BlockEndToken):
|
| 407 |
+
self.states.append(self.parse_indentless_sequence_entry)
|
| 408 |
+
return self.parse_block_node()
|
| 409 |
+
else:
|
| 410 |
+
self.state = self.parse_indentless_sequence_entry
|
| 411 |
+
return self.process_empty_scalar(token.end_mark)
|
| 412 |
+
token = self.peek_token()
|
| 413 |
+
event = SequenceEndEvent(token.start_mark, token.start_mark)
|
| 414 |
+
self.state = self.states.pop()
|
| 415 |
+
return event
|
| 416 |
+
|
| 417 |
+
# block_mapping ::= BLOCK-MAPPING_START
|
| 418 |
+
# ((KEY block_node_or_indentless_sequence?)?
|
| 419 |
+
# (VALUE block_node_or_indentless_sequence?)?)*
|
| 420 |
+
# BLOCK-END
|
| 421 |
+
|
| 422 |
+
def parse_block_mapping_first_key(self):
|
| 423 |
+
token = self.get_token()
|
| 424 |
+
self.marks.append(token.start_mark)
|
| 425 |
+
return self.parse_block_mapping_key()
|
| 426 |
+
|
| 427 |
+
def parse_block_mapping_key(self):
|
| 428 |
+
if self.check_token(KeyToken):
|
| 429 |
+
token = self.get_token()
|
| 430 |
+
if not self.check_token(KeyToken, ValueToken, BlockEndToken):
|
| 431 |
+
self.states.append(self.parse_block_mapping_value)
|
| 432 |
+
return self.parse_block_node_or_indentless_sequence()
|
| 433 |
+
else:
|
| 434 |
+
self.state = self.parse_block_mapping_value
|
| 435 |
+
return self.process_empty_scalar(token.end_mark)
|
| 436 |
+
if not self.check_token(BlockEndToken):
|
| 437 |
+
token = self.peek_token()
|
| 438 |
+
raise ParserError("while parsing a block mapping", self.marks[-1],
|
| 439 |
+
"expected <block end>, but found %r" % token.id, token.start_mark)
|
| 440 |
+
token = self.get_token()
|
| 441 |
+
event = MappingEndEvent(token.start_mark, token.end_mark)
|
| 442 |
+
self.state = self.states.pop()
|
| 443 |
+
self.marks.pop()
|
| 444 |
+
return event
|
| 445 |
+
|
| 446 |
+
def parse_block_mapping_value(self):
|
| 447 |
+
if self.check_token(ValueToken):
|
| 448 |
+
token = self.get_token()
|
| 449 |
+
if not self.check_token(KeyToken, ValueToken, BlockEndToken):
|
| 450 |
+
self.states.append(self.parse_block_mapping_key)
|
| 451 |
+
return self.parse_block_node_or_indentless_sequence()
|
| 452 |
+
else:
|
| 453 |
+
self.state = self.parse_block_mapping_key
|
| 454 |
+
return self.process_empty_scalar(token.end_mark)
|
| 455 |
+
else:
|
| 456 |
+
self.state = self.parse_block_mapping_key
|
| 457 |
+
token = self.peek_token()
|
| 458 |
+
return self.process_empty_scalar(token.start_mark)
|
| 459 |
+
|
| 460 |
+
# flow_sequence ::= FLOW-SEQUENCE-START
|
| 461 |
+
# (flow_sequence_entry FLOW-ENTRY)*
|
| 462 |
+
# flow_sequence_entry?
|
| 463 |
+
# FLOW-SEQUENCE-END
|
| 464 |
+
# flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
|
| 465 |
+
#
|
| 466 |
+
# Note that while production rules for both flow_sequence_entry and
|
| 467 |
+
# flow_mapping_entry are equal, their interpretations are different.
|
| 468 |
+
# For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?`
|
| 469 |
+
# generate an inline mapping (set syntax).
|
| 470 |
+
|
| 471 |
+
def parse_flow_sequence_first_entry(self):
|
| 472 |
+
token = self.get_token()
|
| 473 |
+
self.marks.append(token.start_mark)
|
| 474 |
+
return self.parse_flow_sequence_entry(first=True)
|
| 475 |
+
|
| 476 |
+
def parse_flow_sequence_entry(self, first=False):
|
| 477 |
+
if not self.check_token(FlowSequenceEndToken):
|
| 478 |
+
if not first:
|
| 479 |
+
if self.check_token(FlowEntryToken):
|
| 480 |
+
self.get_token()
|
| 481 |
+
else:
|
| 482 |
+
token = self.peek_token()
|
| 483 |
+
raise ParserError("while parsing a flow sequence", self.marks[-1],
|
| 484 |
+
"expected ',' or ']', but got %r" % token.id, token.start_mark)
|
| 485 |
+
|
| 486 |
+
if self.check_token(KeyToken):
|
| 487 |
+
token = self.peek_token()
|
| 488 |
+
event = MappingStartEvent(None, None, True,
|
| 489 |
+
token.start_mark, token.end_mark,
|
| 490 |
+
flow_style=True)
|
| 491 |
+
self.state = self.parse_flow_sequence_entry_mapping_key
|
| 492 |
+
return event
|
| 493 |
+
elif not self.check_token(FlowSequenceEndToken):
|
| 494 |
+
self.states.append(self.parse_flow_sequence_entry)
|
| 495 |
+
return self.parse_flow_node()
|
| 496 |
+
token = self.get_token()
|
| 497 |
+
event = SequenceEndEvent(token.start_mark, token.end_mark)
|
| 498 |
+
self.state = self.states.pop()
|
| 499 |
+
self.marks.pop()
|
| 500 |
+
return event
|
| 501 |
+
|
| 502 |
+
def parse_flow_sequence_entry_mapping_key(self):
|
| 503 |
+
token = self.get_token()
|
| 504 |
+
if not self.check_token(ValueToken,
|
| 505 |
+
FlowEntryToken, FlowSequenceEndToken):
|
| 506 |
+
self.states.append(self.parse_flow_sequence_entry_mapping_value)
|
| 507 |
+
return self.parse_flow_node()
|
| 508 |
+
else:
|
| 509 |
+
self.state = self.parse_flow_sequence_entry_mapping_value
|
| 510 |
+
return self.process_empty_scalar(token.end_mark)
|
| 511 |
+
|
| 512 |
+
def parse_flow_sequence_entry_mapping_value(self):
|
| 513 |
+
if self.check_token(ValueToken):
|
| 514 |
+
token = self.get_token()
|
| 515 |
+
if not self.check_token(FlowEntryToken, FlowSequenceEndToken):
|
| 516 |
+
self.states.append(self.parse_flow_sequence_entry_mapping_end)
|
| 517 |
+
return self.parse_flow_node()
|
| 518 |
+
else:
|
| 519 |
+
self.state = self.parse_flow_sequence_entry_mapping_end
|
| 520 |
+
return self.process_empty_scalar(token.end_mark)
|
| 521 |
+
else:
|
| 522 |
+
self.state = self.parse_flow_sequence_entry_mapping_end
|
| 523 |
+
token = self.peek_token()
|
| 524 |
+
return self.process_empty_scalar(token.start_mark)
|
| 525 |
+
|
| 526 |
+
def parse_flow_sequence_entry_mapping_end(self):
|
| 527 |
+
self.state = self.parse_flow_sequence_entry
|
| 528 |
+
token = self.peek_token()
|
| 529 |
+
return MappingEndEvent(token.start_mark, token.start_mark)
|
| 530 |
+
|
| 531 |
+
# flow_mapping ::= FLOW-MAPPING-START
|
| 532 |
+
# (flow_mapping_entry FLOW-ENTRY)*
|
| 533 |
+
# flow_mapping_entry?
|
| 534 |
+
# FLOW-MAPPING-END
|
| 535 |
+
# flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
|
| 536 |
+
|
| 537 |
+
def parse_flow_mapping_first_key(self):
|
| 538 |
+
token = self.get_token()
|
| 539 |
+
self.marks.append(token.start_mark)
|
| 540 |
+
return self.parse_flow_mapping_key(first=True)
|
| 541 |
+
|
| 542 |
+
def parse_flow_mapping_key(self, first=False):
|
| 543 |
+
if not self.check_token(FlowMappingEndToken):
|
| 544 |
+
if not first:
|
| 545 |
+
if self.check_token(FlowEntryToken):
|
| 546 |
+
self.get_token()
|
| 547 |
+
else:
|
| 548 |
+
token = self.peek_token()
|
| 549 |
+
raise ParserError("while parsing a flow mapping", self.marks[-1],
|
| 550 |
+
"expected ',' or '}', but got %r" % token.id, token.start_mark)
|
| 551 |
+
if self.check_token(KeyToken):
|
| 552 |
+
token = self.get_token()
|
| 553 |
+
if not self.check_token(ValueToken,
|
| 554 |
+
FlowEntryToken, FlowMappingEndToken):
|
| 555 |
+
self.states.append(self.parse_flow_mapping_value)
|
| 556 |
+
return self.parse_flow_node()
|
| 557 |
+
else:
|
| 558 |
+
self.state = self.parse_flow_mapping_value
|
| 559 |
+
return self.process_empty_scalar(token.end_mark)
|
| 560 |
+
elif not self.check_token(FlowMappingEndToken):
|
| 561 |
+
self.states.append(self.parse_flow_mapping_empty_value)
|
| 562 |
+
return self.parse_flow_node()
|
| 563 |
+
token = self.get_token()
|
| 564 |
+
event = MappingEndEvent(token.start_mark, token.end_mark)
|
| 565 |
+
self.state = self.states.pop()
|
| 566 |
+
self.marks.pop()
|
| 567 |
+
return event
|
| 568 |
+
|
| 569 |
+
def parse_flow_mapping_value(self):
|
| 570 |
+
if self.check_token(ValueToken):
|
| 571 |
+
token = self.get_token()
|
| 572 |
+
if not self.check_token(FlowEntryToken, FlowMappingEndToken):
|
| 573 |
+
self.states.append(self.parse_flow_mapping_key)
|
| 574 |
+
return self.parse_flow_node()
|
| 575 |
+
else:
|
| 576 |
+
self.state = self.parse_flow_mapping_key
|
| 577 |
+
return self.process_empty_scalar(token.end_mark)
|
| 578 |
+
else:
|
| 579 |
+
self.state = self.parse_flow_mapping_key
|
| 580 |
+
token = self.peek_token()
|
| 581 |
+
return self.process_empty_scalar(token.start_mark)
|
| 582 |
+
|
| 583 |
+
def parse_flow_mapping_empty_value(self):
|
| 584 |
+
self.state = self.parse_flow_mapping_key
|
| 585 |
+
return self.process_empty_scalar(self.peek_token().start_mark)
|
| 586 |
+
|
| 587 |
+
def process_empty_scalar(self, mark):
|
| 588 |
+
return ScalarEvent(None, None, (True, False), '', mark, mark)
|
| 589 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/reader.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This module contains abstractions for the input stream. You don't have to
|
| 2 |
+
# looks further, there are no pretty code.
|
| 3 |
+
#
|
| 4 |
+
# We define two classes here.
|
| 5 |
+
#
|
| 6 |
+
# Mark(source, line, column)
|
| 7 |
+
# It's just a record and its only use is producing nice error messages.
|
| 8 |
+
# Parser does not use it for any other purposes.
|
| 9 |
+
#
|
| 10 |
+
# Reader(source, data)
|
| 11 |
+
# Reader determines the encoding of `data` and converts it to unicode.
|
| 12 |
+
# Reader provides the following methods and attributes:
|
| 13 |
+
# reader.peek(length=1) - return the next `length` characters
|
| 14 |
+
# reader.forward(length=1) - move the current position to `length` characters.
|
| 15 |
+
# reader.index - the number of the current character.
|
| 16 |
+
# reader.line, stream.column - the line and the column of the current character.
|
| 17 |
+
|
| 18 |
+
__all__ = ['Reader', 'ReaderError']
|
| 19 |
+
|
| 20 |
+
from .error import YAMLError, Mark
|
| 21 |
+
|
| 22 |
+
import codecs, re
|
| 23 |
+
|
| 24 |
+
class ReaderError(YAMLError):
|
| 25 |
+
|
| 26 |
+
def __init__(self, name, position, character, encoding, reason):
|
| 27 |
+
self.name = name
|
| 28 |
+
self.character = character
|
| 29 |
+
self.position = position
|
| 30 |
+
self.encoding = encoding
|
| 31 |
+
self.reason = reason
|
| 32 |
+
|
| 33 |
+
def __str__(self):
|
| 34 |
+
if isinstance(self.character, bytes):
|
| 35 |
+
return "'%s' codec can't decode byte #x%02x: %s\n" \
|
| 36 |
+
" in \"%s\", position %d" \
|
| 37 |
+
% (self.encoding, ord(self.character), self.reason,
|
| 38 |
+
self.name, self.position)
|
| 39 |
+
else:
|
| 40 |
+
return "unacceptable character #x%04x: %s\n" \
|
| 41 |
+
" in \"%s\", position %d" \
|
| 42 |
+
% (self.character, self.reason,
|
| 43 |
+
self.name, self.position)
|
| 44 |
+
|
| 45 |
+
class Reader(object):
|
| 46 |
+
# Reader:
|
| 47 |
+
# - determines the data encoding and converts it to a unicode string,
|
| 48 |
+
# - checks if characters are in allowed range,
|
| 49 |
+
# - adds '\0' to the end.
|
| 50 |
+
|
| 51 |
+
# Reader accepts
|
| 52 |
+
# - a `bytes` object,
|
| 53 |
+
# - a `str` object,
|
| 54 |
+
# - a file-like object with its `read` method returning `str`,
|
| 55 |
+
# - a file-like object with its `read` method returning `unicode`.
|
| 56 |
+
|
| 57 |
+
# Yeah, it's ugly and slow.
|
| 58 |
+
|
| 59 |
+
def __init__(self, stream):
|
| 60 |
+
self.name = None
|
| 61 |
+
self.stream = None
|
| 62 |
+
self.stream_pointer = 0
|
| 63 |
+
self.eof = True
|
| 64 |
+
self.buffer = ''
|
| 65 |
+
self.pointer = 0
|
| 66 |
+
self.raw_buffer = None
|
| 67 |
+
self.raw_decode = None
|
| 68 |
+
self.encoding = None
|
| 69 |
+
self.index = 0
|
| 70 |
+
self.line = 0
|
| 71 |
+
self.column = 0
|
| 72 |
+
if isinstance(stream, str):
|
| 73 |
+
self.name = "<unicode string>"
|
| 74 |
+
self.check_printable(stream)
|
| 75 |
+
self.buffer = stream+'\0'
|
| 76 |
+
elif isinstance(stream, bytes):
|
| 77 |
+
self.name = "<byte string>"
|
| 78 |
+
self.raw_buffer = stream
|
| 79 |
+
self.determine_encoding()
|
| 80 |
+
else:
|
| 81 |
+
self.stream = stream
|
| 82 |
+
self.name = getattr(stream, 'name', "<file>")
|
| 83 |
+
self.eof = False
|
| 84 |
+
self.raw_buffer = None
|
| 85 |
+
self.determine_encoding()
|
| 86 |
+
|
| 87 |
+
def peek(self, index=0):
|
| 88 |
+
try:
|
| 89 |
+
return self.buffer[self.pointer+index]
|
| 90 |
+
except IndexError:
|
| 91 |
+
self.update(index+1)
|
| 92 |
+
return self.buffer[self.pointer+index]
|
| 93 |
+
|
| 94 |
+
def prefix(self, length=1):
|
| 95 |
+
if self.pointer+length >= len(self.buffer):
|
| 96 |
+
self.update(length)
|
| 97 |
+
return self.buffer[self.pointer:self.pointer+length]
|
| 98 |
+
|
| 99 |
+
def forward(self, length=1):
|
| 100 |
+
if self.pointer+length+1 >= len(self.buffer):
|
| 101 |
+
self.update(length+1)
|
| 102 |
+
while length:
|
| 103 |
+
ch = self.buffer[self.pointer]
|
| 104 |
+
self.pointer += 1
|
| 105 |
+
self.index += 1
|
| 106 |
+
if ch in '\n\x85\u2028\u2029' \
|
| 107 |
+
or (ch == '\r' and self.buffer[self.pointer] != '\n'):
|
| 108 |
+
self.line += 1
|
| 109 |
+
self.column = 0
|
| 110 |
+
elif ch != '\uFEFF':
|
| 111 |
+
self.column += 1
|
| 112 |
+
length -= 1
|
| 113 |
+
|
| 114 |
+
def get_mark(self):
|
| 115 |
+
if self.stream is None:
|
| 116 |
+
return Mark(self.name, self.index, self.line, self.column,
|
| 117 |
+
self.buffer, self.pointer)
|
| 118 |
+
else:
|
| 119 |
+
return Mark(self.name, self.index, self.line, self.column,
|
| 120 |
+
None, None)
|
| 121 |
+
|
| 122 |
+
def determine_encoding(self):
|
| 123 |
+
while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2):
|
| 124 |
+
self.update_raw()
|
| 125 |
+
if isinstance(self.raw_buffer, bytes):
|
| 126 |
+
if self.raw_buffer.startswith(codecs.BOM_UTF16_LE):
|
| 127 |
+
self.raw_decode = codecs.utf_16_le_decode
|
| 128 |
+
self.encoding = 'utf-16-le'
|
| 129 |
+
elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE):
|
| 130 |
+
self.raw_decode = codecs.utf_16_be_decode
|
| 131 |
+
self.encoding = 'utf-16-be'
|
| 132 |
+
else:
|
| 133 |
+
self.raw_decode = codecs.utf_8_decode
|
| 134 |
+
self.encoding = 'utf-8'
|
| 135 |
+
self.update(1)
|
| 136 |
+
|
| 137 |
+
NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]')
|
| 138 |
+
def check_printable(self, data):
|
| 139 |
+
match = self.NON_PRINTABLE.search(data)
|
| 140 |
+
if match:
|
| 141 |
+
character = match.group()
|
| 142 |
+
position = self.index+(len(self.buffer)-self.pointer)+match.start()
|
| 143 |
+
raise ReaderError(self.name, position, ord(character),
|
| 144 |
+
'unicode', "special characters are not allowed")
|
| 145 |
+
|
| 146 |
+
def update(self, length):
|
| 147 |
+
if self.raw_buffer is None:
|
| 148 |
+
return
|
| 149 |
+
self.buffer = self.buffer[self.pointer:]
|
| 150 |
+
self.pointer = 0
|
| 151 |
+
while len(self.buffer) < length:
|
| 152 |
+
if not self.eof:
|
| 153 |
+
self.update_raw()
|
| 154 |
+
if self.raw_decode is not None:
|
| 155 |
+
try:
|
| 156 |
+
data, converted = self.raw_decode(self.raw_buffer,
|
| 157 |
+
'strict', self.eof)
|
| 158 |
+
except UnicodeDecodeError as exc:
|
| 159 |
+
character = self.raw_buffer[exc.start]
|
| 160 |
+
if self.stream is not None:
|
| 161 |
+
position = self.stream_pointer-len(self.raw_buffer)+exc.start
|
| 162 |
+
else:
|
| 163 |
+
position = exc.start
|
| 164 |
+
raise ReaderError(self.name, position, character,
|
| 165 |
+
exc.encoding, exc.reason)
|
| 166 |
+
else:
|
| 167 |
+
data = self.raw_buffer
|
| 168 |
+
converted = len(data)
|
| 169 |
+
self.check_printable(data)
|
| 170 |
+
self.buffer += data
|
| 171 |
+
self.raw_buffer = self.raw_buffer[converted:]
|
| 172 |
+
if self.eof:
|
| 173 |
+
self.buffer += '\0'
|
| 174 |
+
self.raw_buffer = None
|
| 175 |
+
break
|
| 176 |
+
|
| 177 |
+
def update_raw(self, size=4096):
|
| 178 |
+
data = self.stream.read(size)
|
| 179 |
+
if self.raw_buffer is None:
|
| 180 |
+
self.raw_buffer = data
|
| 181 |
+
else:
|
| 182 |
+
self.raw_buffer += data
|
| 183 |
+
self.stream_pointer += len(data)
|
| 184 |
+
if not data:
|
| 185 |
+
self.eof = True
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/representer.py
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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64, collections
|
| 9 |
+
|
| 10 |
+
class RepresenterError(YAMLError):
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
class BaseRepresenter:
|
| 14 |
+
|
| 15 |
+
yaml_representers = {}
|
| 16 |
+
yaml_multi_representers = {}
|
| 17 |
+
|
| 18 |
+
def __init__(self, default_style=None, default_flow_style=False, sort_keys=True):
|
| 19 |
+
self.default_style = default_style
|
| 20 |
+
self.sort_keys = sort_keys
|
| 21 |
+
self.default_flow_style = default_flow_style
|
| 22 |
+
self.represented_objects = {}
|
| 23 |
+
self.object_keeper = []
|
| 24 |
+
self.alias_key = None
|
| 25 |
+
|
| 26 |
+
def represent(self, data):
|
| 27 |
+
node = self.represent_data(data)
|
| 28 |
+
self.serialize(node)
|
| 29 |
+
self.represented_objects = {}
|
| 30 |
+
self.object_keeper = []
|
| 31 |
+
self.alias_key = None
|
| 32 |
+
|
| 33 |
+
def represent_data(self, data):
|
| 34 |
+
if self.ignore_aliases(data):
|
| 35 |
+
self.alias_key = None
|
| 36 |
+
else:
|
| 37 |
+
self.alias_key = id(data)
|
| 38 |
+
if self.alias_key is not None:
|
| 39 |
+
if self.alias_key in self.represented_objects:
|
| 40 |
+
node = self.represented_objects[self.alias_key]
|
| 41 |
+
#if node is None:
|
| 42 |
+
# raise RepresenterError("recursive objects are not allowed: %r" % data)
|
| 43 |
+
return node
|
| 44 |
+
#self.represented_objects[alias_key] = None
|
| 45 |
+
self.object_keeper.append(data)
|
| 46 |
+
data_types = type(data).__mro__
|
| 47 |
+
if data_types[0] in self.yaml_representers:
|
| 48 |
+
node = self.yaml_representers[data_types[0]](self, data)
|
| 49 |
+
else:
|
| 50 |
+
for data_type in data_types:
|
| 51 |
+
if data_type in self.yaml_multi_representers:
|
| 52 |
+
node = self.yaml_multi_representers[data_type](self, data)
|
| 53 |
+
break
|
| 54 |
+
else:
|
| 55 |
+
if None in self.yaml_multi_representers:
|
| 56 |
+
node = self.yaml_multi_representers[None](self, data)
|
| 57 |
+
elif None in self.yaml_representers:
|
| 58 |
+
node = self.yaml_representers[None](self, data)
|
| 59 |
+
else:
|
| 60 |
+
node = ScalarNode(None, str(data))
|
| 61 |
+
#if alias_key is not None:
|
| 62 |
+
# self.represented_objects[alias_key] = node
|
| 63 |
+
return node
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def add_representer(cls, data_type, representer):
|
| 67 |
+
if not 'yaml_representers' in cls.__dict__:
|
| 68 |
+
cls.yaml_representers = cls.yaml_representers.copy()
|
| 69 |
+
cls.yaml_representers[data_type] = representer
|
| 70 |
+
|
| 71 |
+
@classmethod
|
| 72 |
+
def add_multi_representer(cls, data_type, representer):
|
| 73 |
+
if not 'yaml_multi_representers' in cls.__dict__:
|
| 74 |
+
cls.yaml_multi_representers = cls.yaml_multi_representers.copy()
|
| 75 |
+
cls.yaml_multi_representers[data_type] = representer
|
| 76 |
+
|
| 77 |
+
def represent_scalar(self, tag, value, style=None):
|
| 78 |
+
if style is None:
|
| 79 |
+
style = self.default_style
|
| 80 |
+
node = ScalarNode(tag, value, style=style)
|
| 81 |
+
if self.alias_key is not None:
|
| 82 |
+
self.represented_objects[self.alias_key] = node
|
| 83 |
+
return node
|
| 84 |
+
|
| 85 |
+
def represent_sequence(self, tag, sequence, flow_style=None):
|
| 86 |
+
value = []
|
| 87 |
+
node = SequenceNode(tag, value, flow_style=flow_style)
|
| 88 |
+
if self.alias_key is not None:
|
| 89 |
+
self.represented_objects[self.alias_key] = node
|
| 90 |
+
best_style = True
|
| 91 |
+
for item in sequence:
|
| 92 |
+
node_item = self.represent_data(item)
|
| 93 |
+
if not (isinstance(node_item, ScalarNode) and not node_item.style):
|
| 94 |
+
best_style = False
|
| 95 |
+
value.append(node_item)
|
| 96 |
+
if flow_style is None:
|
| 97 |
+
if self.default_flow_style is not None:
|
| 98 |
+
node.flow_style = self.default_flow_style
|
| 99 |
+
else:
|
| 100 |
+
node.flow_style = best_style
|
| 101 |
+
return node
|
| 102 |
+
|
| 103 |
+
def represent_mapping(self, tag, mapping, flow_style=None):
|
| 104 |
+
value = []
|
| 105 |
+
node = MappingNode(tag, value, flow_style=flow_style)
|
| 106 |
+
if self.alias_key is not None:
|
| 107 |
+
self.represented_objects[self.alias_key] = node
|
| 108 |
+
best_style = True
|
| 109 |
+
if hasattr(mapping, 'items'):
|
| 110 |
+
mapping = list(mapping.items())
|
| 111 |
+
if self.sort_keys:
|
| 112 |
+
try:
|
| 113 |
+
mapping = sorted(mapping)
|
| 114 |
+
except TypeError:
|
| 115 |
+
pass
|
| 116 |
+
for item_key, item_value in mapping:
|
| 117 |
+
node_key = self.represent_data(item_key)
|
| 118 |
+
node_value = self.represent_data(item_value)
|
| 119 |
+
if not (isinstance(node_key, ScalarNode) and not node_key.style):
|
| 120 |
+
best_style = False
|
| 121 |
+
if not (isinstance(node_value, ScalarNode) and not node_value.style):
|
| 122 |
+
best_style = False
|
| 123 |
+
value.append((node_key, node_value))
|
| 124 |
+
if flow_style is None:
|
| 125 |
+
if self.default_flow_style is not None:
|
| 126 |
+
node.flow_style = self.default_flow_style
|
| 127 |
+
else:
|
| 128 |
+
node.flow_style = best_style
|
| 129 |
+
return node
|
| 130 |
+
|
| 131 |
+
def ignore_aliases(self, data):
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
class SafeRepresenter(BaseRepresenter):
|
| 135 |
+
|
| 136 |
+
def ignore_aliases(self, data):
|
| 137 |
+
if data is None:
|
| 138 |
+
return True
|
| 139 |
+
if isinstance(data, tuple) and data == ():
|
| 140 |
+
return True
|
| 141 |
+
if isinstance(data, (str, bytes, bool, int, float)):
|
| 142 |
+
return True
|
| 143 |
+
|
| 144 |
+
def represent_none(self, data):
|
| 145 |
+
return self.represent_scalar('tag:yaml.org,2002:null', 'null')
|
| 146 |
+
|
| 147 |
+
def represent_str(self, data):
|
| 148 |
+
return self.represent_scalar('tag:yaml.org,2002:str', data)
|
| 149 |
+
|
| 150 |
+
def represent_binary(self, data):
|
| 151 |
+
if hasattr(base64, 'encodebytes'):
|
| 152 |
+
data = base64.encodebytes(data).decode('ascii')
|
| 153 |
+
else:
|
| 154 |
+
data = base64.encodestring(data).decode('ascii')
|
| 155 |
+
return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|')
|
| 156 |
+
|
| 157 |
+
def represent_bool(self, data):
|
| 158 |
+
if data:
|
| 159 |
+
value = 'true'
|
| 160 |
+
else:
|
| 161 |
+
value = 'false'
|
| 162 |
+
return self.represent_scalar('tag:yaml.org,2002:bool', value)
|
| 163 |
+
|
| 164 |
+
def represent_int(self, data):
|
| 165 |
+
return self.represent_scalar('tag:yaml.org,2002:int', str(data))
|
| 166 |
+
|
| 167 |
+
inf_value = 1e300
|
| 168 |
+
while repr(inf_value) != repr(inf_value*inf_value):
|
| 169 |
+
inf_value *= inf_value
|
| 170 |
+
|
| 171 |
+
def represent_float(self, data):
|
| 172 |
+
if data != data or (data == 0.0 and data == 1.0):
|
| 173 |
+
value = '.nan'
|
| 174 |
+
elif data == self.inf_value:
|
| 175 |
+
value = '.inf'
|
| 176 |
+
elif data == -self.inf_value:
|
| 177 |
+
value = '-.inf'
|
| 178 |
+
else:
|
| 179 |
+
value = repr(data).lower()
|
| 180 |
+
# Note that in some cases `repr(data)` represents a float number
|
| 181 |
+
# without the decimal parts. For instance:
|
| 182 |
+
# >>> repr(1e17)
|
| 183 |
+
# '1e17'
|
| 184 |
+
# Unfortunately, this is not a valid float representation according
|
| 185 |
+
# to the definition of the `!!float` tag. We fix this by adding
|
| 186 |
+
# '.0' before the 'e' symbol.
|
| 187 |
+
if '.' not in value and 'e' in value:
|
| 188 |
+
value = value.replace('e', '.0e', 1)
|
| 189 |
+
return self.represent_scalar('tag:yaml.org,2002:float', value)
|
| 190 |
+
|
| 191 |
+
def represent_list(self, data):
|
| 192 |
+
#pairs = (len(data) > 0 and isinstance(data, list))
|
| 193 |
+
#if pairs:
|
| 194 |
+
# for item in data:
|
| 195 |
+
# if not isinstance(item, tuple) or len(item) != 2:
|
| 196 |
+
# pairs = False
|
| 197 |
+
# break
|
| 198 |
+
#if not pairs:
|
| 199 |
+
return self.represent_sequence('tag:yaml.org,2002:seq', data)
|
| 200 |
+
#value = []
|
| 201 |
+
#for item_key, item_value in data:
|
| 202 |
+
# value.append(self.represent_mapping(u'tag:yaml.org,2002:map',
|
| 203 |
+
# [(item_key, item_value)]))
|
| 204 |
+
#return SequenceNode(u'tag:yaml.org,2002:pairs', value)
|
| 205 |
+
|
| 206 |
+
def represent_dict(self, data):
|
| 207 |
+
return self.represent_mapping('tag:yaml.org,2002:map', data)
|
| 208 |
+
|
| 209 |
+
def represent_set(self, data):
|
| 210 |
+
value = {}
|
| 211 |
+
for key in data:
|
| 212 |
+
value[key] = None
|
| 213 |
+
return self.represent_mapping('tag:yaml.org,2002:set', value)
|
| 214 |
+
|
| 215 |
+
def represent_date(self, data):
|
| 216 |
+
value = data.isoformat()
|
| 217 |
+
return self.represent_scalar('tag:yaml.org,2002:timestamp', value)
|
| 218 |
+
|
| 219 |
+
def represent_datetime(self, data):
|
| 220 |
+
value = data.isoformat(' ')
|
| 221 |
+
return self.represent_scalar('tag:yaml.org,2002:timestamp', value)
|
| 222 |
+
|
| 223 |
+
def represent_yaml_object(self, tag, data, cls, flow_style=None):
|
| 224 |
+
if hasattr(data, '__getstate__'):
|
| 225 |
+
state = data.__getstate__()
|
| 226 |
+
else:
|
| 227 |
+
state = data.__dict__.copy()
|
| 228 |
+
return self.represent_mapping(tag, state, flow_style=flow_style)
|
| 229 |
+
|
| 230 |
+
def represent_undefined(self, data):
|
| 231 |
+
raise RepresenterError("cannot represent an object", data)
|
| 232 |
+
|
| 233 |
+
SafeRepresenter.add_representer(type(None),
|
| 234 |
+
SafeRepresenter.represent_none)
|
| 235 |
+
|
| 236 |
+
SafeRepresenter.add_representer(str,
|
| 237 |
+
SafeRepresenter.represent_str)
|
| 238 |
+
|
| 239 |
+
SafeRepresenter.add_representer(bytes,
|
| 240 |
+
SafeRepresenter.represent_binary)
|
| 241 |
+
|
| 242 |
+
SafeRepresenter.add_representer(bool,
|
| 243 |
+
SafeRepresenter.represent_bool)
|
| 244 |
+
|
| 245 |
+
SafeRepresenter.add_representer(int,
|
| 246 |
+
SafeRepresenter.represent_int)
|
| 247 |
+
|
| 248 |
+
SafeRepresenter.add_representer(float,
|
| 249 |
+
SafeRepresenter.represent_float)
|
| 250 |
+
|
| 251 |
+
SafeRepresenter.add_representer(list,
|
| 252 |
+
SafeRepresenter.represent_list)
|
| 253 |
+
|
| 254 |
+
SafeRepresenter.add_representer(tuple,
|
| 255 |
+
SafeRepresenter.represent_list)
|
| 256 |
+
|
| 257 |
+
SafeRepresenter.add_representer(dict,
|
| 258 |
+
SafeRepresenter.represent_dict)
|
| 259 |
+
|
| 260 |
+
SafeRepresenter.add_representer(set,
|
| 261 |
+
SafeRepresenter.represent_set)
|
| 262 |
+
|
| 263 |
+
SafeRepresenter.add_representer(datetime.date,
|
| 264 |
+
SafeRepresenter.represent_date)
|
| 265 |
+
|
| 266 |
+
SafeRepresenter.add_representer(datetime.datetime,
|
| 267 |
+
SafeRepresenter.represent_datetime)
|
| 268 |
+
|
| 269 |
+
SafeRepresenter.add_representer(None,
|
| 270 |
+
SafeRepresenter.represent_undefined)
|
| 271 |
+
|
| 272 |
+
class Representer(SafeRepresenter):
|
| 273 |
+
|
| 274 |
+
def represent_complex(self, data):
|
| 275 |
+
if data.imag == 0.0:
|
| 276 |
+
data = '%r' % data.real
|
| 277 |
+
elif data.real == 0.0:
|
| 278 |
+
data = '%rj' % data.imag
|
| 279 |
+
elif data.imag > 0:
|
| 280 |
+
data = '%r+%rj' % (data.real, data.imag)
|
| 281 |
+
else:
|
| 282 |
+
data = '%r%rj' % (data.real, data.imag)
|
| 283 |
+
return self.represent_scalar('tag:yaml.org,2002:python/complex', data)
|
| 284 |
+
|
| 285 |
+
def represent_tuple(self, data):
|
| 286 |
+
return self.represent_sequence('tag:yaml.org,2002:python/tuple', data)
|
| 287 |
+
|
| 288 |
+
def represent_name(self, data):
|
| 289 |
+
name = '%s.%s' % (data.__module__, data.__name__)
|
| 290 |
+
return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '')
|
| 291 |
+
|
| 292 |
+
def represent_module(self, data):
|
| 293 |
+
return self.represent_scalar(
|
| 294 |
+
'tag:yaml.org,2002:python/module:'+data.__name__, '')
|
| 295 |
+
|
| 296 |
+
def represent_object(self, data):
|
| 297 |
+
# We use __reduce__ API to save the data. data.__reduce__ returns
|
| 298 |
+
# a tuple of length 2-5:
|
| 299 |
+
# (function, args, state, listitems, dictitems)
|
| 300 |
+
|
| 301 |
+
# For reconstructing, we calls function(*args), then set its state,
|
| 302 |
+
# listitems, and dictitems if they are not None.
|
| 303 |
+
|
| 304 |
+
# A special case is when function.__name__ == '__newobj__'. In this
|
| 305 |
+
# case we create the object with args[0].__new__(*args).
|
| 306 |
+
|
| 307 |
+
# Another special case is when __reduce__ returns a string - we don't
|
| 308 |
+
# support it.
|
| 309 |
+
|
| 310 |
+
# We produce a !!python/object, !!python/object/new or
|
| 311 |
+
# !!python/object/apply node.
|
| 312 |
+
|
| 313 |
+
cls = type(data)
|
| 314 |
+
if cls in copyreg.dispatch_table:
|
| 315 |
+
reduce = copyreg.dispatch_table[cls](data)
|
| 316 |
+
elif hasattr(data, '__reduce_ex__'):
|
| 317 |
+
reduce = data.__reduce_ex__(2)
|
| 318 |
+
elif hasattr(data, '__reduce__'):
|
| 319 |
+
reduce = data.__reduce__()
|
| 320 |
+
else:
|
| 321 |
+
raise RepresenterError("cannot represent an object", data)
|
| 322 |
+
reduce = (list(reduce)+[None]*5)[:5]
|
| 323 |
+
function, args, state, listitems, dictitems = reduce
|
| 324 |
+
args = list(args)
|
| 325 |
+
if state is None:
|
| 326 |
+
state = {}
|
| 327 |
+
if listitems is not None:
|
| 328 |
+
listitems = list(listitems)
|
| 329 |
+
if dictitems is not None:
|
| 330 |
+
dictitems = dict(dictitems)
|
| 331 |
+
if function.__name__ == '__newobj__':
|
| 332 |
+
function = args[0]
|
| 333 |
+
args = args[1:]
|
| 334 |
+
tag = 'tag:yaml.org,2002:python/object/new:'
|
| 335 |
+
newobj = True
|
| 336 |
+
else:
|
| 337 |
+
tag = 'tag:yaml.org,2002:python/object/apply:'
|
| 338 |
+
newobj = False
|
| 339 |
+
function_name = '%s.%s' % (function.__module__, function.__name__)
|
| 340 |
+
if not args and not listitems and not dictitems \
|
| 341 |
+
and isinstance(state, dict) and newobj:
|
| 342 |
+
return self.represent_mapping(
|
| 343 |
+
'tag:yaml.org,2002:python/object:'+function_name, state)
|
| 344 |
+
if not listitems and not dictitems \
|
| 345 |
+
and isinstance(state, dict) and not state:
|
| 346 |
+
return self.represent_sequence(tag+function_name, args)
|
| 347 |
+
value = {}
|
| 348 |
+
if args:
|
| 349 |
+
value['args'] = args
|
| 350 |
+
if state or not isinstance(state, dict):
|
| 351 |
+
value['state'] = state
|
| 352 |
+
if listitems:
|
| 353 |
+
value['listitems'] = listitems
|
| 354 |
+
if dictitems:
|
| 355 |
+
value['dictitems'] = dictitems
|
| 356 |
+
return self.represent_mapping(tag+function_name, value)
|
| 357 |
+
|
| 358 |
+
def represent_ordered_dict(self, data):
|
| 359 |
+
# Provide uniform representation across different Python versions.
|
| 360 |
+
data_type = type(data)
|
| 361 |
+
tag = 'tag:yaml.org,2002:python/object/apply:%s.%s' \
|
| 362 |
+
% (data_type.__module__, data_type.__name__)
|
| 363 |
+
items = [[key, value] for key, value in data.items()]
|
| 364 |
+
return self.represent_sequence(tag, [items])
|
| 365 |
+
|
| 366 |
+
Representer.add_representer(complex,
|
| 367 |
+
Representer.represent_complex)
|
| 368 |
+
|
| 369 |
+
Representer.add_representer(tuple,
|
| 370 |
+
Representer.represent_tuple)
|
| 371 |
+
|
| 372 |
+
Representer.add_multi_representer(type,
|
| 373 |
+
Representer.represent_name)
|
| 374 |
+
|
| 375 |
+
Representer.add_representer(collections.OrderedDict,
|
| 376 |
+
Representer.represent_ordered_dict)
|
| 377 |
+
|
| 378 |
+
Representer.add_representer(types.FunctionType,
|
| 379 |
+
Representer.represent_name)
|
| 380 |
+
|
| 381 |
+
Representer.add_representer(types.BuiltinFunctionType,
|
| 382 |
+
Representer.represent_name)
|
| 383 |
+
|
| 384 |
+
Representer.add_representer(types.ModuleType,
|
| 385 |
+
Representer.represent_module)
|
| 386 |
+
|
| 387 |
+
Representer.add_multi_representer(object,
|
| 388 |
+
Representer.represent_object)
|
| 389 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/resolver.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
__all__ = ['BaseResolver', 'Resolver']
|
| 3 |
+
|
| 4 |
+
from .error import *
|
| 5 |
+
from .nodes import *
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
class ResolverError(YAMLError):
|
| 10 |
+
pass
|
| 11 |
+
|
| 12 |
+
class BaseResolver:
|
| 13 |
+
|
| 14 |
+
DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str'
|
| 15 |
+
DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq'
|
| 16 |
+
DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map'
|
| 17 |
+
|
| 18 |
+
yaml_implicit_resolvers = {}
|
| 19 |
+
yaml_path_resolvers = {}
|
| 20 |
+
|
| 21 |
+
def __init__(self):
|
| 22 |
+
self.resolver_exact_paths = []
|
| 23 |
+
self.resolver_prefix_paths = []
|
| 24 |
+
|
| 25 |
+
@classmethod
|
| 26 |
+
def add_implicit_resolver(cls, tag, regexp, first):
|
| 27 |
+
if not 'yaml_implicit_resolvers' in cls.__dict__:
|
| 28 |
+
implicit_resolvers = {}
|
| 29 |
+
for key in cls.yaml_implicit_resolvers:
|
| 30 |
+
implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:]
|
| 31 |
+
cls.yaml_implicit_resolvers = implicit_resolvers
|
| 32 |
+
if first is None:
|
| 33 |
+
first = [None]
|
| 34 |
+
for ch in first:
|
| 35 |
+
cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp))
|
| 36 |
+
|
| 37 |
+
@classmethod
|
| 38 |
+
def add_path_resolver(cls, tag, path, kind=None):
|
| 39 |
+
# Note: `add_path_resolver` is experimental. The API could be changed.
|
| 40 |
+
# `new_path` is a pattern that is matched against the path from the
|
| 41 |
+
# root to the node that is being considered. `node_path` elements are
|
| 42 |
+
# tuples `(node_check, index_check)`. `node_check` is a node class:
|
| 43 |
+
# `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None`
|
| 44 |
+
# matches any kind of a node. `index_check` could be `None`, a boolean
|
| 45 |
+
# value, a string value, or a number. `None` and `False` match against
|
| 46 |
+
# any _value_ of sequence and mapping nodes. `True` matches against
|
| 47 |
+
# any _key_ of a mapping node. A string `index_check` matches against
|
| 48 |
+
# a mapping value that corresponds to a scalar key which content is
|
| 49 |
+
# equal to the `index_check` value. An integer `index_check` matches
|
| 50 |
+
# against a sequence value with the index equal to `index_check`.
|
| 51 |
+
if not 'yaml_path_resolvers' in cls.__dict__:
|
| 52 |
+
cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy()
|
| 53 |
+
new_path = []
|
| 54 |
+
for element in path:
|
| 55 |
+
if isinstance(element, (list, tuple)):
|
| 56 |
+
if len(element) == 2:
|
| 57 |
+
node_check, index_check = element
|
| 58 |
+
elif len(element) == 1:
|
| 59 |
+
node_check = element[0]
|
| 60 |
+
index_check = True
|
| 61 |
+
else:
|
| 62 |
+
raise ResolverError("Invalid path element: %s" % element)
|
| 63 |
+
else:
|
| 64 |
+
node_check = None
|
| 65 |
+
index_check = element
|
| 66 |
+
if node_check is str:
|
| 67 |
+
node_check = ScalarNode
|
| 68 |
+
elif node_check is list:
|
| 69 |
+
node_check = SequenceNode
|
| 70 |
+
elif node_check is dict:
|
| 71 |
+
node_check = MappingNode
|
| 72 |
+
elif node_check not in [ScalarNode, SequenceNode, MappingNode] \
|
| 73 |
+
and not isinstance(node_check, str) \
|
| 74 |
+
and node_check is not None:
|
| 75 |
+
raise ResolverError("Invalid node checker: %s" % node_check)
|
| 76 |
+
if not isinstance(index_check, (str, int)) \
|
| 77 |
+
and index_check is not None:
|
| 78 |
+
raise ResolverError("Invalid index checker: %s" % index_check)
|
| 79 |
+
new_path.append((node_check, index_check))
|
| 80 |
+
if kind is str:
|
| 81 |
+
kind = ScalarNode
|
| 82 |
+
elif kind is list:
|
| 83 |
+
kind = SequenceNode
|
| 84 |
+
elif kind is dict:
|
| 85 |
+
kind = MappingNode
|
| 86 |
+
elif kind not in [ScalarNode, SequenceNode, MappingNode] \
|
| 87 |
+
and kind is not None:
|
| 88 |
+
raise ResolverError("Invalid node kind: %s" % kind)
|
| 89 |
+
cls.yaml_path_resolvers[tuple(new_path), kind] = tag
|
| 90 |
+
|
| 91 |
+
def descend_resolver(self, current_node, current_index):
|
| 92 |
+
if not self.yaml_path_resolvers:
|
| 93 |
+
return
|
| 94 |
+
exact_paths = {}
|
| 95 |
+
prefix_paths = []
|
| 96 |
+
if current_node:
|
| 97 |
+
depth = len(self.resolver_prefix_paths)
|
| 98 |
+
for path, kind in self.resolver_prefix_paths[-1]:
|
| 99 |
+
if self.check_resolver_prefix(depth, path, kind,
|
| 100 |
+
current_node, current_index):
|
| 101 |
+
if len(path) > depth:
|
| 102 |
+
prefix_paths.append((path, kind))
|
| 103 |
+
else:
|
| 104 |
+
exact_paths[kind] = self.yaml_path_resolvers[path, kind]
|
| 105 |
+
else:
|
| 106 |
+
for path, kind in self.yaml_path_resolvers:
|
| 107 |
+
if not path:
|
| 108 |
+
exact_paths[kind] = self.yaml_path_resolvers[path, kind]
|
| 109 |
+
else:
|
| 110 |
+
prefix_paths.append((path, kind))
|
| 111 |
+
self.resolver_exact_paths.append(exact_paths)
|
| 112 |
+
self.resolver_prefix_paths.append(prefix_paths)
|
| 113 |
+
|
| 114 |
+
def ascend_resolver(self):
|
| 115 |
+
if not self.yaml_path_resolvers:
|
| 116 |
+
return
|
| 117 |
+
self.resolver_exact_paths.pop()
|
| 118 |
+
self.resolver_prefix_paths.pop()
|
| 119 |
+
|
| 120 |
+
def check_resolver_prefix(self, depth, path, kind,
|
| 121 |
+
current_node, current_index):
|
| 122 |
+
node_check, index_check = path[depth-1]
|
| 123 |
+
if isinstance(node_check, str):
|
| 124 |
+
if current_node.tag != node_check:
|
| 125 |
+
return
|
| 126 |
+
elif node_check is not None:
|
| 127 |
+
if not isinstance(current_node, node_check):
|
| 128 |
+
return
|
| 129 |
+
if index_check is True and current_index is not None:
|
| 130 |
+
return
|
| 131 |
+
if (index_check is False or index_check is None) \
|
| 132 |
+
and current_index is None:
|
| 133 |
+
return
|
| 134 |
+
if isinstance(index_check, str):
|
| 135 |
+
if not (isinstance(current_index, ScalarNode)
|
| 136 |
+
and index_check == current_index.value):
|
| 137 |
+
return
|
| 138 |
+
elif isinstance(index_check, int) and not isinstance(index_check, bool):
|
| 139 |
+
if index_check != current_index:
|
| 140 |
+
return
|
| 141 |
+
return True
|
| 142 |
+
|
| 143 |
+
def resolve(self, kind, value, implicit):
|
| 144 |
+
if kind is ScalarNode and implicit[0]:
|
| 145 |
+
if value == '':
|
| 146 |
+
resolvers = self.yaml_implicit_resolvers.get('', [])
|
| 147 |
+
else:
|
| 148 |
+
resolvers = self.yaml_implicit_resolvers.get(value[0], [])
|
| 149 |
+
wildcard_resolvers = self.yaml_implicit_resolvers.get(None, [])
|
| 150 |
+
for tag, regexp in resolvers + wildcard_resolvers:
|
| 151 |
+
if regexp.match(value):
|
| 152 |
+
return tag
|
| 153 |
+
implicit = implicit[1]
|
| 154 |
+
if self.yaml_path_resolvers:
|
| 155 |
+
exact_paths = self.resolver_exact_paths[-1]
|
| 156 |
+
if kind in exact_paths:
|
| 157 |
+
return exact_paths[kind]
|
| 158 |
+
if None in exact_paths:
|
| 159 |
+
return exact_paths[None]
|
| 160 |
+
if kind is ScalarNode:
|
| 161 |
+
return self.DEFAULT_SCALAR_TAG
|
| 162 |
+
elif kind is SequenceNode:
|
| 163 |
+
return self.DEFAULT_SEQUENCE_TAG
|
| 164 |
+
elif kind is MappingNode:
|
| 165 |
+
return self.DEFAULT_MAPPING_TAG
|
| 166 |
+
|
| 167 |
+
class Resolver(BaseResolver):
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
Resolver.add_implicit_resolver(
|
| 171 |
+
'tag:yaml.org,2002:bool',
|
| 172 |
+
re.compile(r'''^(?:yes|Yes|YES|no|No|NO
|
| 173 |
+
|true|True|TRUE|false|False|FALSE
|
| 174 |
+
|on|On|ON|off|Off|OFF)$''', re.X),
|
| 175 |
+
list('yYnNtTfFoO'))
|
| 176 |
+
|
| 177 |
+
Resolver.add_implicit_resolver(
|
| 178 |
+
'tag:yaml.org,2002:float',
|
| 179 |
+
re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
|
| 180 |
+
|\.[0-9][0-9_]*(?:[eE][-+][0-9]+)?
|
| 181 |
+
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
|
| 182 |
+
|[-+]?\.(?:inf|Inf|INF)
|
| 183 |
+
|\.(?:nan|NaN|NAN))$''', re.X),
|
| 184 |
+
list('-+0123456789.'))
|
| 185 |
+
|
| 186 |
+
Resolver.add_implicit_resolver(
|
| 187 |
+
'tag:yaml.org,2002:int',
|
| 188 |
+
re.compile(r'''^(?:[-+]?0b[0-1_]+
|
| 189 |
+
|[-+]?0[0-7_]+
|
| 190 |
+
|[-+]?(?:0|[1-9][0-9_]*)
|
| 191 |
+
|[-+]?0x[0-9a-fA-F_]+
|
| 192 |
+
|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
|
| 193 |
+
list('-+0123456789'))
|
| 194 |
+
|
| 195 |
+
Resolver.add_implicit_resolver(
|
| 196 |
+
'tag:yaml.org,2002:merge',
|
| 197 |
+
re.compile(r'^(?:<<)$'),
|
| 198 |
+
['<'])
|
| 199 |
+
|
| 200 |
+
Resolver.add_implicit_resolver(
|
| 201 |
+
'tag:yaml.org,2002:null',
|
| 202 |
+
re.compile(r'''^(?: ~
|
| 203 |
+
|null|Null|NULL
|
| 204 |
+
| )$''', re.X),
|
| 205 |
+
['~', 'n', 'N', ''])
|
| 206 |
+
|
| 207 |
+
Resolver.add_implicit_resolver(
|
| 208 |
+
'tag:yaml.org,2002:timestamp',
|
| 209 |
+
re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
|
| 210 |
+
|[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
|
| 211 |
+
(?:[Tt]|[ \t]+)[0-9][0-9]?
|
| 212 |
+
:[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)?
|
| 213 |
+
(?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
|
| 214 |
+
list('0123456789'))
|
| 215 |
+
|
| 216 |
+
Resolver.add_implicit_resolver(
|
| 217 |
+
'tag:yaml.org,2002:value',
|
| 218 |
+
re.compile(r'^(?:=)$'),
|
| 219 |
+
['='])
|
| 220 |
+
|
| 221 |
+
# The following resolver is only for documentation purposes. It cannot work
|
| 222 |
+
# because plain scalars cannot start with '!', '&', or '*'.
|
| 223 |
+
Resolver.add_implicit_resolver(
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Scanner produces tokens of the following types:
|
| 3 |
+
# STREAM-START
|
| 4 |
+
# STREAM-END
|
| 5 |
+
# DIRECTIVE(name, value)
|
| 6 |
+
# DOCUMENT-START
|
| 7 |
+
# DOCUMENT-END
|
| 8 |
+
# BLOCK-SEQUENCE-START
|
| 9 |
+
# BLOCK-MAPPING-START
|
| 10 |
+
# BLOCK-END
|
| 11 |
+
# FLOW-SEQUENCE-START
|
| 12 |
+
# FLOW-MAPPING-START
|
| 13 |
+
# FLOW-SEQUENCE-END
|
| 14 |
+
# FLOW-MAPPING-END
|
| 15 |
+
# BLOCK-ENTRY
|
| 16 |
+
# FLOW-ENTRY
|
| 17 |
+
# KEY
|
| 18 |
+
# VALUE
|
| 19 |
+
# ALIAS(value)
|
| 20 |
+
# ANCHOR(value)
|
| 21 |
+
# TAG(value)
|
| 22 |
+
# SCALAR(value, plain, style)
|
| 23 |
+
#
|
| 24 |
+
# Read comments in the Scanner code for more details.
|
| 25 |
+
#
|
| 26 |
+
|
| 27 |
+
__all__ = ['Scanner', 'ScannerError']
|
| 28 |
+
|
| 29 |
+
from .error import MarkedYAMLError
|
| 30 |
+
from .tokens import *
|
| 31 |
+
|
| 32 |
+
class ScannerError(MarkedYAMLError):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
class SimpleKey:
|
| 36 |
+
# See below simple keys treatment.
|
| 37 |
+
|
| 38 |
+
def __init__(self, token_number, required, index, line, column, mark):
|
| 39 |
+
self.token_number = token_number
|
| 40 |
+
self.required = required
|
| 41 |
+
self.index = index
|
| 42 |
+
self.line = line
|
| 43 |
+
self.column = column
|
| 44 |
+
self.mark = mark
|
| 45 |
+
|
| 46 |
+
class Scanner:
|
| 47 |
+
|
| 48 |
+
def __init__(self):
|
| 49 |
+
"""Initialize the scanner."""
|
| 50 |
+
# It is assumed that Scanner and Reader will have a common descendant.
|
| 51 |
+
# Reader do the dirty work of checking for BOM and converting the
|
| 52 |
+
# input data to Unicode. It also adds NUL to the end.
|
| 53 |
+
#
|
| 54 |
+
# Reader supports the following methods
|
| 55 |
+
# self.peek(i=0) # peek the next i-th character
|
| 56 |
+
# self.prefix(l=1) # peek the next l characters
|
| 57 |
+
# self.forward(l=1) # read the next l characters and move the pointer.
|
| 58 |
+
|
| 59 |
+
# Had we reached the end of the stream?
|
| 60 |
+
self.done = False
|
| 61 |
+
|
| 62 |
+
# The number of unclosed '{' and '['. `flow_level == 0` means block
|
| 63 |
+
# context.
|
| 64 |
+
self.flow_level = 0
|
| 65 |
+
|
| 66 |
+
# List of processed tokens that are not yet emitted.
|
| 67 |
+
self.tokens = []
|
| 68 |
+
|
| 69 |
+
# Add the STREAM-START token.
|
| 70 |
+
self.fetch_stream_start()
|
| 71 |
+
|
| 72 |
+
# Number of tokens that were emitted through the `get_token` method.
|
| 73 |
+
self.tokens_taken = 0
|
| 74 |
+
|
| 75 |
+
# The current indentation level.
|
| 76 |
+
self.indent = -1
|
| 77 |
+
|
| 78 |
+
# Past indentation levels.
|
| 79 |
+
self.indents = []
|
| 80 |
+
|
| 81 |
+
# Variables related to simple keys treatment.
|
| 82 |
+
|
| 83 |
+
# A simple key is a key that is not denoted by the '?' indicator.
|
| 84 |
+
# Example of simple keys:
|
| 85 |
+
# ---
|
| 86 |
+
# block simple key: value
|
| 87 |
+
# ? not a simple key:
|
| 88 |
+
# : { flow simple key: value }
|
| 89 |
+
# We emit the KEY token before all keys, so when we find a potential
|
| 90 |
+
# simple key, we try to locate the corresponding ':' indicator.
|
| 91 |
+
# Simple keys should be limited to a single line and 1024 characters.
|
| 92 |
+
|
| 93 |
+
# Can a simple key start at the current position? A simple key may
|
| 94 |
+
# start:
|
| 95 |
+
# - at the beginning of the line, not counting indentation spaces
|
| 96 |
+
# (in block context),
|
| 97 |
+
# - after '{', '[', ',' (in the flow context),
|
| 98 |
+
# - after '?', ':', '-' (in the block context).
|
| 99 |
+
# In the block context, this flag also signifies if a block collection
|
| 100 |
+
# may start at the current position.
|
| 101 |
+
self.allow_simple_key = True
|
| 102 |
+
|
| 103 |
+
# Keep track of possible simple keys. This is a dictionary. The key
|
| 104 |
+
# is `flow_level`; there can be no more that one possible simple key
|
| 105 |
+
# for each level. The value is a SimpleKey record:
|
| 106 |
+
# (token_number, required, index, line, column, mark)
|
| 107 |
+
# A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow),
|
| 108 |
+
# '[', or '{' tokens.
|
| 109 |
+
self.possible_simple_keys = {}
|
| 110 |
+
|
| 111 |
+
# Public methods.
|
| 112 |
+
|
| 113 |
+
def check_token(self, *choices):
|
| 114 |
+
# Check if the next token is one of the given types.
|
| 115 |
+
while self.need_more_tokens():
|
| 116 |
+
self.fetch_more_tokens()
|
| 117 |
+
if self.tokens:
|
| 118 |
+
if not choices:
|
| 119 |
+
return True
|
| 120 |
+
for choice in choices:
|
| 121 |
+
if isinstance(self.tokens[0], choice):
|
| 122 |
+
return True
|
| 123 |
+
return False
|
| 124 |
+
|
| 125 |
+
def peek_token(self):
|
| 126 |
+
# Return the next token, but do not delete if from the queue.
|
| 127 |
+
# Return None if no more tokens.
|
| 128 |
+
while self.need_more_tokens():
|
| 129 |
+
self.fetch_more_tokens()
|
| 130 |
+
if self.tokens:
|
| 131 |
+
return self.tokens[0]
|
| 132 |
+
else:
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
def get_token(self):
|
| 136 |
+
# Return the next token.
|
| 137 |
+
while self.need_more_tokens():
|
| 138 |
+
self.fetch_more_tokens()
|
| 139 |
+
if self.tokens:
|
| 140 |
+
self.tokens_taken += 1
|
| 141 |
+
return self.tokens.pop(0)
|
| 142 |
+
|
| 143 |
+
# Private methods.
|
| 144 |
+
|
| 145 |
+
def need_more_tokens(self):
|
| 146 |
+
if self.done:
|
| 147 |
+
return False
|
| 148 |
+
if not self.tokens:
|
| 149 |
+
return True
|
| 150 |
+
# The current token may be a potential simple key, so we
|
| 151 |
+
# need to look further.
|
| 152 |
+
self.stale_possible_simple_keys()
|
| 153 |
+
if self.next_possible_simple_key() == self.tokens_taken:
|
| 154 |
+
return True
|
| 155 |
+
|
| 156 |
+
def fetch_more_tokens(self):
|
| 157 |
+
|
| 158 |
+
# Eat whitespaces and comments until we reach the next token.
|
| 159 |
+
self.scan_to_next_token()
|
| 160 |
+
|
| 161 |
+
# Remove obsolete possible simple keys.
|
| 162 |
+
self.stale_possible_simple_keys()
|
| 163 |
+
|
| 164 |
+
# Compare the current indentation and column. It may add some tokens
|
| 165 |
+
# and decrease the current indentation level.
|
| 166 |
+
self.unwind_indent(self.column)
|
| 167 |
+
|
| 168 |
+
# Peek the next character.
|
| 169 |
+
ch = self.peek()
|
| 170 |
+
|
| 171 |
+
# Is it the end of stream?
|
| 172 |
+
if ch == '\0':
|
| 173 |
+
return self.fetch_stream_end()
|
| 174 |
+
|
| 175 |
+
# Is it a directive?
|
| 176 |
+
if ch == '%' and self.check_directive():
|
| 177 |
+
return self.fetch_directive()
|
| 178 |
+
|
| 179 |
+
# Is it the document start?
|
| 180 |
+
if ch == '-' and self.check_document_start():
|
| 181 |
+
return self.fetch_document_start()
|
| 182 |
+
|
| 183 |
+
# Is it the document end?
|
| 184 |
+
if ch == '.' and self.check_document_end():
|
| 185 |
+
return self.fetch_document_end()
|
| 186 |
+
|
| 187 |
+
# TODO: support for BOM within a stream.
|
| 188 |
+
#if ch == '\uFEFF':
|
| 189 |
+
# return self.fetch_bom() <-- issue BOMToken
|
| 190 |
+
|
| 191 |
+
# Note: the order of the following checks is NOT significant.
|
| 192 |
+
|
| 193 |
+
# Is it the flow sequence start indicator?
|
| 194 |
+
if ch == '[':
|
| 195 |
+
return self.fetch_flow_sequence_start()
|
| 196 |
+
|
| 197 |
+
# Is it the flow mapping start indicator?
|
| 198 |
+
if ch == '{':
|
| 199 |
+
return self.fetch_flow_mapping_start()
|
| 200 |
+
|
| 201 |
+
# Is it the flow sequence end indicator?
|
| 202 |
+
if ch == ']':
|
| 203 |
+
return self.fetch_flow_sequence_end()
|
| 204 |
+
|
| 205 |
+
# Is it the flow mapping end indicator?
|
| 206 |
+
if ch == '}':
|
| 207 |
+
return self.fetch_flow_mapping_end()
|
| 208 |
+
|
| 209 |
+
# Is it the flow entry indicator?
|
| 210 |
+
if ch == ',':
|
| 211 |
+
return self.fetch_flow_entry()
|
| 212 |
+
|
| 213 |
+
# Is it the block entry indicator?
|
| 214 |
+
if ch == '-' and self.check_block_entry():
|
| 215 |
+
return self.fetch_block_entry()
|
| 216 |
+
|
| 217 |
+
# Is it the key indicator?
|
| 218 |
+
if ch == '?' and self.check_key():
|
| 219 |
+
return self.fetch_key()
|
| 220 |
+
|
| 221 |
+
# Is it the value indicator?
|
| 222 |
+
if ch == ':' and self.check_value():
|
| 223 |
+
return self.fetch_value()
|
| 224 |
+
|
| 225 |
+
# Is it an alias?
|
| 226 |
+
if ch == '*':
|
| 227 |
+
return self.fetch_alias()
|
| 228 |
+
|
| 229 |
+
# Is it an anchor?
|
| 230 |
+
if ch == '&':
|
| 231 |
+
return self.fetch_anchor()
|
| 232 |
+
|
| 233 |
+
# Is it a tag?
|
| 234 |
+
if ch == '!':
|
| 235 |
+
return self.fetch_tag()
|
| 236 |
+
|
| 237 |
+
# Is it a literal scalar?
|
| 238 |
+
if ch == '|' and not self.flow_level:
|
| 239 |
+
return self.fetch_literal()
|
| 240 |
+
|
| 241 |
+
# Is it a folded scalar?
|
| 242 |
+
if ch == '>' and not self.flow_level:
|
| 243 |
+
return self.fetch_folded()
|
| 244 |
+
|
| 245 |
+
# Is it a single quoted scalar?
|
| 246 |
+
if ch == '\'':
|
| 247 |
+
return self.fetch_single()
|
| 248 |
+
|
| 249 |
+
# Is it a double quoted scalar?
|
| 250 |
+
if ch == '\"':
|
| 251 |
+
return self.fetch_double()
|
| 252 |
+
|
| 253 |
+
# It must be a plain scalar then.
|
| 254 |
+
if self.check_plain():
|
| 255 |
+
return self.fetch_plain()
|
| 256 |
+
|
| 257 |
+
# No? It's an error. Let's produce a nice error message.
|
| 258 |
+
raise ScannerError("while scanning for the next token", None,
|
| 259 |
+
"found character %r that cannot start any token" % ch,
|
| 260 |
+
self.get_mark())
|
| 261 |
+
|
| 262 |
+
# Simple keys treatment.
|
| 263 |
+
|
| 264 |
+
def next_possible_simple_key(self):
|
| 265 |
+
# Return the number of the nearest possible simple key. Actually we
|
| 266 |
+
# don't need to loop through the whole dictionary. We may replace it
|
| 267 |
+
# with the following code:
|
| 268 |
+
# if not self.possible_simple_keys:
|
| 269 |
+
# return None
|
| 270 |
+
# return self.possible_simple_keys[
|
| 271 |
+
# min(self.possible_simple_keys.keys())].token_number
|
| 272 |
+
min_token_number = None
|
| 273 |
+
for level in self.possible_simple_keys:
|
| 274 |
+
key = self.possible_simple_keys[level]
|
| 275 |
+
if min_token_number is None or key.token_number < min_token_number:
|
| 276 |
+
min_token_number = key.token_number
|
| 277 |
+
return min_token_number
|
| 278 |
+
|
| 279 |
+
def stale_possible_simple_keys(self):
|
| 280 |
+
# Remove entries that are no longer possible simple keys. According to
|
| 281 |
+
# the YAML specification, simple keys
|
| 282 |
+
# - should be limited to a single line,
|
| 283 |
+
# - should be no longer than 1024 characters.
|
| 284 |
+
# Disabling this procedure will allow simple keys of any length and
|
| 285 |
+
# height (may cause problems if indentation is broken though).
|
| 286 |
+
for level in list(self.possible_simple_keys):
|
| 287 |
+
key = self.possible_simple_keys[level]
|
| 288 |
+
if key.line != self.line \
|
| 289 |
+
or self.index-key.index > 1024:
|
| 290 |
+
if key.required:
|
| 291 |
+
raise ScannerError("while scanning a simple key", key.mark,
|
| 292 |
+
"could not find expected ':'", self.get_mark())
|
| 293 |
+
del self.possible_simple_keys[level]
|
| 294 |
+
|
| 295 |
+
def save_possible_simple_key(self):
|
| 296 |
+
# The next token may start a simple key. We check if it's possible
|
| 297 |
+
# and save its position. This function is called for
|
| 298 |
+
# ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'.
|
| 299 |
+
|
| 300 |
+
# Check if a simple key is required at the current position.
|
| 301 |
+
required = not self.flow_level and self.indent == self.column
|
| 302 |
+
|
| 303 |
+
# The next token might be a simple key. Let's save it's number and
|
| 304 |
+
# position.
|
| 305 |
+
if self.allow_simple_key:
|
| 306 |
+
self.remove_possible_simple_key()
|
| 307 |
+
token_number = self.tokens_taken+len(self.tokens)
|
| 308 |
+
key = SimpleKey(token_number, required,
|
| 309 |
+
self.index, self.line, self.column, self.get_mark())
|
| 310 |
+
self.possible_simple_keys[self.flow_level] = key
|
| 311 |
+
|
| 312 |
+
def remove_possible_simple_key(self):
|
| 313 |
+
# Remove the saved possible key position at the current flow level.
|
| 314 |
+
if self.flow_level in self.possible_simple_keys:
|
| 315 |
+
key = self.possible_simple_keys[self.flow_level]
|
| 316 |
+
|
| 317 |
+
if key.required:
|
| 318 |
+
raise ScannerError("while scanning a simple key", key.mark,
|
| 319 |
+
"could not find expected ':'", self.get_mark())
|
| 320 |
+
|
| 321 |
+
del self.possible_simple_keys[self.flow_level]
|
| 322 |
+
|
| 323 |
+
# Indentation functions.
|
| 324 |
+
|
| 325 |
+
def unwind_indent(self, column):
|
| 326 |
+
|
| 327 |
+
## In flow context, tokens should respect indentation.
|
| 328 |
+
## Actually the condition should be `self.indent >= column` according to
|
| 329 |
+
## the spec. But this condition will prohibit intuitively correct
|
| 330 |
+
## constructions such as
|
| 331 |
+
## key : {
|
| 332 |
+
## }
|
| 333 |
+
#if self.flow_level and self.indent > column:
|
| 334 |
+
# raise ScannerError(None, None,
|
| 335 |
+
# "invalid indentation or unclosed '[' or '{'",
|
| 336 |
+
# self.get_mark())
|
| 337 |
+
|
| 338 |
+
# In the flow context, indentation is ignored. We make the scanner less
|
| 339 |
+
# restrictive then specification requires.
|
| 340 |
+
if self.flow_level:
|
| 341 |
+
return
|
| 342 |
+
|
| 343 |
+
# In block context, we may need to issue the BLOCK-END tokens.
|
| 344 |
+
while self.indent > column:
|
| 345 |
+
mark = self.get_mark()
|
| 346 |
+
self.indent = self.indents.pop()
|
| 347 |
+
self.tokens.append(BlockEndToken(mark, mark))
|
| 348 |
+
|
| 349 |
+
def add_indent(self, column):
|
| 350 |
+
# Check if we need to increase indentation.
|
| 351 |
+
if self.indent < column:
|
| 352 |
+
self.indents.append(self.indent)
|
| 353 |
+
self.indent = column
|
| 354 |
+
return True
|
| 355 |
+
return False
|
| 356 |
+
|
| 357 |
+
# Fetchers.
|
| 358 |
+
|
| 359 |
+
def fetch_stream_start(self):
|
| 360 |
+
# We always add STREAM-START as the first token and STREAM-END as the
|
| 361 |
+
# last token.
|
| 362 |
+
|
| 363 |
+
# Read the token.
|
| 364 |
+
mark = self.get_mark()
|
| 365 |
+
|
| 366 |
+
# Add STREAM-START.
|
| 367 |
+
self.tokens.append(StreamStartToken(mark, mark,
|
| 368 |
+
encoding=self.encoding))
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def fetch_stream_end(self):
|
| 372 |
+
|
| 373 |
+
# Set the current indentation to -1.
|
| 374 |
+
self.unwind_indent(-1)
|
| 375 |
+
|
| 376 |
+
# Reset simple keys.
|
| 377 |
+
self.remove_possible_simple_key()
|
| 378 |
+
self.allow_simple_key = False
|
| 379 |
+
self.possible_simple_keys = {}
|
| 380 |
+
|
| 381 |
+
# Read the token.
|
| 382 |
+
mark = self.get_mark()
|
| 383 |
+
|
| 384 |
+
# Add STREAM-END.
|
| 385 |
+
self.tokens.append(StreamEndToken(mark, mark))
|
| 386 |
+
|
| 387 |
+
# The steam is finished.
|
| 388 |
+
self.done = True
|
| 389 |
+
|
| 390 |
+
def fetch_directive(self):
|
| 391 |
+
|
| 392 |
+
# Set the current indentation to -1.
|
| 393 |
+
self.unwind_indent(-1)
|
| 394 |
+
|
| 395 |
+
# Reset simple keys.
|
| 396 |
+
self.remove_possible_simple_key()
|
| 397 |
+
self.allow_simple_key = False
|
| 398 |
+
|
| 399 |
+
# Scan and add DIRECTIVE.
|
| 400 |
+
self.tokens.append(self.scan_directive())
|
| 401 |
+
|
| 402 |
+
def fetch_document_start(self):
|
| 403 |
+
self.fetch_document_indicator(DocumentStartToken)
|
| 404 |
+
|
| 405 |
+
def fetch_document_end(self):
|
| 406 |
+
self.fetch_document_indicator(DocumentEndToken)
|
| 407 |
+
|
| 408 |
+
def fetch_document_indicator(self, TokenClass):
|
| 409 |
+
|
| 410 |
+
# Set the current indentation to -1.
|
| 411 |
+
self.unwind_indent(-1)
|
| 412 |
+
|
| 413 |
+
# Reset simple keys. Note that there could not be a block collection
|
| 414 |
+
# after '---'.
|
| 415 |
+
self.remove_possible_simple_key()
|
| 416 |
+
self.allow_simple_key = False
|
| 417 |
+
|
| 418 |
+
# Add DOCUMENT-START or DOCUMENT-END.
|
| 419 |
+
start_mark = self.get_mark()
|
| 420 |
+
self.forward(3)
|
| 421 |
+
end_mark = self.get_mark()
|
| 422 |
+
self.tokens.append(TokenClass(start_mark, end_mark))
|
| 423 |
+
|
| 424 |
+
def fetch_flow_sequence_start(self):
|
| 425 |
+
self.fetch_flow_collection_start(FlowSequenceStartToken)
|
| 426 |
+
|
| 427 |
+
def fetch_flow_mapping_start(self):
|
| 428 |
+
self.fetch_flow_collection_start(FlowMappingStartToken)
|
| 429 |
+
|
| 430 |
+
def fetch_flow_collection_start(self, TokenClass):
|
| 431 |
+
|
| 432 |
+
# '[' and '{' may start a simple key.
|
| 433 |
+
self.save_possible_simple_key()
|
| 434 |
+
|
| 435 |
+
# Increase the flow level.
|
| 436 |
+
self.flow_level += 1
|
| 437 |
+
|
| 438 |
+
# Simple keys are allowed after '[' and '{'.
|
| 439 |
+
self.allow_simple_key = True
|
| 440 |
+
|
| 441 |
+
# Add FLOW-SEQUENCE-START or FLOW-MAPPING-START.
|
| 442 |
+
start_mark = self.get_mark()
|
| 443 |
+
self.forward()
|
| 444 |
+
end_mark = self.get_mark()
|
| 445 |
+
self.tokens.append(TokenClass(start_mark, end_mark))
|
| 446 |
+
|
| 447 |
+
def fetch_flow_sequence_end(self):
|
| 448 |
+
self.fetch_flow_collection_end(FlowSequenceEndToken)
|
| 449 |
+
|
| 450 |
+
def fetch_flow_mapping_end(self):
|
| 451 |
+
self.fetch_flow_collection_end(FlowMappingEndToken)
|
| 452 |
+
|
| 453 |
+
def fetch_flow_collection_end(self, TokenClass):
|
| 454 |
+
|
| 455 |
+
# Reset possible simple key on the current level.
|
| 456 |
+
self.remove_possible_simple_key()
|
| 457 |
+
|
| 458 |
+
# Decrease the flow level.
|
| 459 |
+
self.flow_level -= 1
|
| 460 |
+
|
| 461 |
+
# No simple keys after ']' or '}'.
|
| 462 |
+
self.allow_simple_key = False
|
| 463 |
+
|
| 464 |
+
# Add FLOW-SEQUENCE-END or FLOW-MAPPING-END.
|
| 465 |
+
start_mark = self.get_mark()
|
| 466 |
+
self.forward()
|
| 467 |
+
end_mark = self.get_mark()
|
| 468 |
+
self.tokens.append(TokenClass(start_mark, end_mark))
|
| 469 |
+
|
| 470 |
+
def fetch_flow_entry(self):
|
| 471 |
+
|
| 472 |
+
# Simple keys are allowed after ','.
|
| 473 |
+
self.allow_simple_key = True
|
| 474 |
+
|
| 475 |
+
# Reset possible simple key on the current level.
|
| 476 |
+
self.remove_possible_simple_key()
|
| 477 |
+
|
| 478 |
+
# Add FLOW-ENTRY.
|
| 479 |
+
start_mark = self.get_mark()
|
| 480 |
+
self.forward()
|
| 481 |
+
end_mark = self.get_mark()
|
| 482 |
+
self.tokens.append(FlowEntryToken(start_mark, end_mark))
|
| 483 |
+
|
| 484 |
+
def fetch_block_entry(self):
|
| 485 |
+
|
| 486 |
+
# Block context needs additional checks.
|
| 487 |
+
if not self.flow_level:
|
| 488 |
+
|
| 489 |
+
# Are we allowed to start a new entry?
|
| 490 |
+
if not self.allow_simple_key:
|
| 491 |
+
raise ScannerError(None, None,
|
| 492 |
+
"sequence entries are not allowed here",
|
| 493 |
+
self.get_mark())
|
| 494 |
+
|
| 495 |
+
# We may need to add BLOCK-SEQUENCE-START.
|
| 496 |
+
if self.add_indent(self.column):
|
| 497 |
+
mark = self.get_mark()
|
| 498 |
+
self.tokens.append(BlockSequenceStartToken(mark, mark))
|
| 499 |
+
|
| 500 |
+
# It's an error for the block entry to occur in the flow context,
|
| 501 |
+
# but we let the parser detect this.
|
| 502 |
+
else:
|
| 503 |
+
pass
|
| 504 |
+
|
| 505 |
+
# Simple keys are allowed after '-'.
|
| 506 |
+
self.allow_simple_key = True
|
| 507 |
+
|
| 508 |
+
# Reset possible simple key on the current level.
|
| 509 |
+
self.remove_possible_simple_key()
|
| 510 |
+
|
| 511 |
+
# Add BLOCK-ENTRY.
|
| 512 |
+
start_mark = self.get_mark()
|
| 513 |
+
self.forward()
|
| 514 |
+
end_mark = self.get_mark()
|
| 515 |
+
self.tokens.append(BlockEntryToken(start_mark, end_mark))
|
| 516 |
+
|
| 517 |
+
def fetch_key(self):
|
| 518 |
+
|
| 519 |
+
# Block context needs additional checks.
|
| 520 |
+
if not self.flow_level:
|
| 521 |
+
|
| 522 |
+
# Are we allowed to start a key (not necessary a simple)?
|
| 523 |
+
if not self.allow_simple_key:
|
| 524 |
+
raise ScannerError(None, None,
|
| 525 |
+
"mapping keys are not allowed here",
|
| 526 |
+
self.get_mark())
|
| 527 |
+
|
| 528 |
+
# We may need to add BLOCK-MAPPING-START.
|
| 529 |
+
if self.add_indent(self.column):
|
| 530 |
+
mark = self.get_mark()
|
| 531 |
+
self.tokens.append(BlockMappingStartToken(mark, mark))
|
| 532 |
+
|
| 533 |
+
# Simple keys are allowed after '?' in the block context.
|
| 534 |
+
self.allow_simple_key = not self.flow_level
|
| 535 |
+
|
| 536 |
+
# Reset possible simple key on the current level.
|
| 537 |
+
self.remove_possible_simple_key()
|
| 538 |
+
|
| 539 |
+
# Add KEY.
|
| 540 |
+
start_mark = self.get_mark()
|
| 541 |
+
self.forward()
|
| 542 |
+
end_mark = self.get_mark()
|
| 543 |
+
self.tokens.append(KeyToken(start_mark, end_mark))
|
| 544 |
+
|
| 545 |
+
def fetch_value(self):
|
| 546 |
+
|
| 547 |
+
# Do we determine a simple key?
|
| 548 |
+
if self.flow_level in self.possible_simple_keys:
|
| 549 |
+
|
| 550 |
+
# Add KEY.
|
| 551 |
+
key = self.possible_simple_keys[self.flow_level]
|
| 552 |
+
del self.possible_simple_keys[self.flow_level]
|
| 553 |
+
self.tokens.insert(key.token_number-self.tokens_taken,
|
| 554 |
+
KeyToken(key.mark, key.mark))
|
| 555 |
+
|
| 556 |
+
# If this key starts a new block mapping, we need to add
|
| 557 |
+
# BLOCK-MAPPING-START.
|
| 558 |
+
if not self.flow_level:
|
| 559 |
+
if self.add_indent(key.column):
|
| 560 |
+
self.tokens.insert(key.token_number-self.tokens_taken,
|
| 561 |
+
BlockMappingStartToken(key.mark, key.mark))
|
| 562 |
+
|
| 563 |
+
# There cannot be two simple keys one after another.
|
| 564 |
+
self.allow_simple_key = False
|
| 565 |
+
|
| 566 |
+
# It must be a part of a complex key.
|
| 567 |
+
else:
|
| 568 |
+
|
| 569 |
+
# Block context needs additional checks.
|
| 570 |
+
# (Do we really need them? They will be caught by the parser
|
| 571 |
+
# anyway.)
|
| 572 |
+
if not self.flow_level:
|
| 573 |
+
|
| 574 |
+
# We are allowed to start a complex value if and only if
|
| 575 |
+
# we can start a simple key.
|
| 576 |
+
if not self.allow_simple_key:
|
| 577 |
+
raise ScannerError(None, None,
|
| 578 |
+
"mapping values are not allowed here",
|
| 579 |
+
self.get_mark())
|
| 580 |
+
|
| 581 |
+
# If this value starts a new block mapping, we need to add
|
| 582 |
+
# BLOCK-MAPPING-START. It will be detected as an error later by
|
| 583 |
+
# the parser.
|
| 584 |
+
if not self.flow_level:
|
| 585 |
+
if self.add_indent(self.column):
|
| 586 |
+
mark = self.get_mark()
|
| 587 |
+
self.tokens.append(BlockMappingStartToken(mark, mark))
|
| 588 |
+
|
| 589 |
+
# Simple keys are allowed after ':' in the block context.
|
| 590 |
+
self.allow_simple_key = not self.flow_level
|
| 591 |
+
|
| 592 |
+
# Reset possible simple key on the current level.
|
| 593 |
+
self.remove_possible_simple_key()
|
| 594 |
+
|
| 595 |
+
# Add VALUE.
|
| 596 |
+
start_mark = self.get_mark()
|
| 597 |
+
self.forward()
|
| 598 |
+
end_mark = self.get_mark()
|
| 599 |
+
self.tokens.append(ValueToken(start_mark, end_mark))
|
| 600 |
+
|
| 601 |
+
def fetch_alias(self):
|
| 602 |
+
|
| 603 |
+
# ALIAS could be a simple key.
|
| 604 |
+
self.save_possible_simple_key()
|
| 605 |
+
|
| 606 |
+
# No simple keys after ALIAS.
|
| 607 |
+
self.allow_simple_key = False
|
| 608 |
+
|
| 609 |
+
# Scan and add ALIAS.
|
| 610 |
+
self.tokens.append(self.scan_anchor(AliasToken))
|
| 611 |
+
|
| 612 |
+
def fetch_anchor(self):
|
| 613 |
+
|
| 614 |
+
# ANCHOR could start a simple key.
|
| 615 |
+
self.save_possible_simple_key()
|
| 616 |
+
|
| 617 |
+
# No simple keys after ANCHOR.
|
| 618 |
+
self.allow_simple_key = False
|
| 619 |
+
|
| 620 |
+
# Scan and add ANCHOR.
|
| 621 |
+
self.tokens.append(self.scan_anchor(AnchorToken))
|
| 622 |
+
|
| 623 |
+
def fetch_tag(self):
|
| 624 |
+
|
| 625 |
+
# TAG could start a simple key.
|
| 626 |
+
self.save_possible_simple_key()
|
| 627 |
+
|
| 628 |
+
# No simple keys after TAG.
|
| 629 |
+
self.allow_simple_key = False
|
| 630 |
+
|
| 631 |
+
# Scan and add TAG.
|
| 632 |
+
self.tokens.append(self.scan_tag())
|
| 633 |
+
|
| 634 |
+
def fetch_literal(self):
|
| 635 |
+
self.fetch_block_scalar(style='|')
|
| 636 |
+
|
| 637 |
+
def fetch_folded(self):
|
| 638 |
+
self.fetch_block_scalar(style='>')
|
| 639 |
+
|
| 640 |
+
def fetch_block_scalar(self, style):
|
| 641 |
+
|
| 642 |
+
# A simple key may follow a block scalar.
|
| 643 |
+
self.allow_simple_key = True
|
| 644 |
+
|
| 645 |
+
# Reset possible simple key on the current level.
|
| 646 |
+
self.remove_possible_simple_key()
|
| 647 |
+
|
| 648 |
+
# Scan and add SCALAR.
|
| 649 |
+
self.tokens.append(self.scan_block_scalar(style))
|
| 650 |
+
|
| 651 |
+
def fetch_single(self):
|
| 652 |
+
self.fetch_flow_scalar(style='\'')
|
| 653 |
+
|
| 654 |
+
def fetch_double(self):
|
| 655 |
+
self.fetch_flow_scalar(style='"')
|
| 656 |
+
|
| 657 |
+
def fetch_flow_scalar(self, style):
|
| 658 |
+
|
| 659 |
+
# A flow scalar could be a simple key.
|
| 660 |
+
self.save_possible_simple_key()
|
| 661 |
+
|
| 662 |
+
# No simple keys after flow scalars.
|
| 663 |
+
self.allow_simple_key = False
|
| 664 |
+
|
| 665 |
+
# Scan and add SCALAR.
|
| 666 |
+
self.tokens.append(self.scan_flow_scalar(style))
|
| 667 |
+
|
| 668 |
+
def fetch_plain(self):
|
| 669 |
+
|
| 670 |
+
# A plain scalar could be a simple key.
|
| 671 |
+
self.save_possible_simple_key()
|
| 672 |
+
|
| 673 |
+
# No simple keys after plain scalars. But note that `scan_plain` will
|
| 674 |
+
# change this flag if the scan is finished at the beginning of the
|
| 675 |
+
# line.
|
| 676 |
+
self.allow_simple_key = False
|
| 677 |
+
|
| 678 |
+
# Scan and add SCALAR. May change `allow_simple_key`.
|
| 679 |
+
self.tokens.append(self.scan_plain())
|
| 680 |
+
|
| 681 |
+
# Checkers.
|
| 682 |
+
|
| 683 |
+
def check_directive(self):
|
| 684 |
+
|
| 685 |
+
# DIRECTIVE: ^ '%' ...
|
| 686 |
+
# The '%' indicator is already checked.
|
| 687 |
+
if self.column == 0:
|
| 688 |
+
return True
|
| 689 |
+
|
| 690 |
+
def check_document_start(self):
|
| 691 |
+
|
| 692 |
+
# DOCUMENT-START: ^ '---' (' '|'\n')
|
| 693 |
+
if self.column == 0:
|
| 694 |
+
if self.prefix(3) == '---' \
|
| 695 |
+
and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
|
| 696 |
+
return True
|
| 697 |
+
|
| 698 |
+
def check_document_end(self):
|
| 699 |
+
|
| 700 |
+
# DOCUMENT-END: ^ '...' (' '|'\n')
|
| 701 |
+
if self.column == 0:
|
| 702 |
+
if self.prefix(3) == '...' \
|
| 703 |
+
and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
|
| 704 |
+
return True
|
| 705 |
+
|
| 706 |
+
def check_block_entry(self):
|
| 707 |
+
|
| 708 |
+
# BLOCK-ENTRY: '-' (' '|'\n')
|
| 709 |
+
return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029'
|
| 710 |
+
|
| 711 |
+
def check_key(self):
|
| 712 |
+
|
| 713 |
+
# KEY(flow context): '?'
|
| 714 |
+
if self.flow_level:
|
| 715 |
+
return True
|
| 716 |
+
|
| 717 |
+
# KEY(block context): '?' (' '|'\n')
|
| 718 |
+
else:
|
| 719 |
+
return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029'
|
| 720 |
+
|
| 721 |
+
def check_value(self):
|
| 722 |
+
|
| 723 |
+
# VALUE(flow context): ':'
|
| 724 |
+
if self.flow_level:
|
| 725 |
+
return True
|
| 726 |
+
|
| 727 |
+
# VALUE(block context): ':' (' '|'\n')
|
| 728 |
+
else:
|
| 729 |
+
return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029'
|
| 730 |
+
|
| 731 |
+
def check_plain(self):
|
| 732 |
+
|
| 733 |
+
# A plain scalar may start with any non-space character except:
|
| 734 |
+
# '-', '?', ':', ',', '[', ']', '{', '}',
|
| 735 |
+
# '#', '&', '*', '!', '|', '>', '\'', '\"',
|
| 736 |
+
# '%', '@', '`'.
|
| 737 |
+
#
|
| 738 |
+
# It may also start with
|
| 739 |
+
# '-', '?', ':'
|
| 740 |
+
# if it is followed by a non-space character.
|
| 741 |
+
#
|
| 742 |
+
# Note that we limit the last rule to the block context (except the
|
| 743 |
+
# '-' character) because we want the flow context to be space
|
| 744 |
+
# independent.
|
| 745 |
+
ch = self.peek()
|
| 746 |
+
return ch not in '\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \
|
| 747 |
+
or (self.peek(1) not in '\0 \t\r\n\x85\u2028\u2029'
|
| 748 |
+
and (ch == '-' or (not self.flow_level and ch in '?:')))
|
| 749 |
+
|
| 750 |
+
# Scanners.
|
| 751 |
+
|
| 752 |
+
def scan_to_next_token(self):
|
| 753 |
+
# We ignore spaces, line breaks and comments.
|
| 754 |
+
# If we find a line break in the block context, we set the flag
|
| 755 |
+
# `allow_simple_key` on.
|
| 756 |
+
# The byte order mark is stripped if it's the first character in the
|
| 757 |
+
# stream. We do not yet support BOM inside the stream as the
|
| 758 |
+
# specification requires. Any such mark will be considered as a part
|
| 759 |
+
# of the document.
|
| 760 |
+
#
|
| 761 |
+
# TODO: We need to make tab handling rules more sane. A good rule is
|
| 762 |
+
# Tabs cannot precede tokens
|
| 763 |
+
# BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END,
|
| 764 |
+
# KEY(block), VALUE(block), BLOCK-ENTRY
|
| 765 |
+
# So the checking code is
|
| 766 |
+
# if <TAB>:
|
| 767 |
+
# self.allow_simple_keys = False
|
| 768 |
+
# We also need to add the check for `allow_simple_keys == True` to
|
| 769 |
+
# `unwind_indent` before issuing BLOCK-END.
|
| 770 |
+
# Scanners for block, flow, and plain scalars need to be modified.
|
| 771 |
+
|
| 772 |
+
if self.index == 0 and self.peek() == '\uFEFF':
|
| 773 |
+
self.forward()
|
| 774 |
+
found = False
|
| 775 |
+
while not found:
|
| 776 |
+
while self.peek() == ' ':
|
| 777 |
+
self.forward()
|
| 778 |
+
if self.peek() == '#':
|
| 779 |
+
while self.peek() not in '\0\r\n\x85\u2028\u2029':
|
| 780 |
+
self.forward()
|
| 781 |
+
if self.scan_line_break():
|
| 782 |
+
if not self.flow_level:
|
| 783 |
+
self.allow_simple_key = True
|
| 784 |
+
else:
|
| 785 |
+
found = True
|
| 786 |
+
|
| 787 |
+
def scan_directive(self):
|
| 788 |
+
# See the specification for details.
|
| 789 |
+
start_mark = self.get_mark()
|
| 790 |
+
self.forward()
|
| 791 |
+
name = self.scan_directive_name(start_mark)
|
| 792 |
+
value = None
|
| 793 |
+
if name == 'YAML':
|
| 794 |
+
value = self.scan_yaml_directive_value(start_mark)
|
| 795 |
+
end_mark = self.get_mark()
|
| 796 |
+
elif name == 'TAG':
|
| 797 |
+
value = self.scan_tag_directive_value(start_mark)
|
| 798 |
+
end_mark = self.get_mark()
|
| 799 |
+
else:
|
| 800 |
+
end_mark = self.get_mark()
|
| 801 |
+
while self.peek() not in '\0\r\n\x85\u2028\u2029':
|
| 802 |
+
self.forward()
|
| 803 |
+
self.scan_directive_ignored_line(start_mark)
|
| 804 |
+
return DirectiveToken(name, value, start_mark, end_mark)
|
| 805 |
+
|
| 806 |
+
def scan_directive_name(self, start_mark):
|
| 807 |
+
# See the specification for details.
|
| 808 |
+
length = 0
|
| 809 |
+
ch = self.peek(length)
|
| 810 |
+
while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
|
| 811 |
+
or ch in '-_':
|
| 812 |
+
length += 1
|
| 813 |
+
ch = self.peek(length)
|
| 814 |
+
if not length:
|
| 815 |
+
raise ScannerError("while scanning a directive", start_mark,
|
| 816 |
+
"expected alphabetic or numeric character, but found %r"
|
| 817 |
+
% ch, self.get_mark())
|
| 818 |
+
value = self.prefix(length)
|
| 819 |
+
self.forward(length)
|
| 820 |
+
ch = self.peek()
|
| 821 |
+
if ch not in '\0 \r\n\x85\u2028\u2029':
|
| 822 |
+
raise ScannerError("while scanning a directive", start_mark,
|
| 823 |
+
"expected alphabetic or numeric character, but found %r"
|
| 824 |
+
% ch, self.get_mark())
|
| 825 |
+
return value
|
| 826 |
+
|
| 827 |
+
def scan_yaml_directive_value(self, start_mark):
|
| 828 |
+
# See the specification for details.
|
| 829 |
+
while self.peek() == ' ':
|
| 830 |
+
self.forward()
|
| 831 |
+
major = self.scan_yaml_directive_number(start_mark)
|
| 832 |
+
if self.peek() != '.':
|
| 833 |
+
raise ScannerError("while scanning a directive", start_mark,
|
| 834 |
+
"expected a digit or '.', but found %r" % self.peek(),
|
| 835 |
+
self.get_mark())
|
| 836 |
+
self.forward()
|
| 837 |
+
minor = self.scan_yaml_directive_number(start_mark)
|
| 838 |
+
if self.peek() not in '\0 \r\n\x85\u2028\u2029':
|
| 839 |
+
raise ScannerError("while scanning a directive", start_mark,
|
| 840 |
+
"expected a digit or ' ', but found %r" % self.peek(),
|
| 841 |
+
self.get_mark())
|
| 842 |
+
return (major, minor)
|
| 843 |
+
|
| 844 |
+
def scan_yaml_directive_number(self, start_mark):
|
| 845 |
+
# See the specification for details.
|
| 846 |
+
ch = self.peek()
|
| 847 |
+
if not ('0' <= ch <= '9'):
|
| 848 |
+
raise ScannerError("while scanning a directive", start_mark,
|
| 849 |
+
"expected a digit, but found %r" % ch, self.get_mark())
|
| 850 |
+
length = 0
|
| 851 |
+
while '0' <= self.peek(length) <= '9':
|
| 852 |
+
length += 1
|
| 853 |
+
value = int(self.prefix(length))
|
| 854 |
+
self.forward(length)
|
| 855 |
+
return value
|
| 856 |
+
|
| 857 |
+
def scan_tag_directive_value(self, start_mark):
|
| 858 |
+
# See the specification for details.
|
| 859 |
+
while self.peek() == ' ':
|
| 860 |
+
self.forward()
|
| 861 |
+
handle = self.scan_tag_directive_handle(start_mark)
|
| 862 |
+
while self.peek() == ' ':
|
| 863 |
+
self.forward()
|
| 864 |
+
prefix = self.scan_tag_directive_prefix(start_mark)
|
| 865 |
+
return (handle, prefix)
|
| 866 |
+
|
| 867 |
+
def scan_tag_directive_handle(self, start_mark):
|
| 868 |
+
# See the specification for details.
|
| 869 |
+
value = self.scan_tag_handle('directive', start_mark)
|
| 870 |
+
ch = self.peek()
|
| 871 |
+
if ch != ' ':
|
| 872 |
+
raise ScannerError("while scanning a directive", start_mark,
|
| 873 |
+
"expected ' ', but found %r" % ch, self.get_mark())
|
| 874 |
+
return value
|
| 875 |
+
|
| 876 |
+
def scan_tag_directive_prefix(self, start_mark):
|
| 877 |
+
# See the specification for details.
|
| 878 |
+
value = self.scan_tag_uri('directive', start_mark)
|
| 879 |
+
ch = self.peek()
|
| 880 |
+
if ch not in '\0 \r\n\x85\u2028\u2029':
|
| 881 |
+
raise ScannerError("while scanning a directive", start_mark,
|
| 882 |
+
"expected ' ', but found %r" % ch, self.get_mark())
|
| 883 |
+
return value
|
| 884 |
+
|
| 885 |
+
def scan_directive_ignored_line(self, start_mark):
|
| 886 |
+
# See the specification for details.
|
| 887 |
+
while self.peek() == ' ':
|
| 888 |
+
self.forward()
|
| 889 |
+
if self.peek() == '#':
|
| 890 |
+
while self.peek() not in '\0\r\n\x85\u2028\u2029':
|
| 891 |
+
self.forward()
|
| 892 |
+
ch = self.peek()
|
| 893 |
+
if ch not in '\0\r\n\x85\u2028\u2029':
|
| 894 |
+
raise ScannerError("while scanning a directive", start_mark,
|
| 895 |
+
"expected a comment or a line break, but found %r"
|
| 896 |
+
% ch, self.get_mark())
|
| 897 |
+
self.scan_line_break()
|
| 898 |
+
|
| 899 |
+
def scan_anchor(self, TokenClass):
|
| 900 |
+
# The specification does not restrict characters for anchors and
|
| 901 |
+
# aliases. This may lead to problems, for instance, the document:
|
| 902 |
+
# [ *alias, value ]
|
| 903 |
+
# can be interpreted in two ways, as
|
| 904 |
+
# [ "value" ]
|
| 905 |
+
# and
|
| 906 |
+
# [ *alias , "value" ]
|
| 907 |
+
# Therefore we restrict aliases to numbers and ASCII letters.
|
| 908 |
+
start_mark = self.get_mark()
|
| 909 |
+
indicator = self.peek()
|
| 910 |
+
if indicator == '*':
|
| 911 |
+
name = 'alias'
|
| 912 |
+
else:
|
| 913 |
+
name = 'anchor'
|
| 914 |
+
self.forward()
|
| 915 |
+
length = 0
|
| 916 |
+
ch = self.peek(length)
|
| 917 |
+
while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
|
| 918 |
+
or ch in '-_':
|
| 919 |
+
length += 1
|
| 920 |
+
ch = self.peek(length)
|
| 921 |
+
if not length:
|
| 922 |
+
raise ScannerError("while scanning an %s" % name, start_mark,
|
| 923 |
+
"expected alphabetic or numeric character, but found %r"
|
| 924 |
+
% ch, self.get_mark())
|
| 925 |
+
value = self.prefix(length)
|
| 926 |
+
self.forward(length)
|
| 927 |
+
ch = self.peek()
|
| 928 |
+
if ch not in '\0 \t\r\n\x85\u2028\u2029?:,]}%@`':
|
| 929 |
+
raise ScannerError("while scanning an %s" % name, start_mark,
|
| 930 |
+
"expected alphabetic or numeric character, but found %r"
|
| 931 |
+
% ch, self.get_mark())
|
| 932 |
+
end_mark = self.get_mark()
|
| 933 |
+
return TokenClass(value, start_mark, end_mark)
|
| 934 |
+
|
| 935 |
+
def scan_tag(self):
|
| 936 |
+
# See the specification for details.
|
| 937 |
+
start_mark = self.get_mark()
|
| 938 |
+
ch = self.peek(1)
|
| 939 |
+
if ch == '<':
|
| 940 |
+
handle = None
|
| 941 |
+
self.forward(2)
|
| 942 |
+
suffix = self.scan_tag_uri('tag', start_mark)
|
| 943 |
+
if self.peek() != '>':
|
| 944 |
+
raise ScannerError("while parsing a tag", start_mark,
|
| 945 |
+
"expected '>', but found %r" % self.peek(),
|
| 946 |
+
self.get_mark())
|
| 947 |
+
self.forward()
|
| 948 |
+
elif ch in '\0 \t\r\n\x85\u2028\u2029':
|
| 949 |
+
handle = None
|
| 950 |
+
suffix = '!'
|
| 951 |
+
self.forward()
|
| 952 |
+
else:
|
| 953 |
+
length = 1
|
| 954 |
+
use_handle = False
|
| 955 |
+
while ch not in '\0 \r\n\x85\u2028\u2029':
|
| 956 |
+
if ch == '!':
|
| 957 |
+
use_handle = True
|
| 958 |
+
break
|
| 959 |
+
length += 1
|
| 960 |
+
ch = self.peek(length)
|
| 961 |
+
handle = '!'
|
| 962 |
+
if use_handle:
|
| 963 |
+
handle = self.scan_tag_handle('tag', start_mark)
|
| 964 |
+
else:
|
| 965 |
+
handle = '!'
|
| 966 |
+
self.forward()
|
| 967 |
+
suffix = self.scan_tag_uri('tag', start_mark)
|
| 968 |
+
ch = self.peek()
|
| 969 |
+
if ch not in '\0 \r\n\x85\u2028\u2029':
|
| 970 |
+
raise ScannerError("while scanning a tag", start_mark,
|
| 971 |
+
"expected ' ', but found %r" % ch, self.get_mark())
|
| 972 |
+
value = (handle, suffix)
|
| 973 |
+
end_mark = self.get_mark()
|
| 974 |
+
return TagToken(value, start_mark, end_mark)
|
| 975 |
+
|
| 976 |
+
def scan_block_scalar(self, style):
|
| 977 |
+
# See the specification for details.
|
| 978 |
+
|
| 979 |
+
if style == '>':
|
| 980 |
+
folded = True
|
| 981 |
+
else:
|
| 982 |
+
folded = False
|
| 983 |
+
|
| 984 |
+
chunks = []
|
| 985 |
+
start_mark = self.get_mark()
|
| 986 |
+
|
| 987 |
+
# Scan the header.
|
| 988 |
+
self.forward()
|
| 989 |
+
chomping, increment = self.scan_block_scalar_indicators(start_mark)
|
| 990 |
+
self.scan_block_scalar_ignored_line(start_mark)
|
| 991 |
+
|
| 992 |
+
# Determine the indentation level and go to the first non-empty line.
|
| 993 |
+
min_indent = self.indent+1
|
| 994 |
+
if min_indent < 1:
|
| 995 |
+
min_indent = 1
|
| 996 |
+
if increment is None:
|
| 997 |
+
breaks, max_indent, end_mark = self.scan_block_scalar_indentation()
|
| 998 |
+
indent = max(min_indent, max_indent)
|
| 999 |
+
else:
|
| 1000 |
+
indent = min_indent+increment-1
|
| 1001 |
+
breaks, end_mark = self.scan_block_scalar_breaks(indent)
|
| 1002 |
+
line_break = ''
|
| 1003 |
+
|
| 1004 |
+
# Scan the inner part of the block scalar.
|
| 1005 |
+
while self.column == indent and self.peek() != '\0':
|
| 1006 |
+
chunks.extend(breaks)
|
| 1007 |
+
leading_non_space = self.peek() not in ' \t'
|
| 1008 |
+
length = 0
|
| 1009 |
+
while self.peek(length) not in '\0\r\n\x85\u2028\u2029':
|
| 1010 |
+
length += 1
|
| 1011 |
+
chunks.append(self.prefix(length))
|
| 1012 |
+
self.forward(length)
|
| 1013 |
+
line_break = self.scan_line_break()
|
| 1014 |
+
breaks, end_mark = self.scan_block_scalar_breaks(indent)
|
| 1015 |
+
if self.column == indent and self.peek() != '\0':
|
| 1016 |
+
|
| 1017 |
+
# Unfortunately, folding rules are ambiguous.
|
| 1018 |
+
#
|
| 1019 |
+
# This is the folding according to the specification:
|
| 1020 |
+
|
| 1021 |
+
if folded and line_break == '\n' \
|
| 1022 |
+
and leading_non_space and self.peek() not in ' \t':
|
| 1023 |
+
if not breaks:
|
| 1024 |
+
chunks.append(' ')
|
| 1025 |
+
else:
|
| 1026 |
+
chunks.append(line_break)
|
| 1027 |
+
|
| 1028 |
+
# This is Clark Evans's interpretation (also in the spec
|
| 1029 |
+
# examples):
|
| 1030 |
+
#
|
| 1031 |
+
#if folded and line_break == '\n':
|
| 1032 |
+
# if not breaks:
|
| 1033 |
+
# if self.peek() not in ' \t':
|
| 1034 |
+
# chunks.append(' ')
|
| 1035 |
+
# else:
|
| 1036 |
+
# chunks.append(line_break)
|
| 1037 |
+
#else:
|
| 1038 |
+
# chunks.append(line_break)
|
| 1039 |
+
else:
|
| 1040 |
+
break
|
| 1041 |
+
|
| 1042 |
+
# Chomp the tail.
|
| 1043 |
+
if chomping is not False:
|
| 1044 |
+
chunks.append(line_break)
|
| 1045 |
+
if chomping is True:
|
| 1046 |
+
chunks.extend(breaks)
|
| 1047 |
+
|
| 1048 |
+
# We are done.
|
| 1049 |
+
return ScalarToken(''.join(chunks), False, start_mark, end_mark,
|
| 1050 |
+
style)
|
| 1051 |
+
|
| 1052 |
+
def scan_block_scalar_indicators(self, start_mark):
|
| 1053 |
+
# See the specification for details.
|
| 1054 |
+
chomping = None
|
| 1055 |
+
increment = None
|
| 1056 |
+
ch = self.peek()
|
| 1057 |
+
if ch in '+-':
|
| 1058 |
+
if ch == '+':
|
| 1059 |
+
chomping = True
|
| 1060 |
+
else:
|
| 1061 |
+
chomping = False
|
| 1062 |
+
self.forward()
|
| 1063 |
+
ch = self.peek()
|
| 1064 |
+
if ch in '0123456789':
|
| 1065 |
+
increment = int(ch)
|
| 1066 |
+
if increment == 0:
|
| 1067 |
+
raise ScannerError("while scanning a block scalar", start_mark,
|
| 1068 |
+
"expected indentation indicator in the range 1-9, but found 0",
|
| 1069 |
+
self.get_mark())
|
| 1070 |
+
self.forward()
|
| 1071 |
+
elif ch in '0123456789':
|
| 1072 |
+
increment = int(ch)
|
| 1073 |
+
if increment == 0:
|
| 1074 |
+
raise ScannerError("while scanning a block scalar", start_mark,
|
| 1075 |
+
"expected indentation indicator in the range 1-9, but found 0",
|
| 1076 |
+
self.get_mark())
|
| 1077 |
+
self.forward()
|
| 1078 |
+
ch = self.peek()
|
| 1079 |
+
if ch in '+-':
|
| 1080 |
+
if ch == '+':
|
| 1081 |
+
chomping = True
|
| 1082 |
+
else:
|
| 1083 |
+
chomping = False
|
| 1084 |
+
self.forward()
|
| 1085 |
+
ch = self.peek()
|
| 1086 |
+
if ch not in '\0 \r\n\x85\u2028\u2029':
|
| 1087 |
+
raise ScannerError("while scanning a block scalar", start_mark,
|
| 1088 |
+
"expected chomping or indentation indicators, but found %r"
|
| 1089 |
+
% ch, self.get_mark())
|
| 1090 |
+
return chomping, increment
|
| 1091 |
+
|
| 1092 |
+
def scan_block_scalar_ignored_line(self, start_mark):
|
| 1093 |
+
# See the specification for details.
|
| 1094 |
+
while self.peek() == ' ':
|
| 1095 |
+
self.forward()
|
| 1096 |
+
if self.peek() == '#':
|
| 1097 |
+
while self.peek() not in '\0\r\n\x85\u2028\u2029':
|
| 1098 |
+
self.forward()
|
| 1099 |
+
ch = self.peek()
|
| 1100 |
+
if ch not in '\0\r\n\x85\u2028\u2029':
|
| 1101 |
+
raise ScannerError("while scanning a block scalar", start_mark,
|
| 1102 |
+
"expected a comment or a line break, but found %r" % ch,
|
| 1103 |
+
self.get_mark())
|
| 1104 |
+
self.scan_line_break()
|
| 1105 |
+
|
| 1106 |
+
def scan_block_scalar_indentation(self):
|
| 1107 |
+
# See the specification for details.
|
| 1108 |
+
chunks = []
|
| 1109 |
+
max_indent = 0
|
| 1110 |
+
end_mark = self.get_mark()
|
| 1111 |
+
while self.peek() in ' \r\n\x85\u2028\u2029':
|
| 1112 |
+
if self.peek() != ' ':
|
| 1113 |
+
chunks.append(self.scan_line_break())
|
| 1114 |
+
end_mark = self.get_mark()
|
| 1115 |
+
else:
|
| 1116 |
+
self.forward()
|
| 1117 |
+
if self.column > max_indent:
|
| 1118 |
+
max_indent = self.column
|
| 1119 |
+
return chunks, max_indent, end_mark
|
| 1120 |
+
|
| 1121 |
+
def scan_block_scalar_breaks(self, indent):
|
| 1122 |
+
# See the specification for details.
|
| 1123 |
+
chunks = []
|
| 1124 |
+
end_mark = self.get_mark()
|
| 1125 |
+
while self.column < indent and self.peek() == ' ':
|
| 1126 |
+
self.forward()
|
| 1127 |
+
while self.peek() in '\r\n\x85\u2028\u2029':
|
| 1128 |
+
chunks.append(self.scan_line_break())
|
| 1129 |
+
end_mark = self.get_mark()
|
| 1130 |
+
while self.column < indent and self.peek() == ' ':
|
| 1131 |
+
self.forward()
|
| 1132 |
+
return chunks, end_mark
|
| 1133 |
+
|
| 1134 |
+
def scan_flow_scalar(self, style):
|
| 1135 |
+
# See the specification for details.
|
| 1136 |
+
# Note that we loose indentation rules for quoted scalars. Quoted
|
| 1137 |
+
# scalars don't need to adhere indentation because " and ' clearly
|
| 1138 |
+
# mark the beginning and the end of them. Therefore we are less
|
| 1139 |
+
# restrictive then the specification requires. We only need to check
|
| 1140 |
+
# that document separators are not included in scalars.
|
| 1141 |
+
if style == '"':
|
| 1142 |
+
double = True
|
| 1143 |
+
else:
|
| 1144 |
+
double = False
|
| 1145 |
+
chunks = []
|
| 1146 |
+
start_mark = self.get_mark()
|
| 1147 |
+
quote = self.peek()
|
| 1148 |
+
self.forward()
|
| 1149 |
+
chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
|
| 1150 |
+
while self.peek() != quote:
|
| 1151 |
+
chunks.extend(self.scan_flow_scalar_spaces(double, start_mark))
|
| 1152 |
+
chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
|
| 1153 |
+
self.forward()
|
| 1154 |
+
end_mark = self.get_mark()
|
| 1155 |
+
return ScalarToken(''.join(chunks), False, start_mark, end_mark,
|
| 1156 |
+
style)
|
| 1157 |
+
|
| 1158 |
+
ESCAPE_REPLACEMENTS = {
|
| 1159 |
+
'0': '\0',
|
| 1160 |
+
'a': '\x07',
|
| 1161 |
+
'b': '\x08',
|
| 1162 |
+
't': '\x09',
|
| 1163 |
+
'\t': '\x09',
|
| 1164 |
+
'n': '\x0A',
|
| 1165 |
+
'v': '\x0B',
|
| 1166 |
+
'f': '\x0C',
|
| 1167 |
+
'r': '\x0D',
|
| 1168 |
+
'e': '\x1B',
|
| 1169 |
+
' ': '\x20',
|
| 1170 |
+
'\"': '\"',
|
| 1171 |
+
'\\': '\\',
|
| 1172 |
+
'/': '/',
|
| 1173 |
+
'N': '\x85',
|
| 1174 |
+
'_': '\xA0',
|
| 1175 |
+
'L': '\u2028',
|
| 1176 |
+
'P': '\u2029',
|
| 1177 |
+
}
|
| 1178 |
+
|
| 1179 |
+
ESCAPE_CODES = {
|
| 1180 |
+
'x': 2,
|
| 1181 |
+
'u': 4,
|
| 1182 |
+
'U': 8,
|
| 1183 |
+
}
|
| 1184 |
+
|
| 1185 |
+
def scan_flow_scalar_non_spaces(self, double, start_mark):
|
| 1186 |
+
# See the specification for details.
|
| 1187 |
+
chunks = []
|
| 1188 |
+
while True:
|
| 1189 |
+
length = 0
|
| 1190 |
+
while self.peek(length) not in '\'\"\\\0 \t\r\n\x85\u2028\u2029':
|
| 1191 |
+
length += 1
|
| 1192 |
+
if length:
|
| 1193 |
+
chunks.append(self.prefix(length))
|
| 1194 |
+
self.forward(length)
|
| 1195 |
+
ch = self.peek()
|
| 1196 |
+
if not double and ch == '\'' and self.peek(1) == '\'':
|
| 1197 |
+
chunks.append('\'')
|
| 1198 |
+
self.forward(2)
|
| 1199 |
+
elif (double and ch == '\'') or (not double and ch in '\"\\'):
|
| 1200 |
+
chunks.append(ch)
|
| 1201 |
+
self.forward()
|
| 1202 |
+
elif double and ch == '\\':
|
| 1203 |
+
self.forward()
|
| 1204 |
+
ch = self.peek()
|
| 1205 |
+
if ch in self.ESCAPE_REPLACEMENTS:
|
| 1206 |
+
chunks.append(self.ESCAPE_REPLACEMENTS[ch])
|
| 1207 |
+
self.forward()
|
| 1208 |
+
elif ch in self.ESCAPE_CODES:
|
| 1209 |
+
length = self.ESCAPE_CODES[ch]
|
| 1210 |
+
self.forward()
|
| 1211 |
+
for k in range(length):
|
| 1212 |
+
if self.peek(k) not in '0123456789ABCDEFabcdef':
|
| 1213 |
+
raise ScannerError("while scanning a double-quoted scalar", start_mark,
|
| 1214 |
+
"expected escape sequence of %d hexadecimal numbers, but found %r" %
|
| 1215 |
+
(length, self.peek(k)), self.get_mark())
|
| 1216 |
+
code = int(self.prefix(length), 16)
|
| 1217 |
+
chunks.append(chr(code))
|
| 1218 |
+
self.forward(length)
|
| 1219 |
+
elif ch in '\r\n\x85\u2028\u2029':
|
| 1220 |
+
self.scan_line_break()
|
| 1221 |
+
chunks.extend(self.scan_flow_scalar_breaks(double, start_mark))
|
| 1222 |
+
else:
|
| 1223 |
+
raise ScannerError("while scanning a double-quoted scalar", start_mark,
|
| 1224 |
+
"found unknown escape character %r" % ch, self.get_mark())
|
| 1225 |
+
else:
|
| 1226 |
+
return chunks
|
| 1227 |
+
|
| 1228 |
+
def scan_flow_scalar_spaces(self, double, start_mark):
|
| 1229 |
+
# See the specification for details.
|
| 1230 |
+
chunks = []
|
| 1231 |
+
length = 0
|
| 1232 |
+
while self.peek(length) in ' \t':
|
| 1233 |
+
length += 1
|
| 1234 |
+
whitespaces = self.prefix(length)
|
| 1235 |
+
self.forward(length)
|
| 1236 |
+
ch = self.peek()
|
| 1237 |
+
if ch == '\0':
|
| 1238 |
+
raise ScannerError("while scanning a quoted scalar", start_mark,
|
| 1239 |
+
"found unexpected end of stream", self.get_mark())
|
| 1240 |
+
elif ch in '\r\n\x85\u2028\u2029':
|
| 1241 |
+
line_break = self.scan_line_break()
|
| 1242 |
+
breaks = self.scan_flow_scalar_breaks(double, start_mark)
|
| 1243 |
+
if line_break != '\n':
|
| 1244 |
+
chunks.append(line_break)
|
| 1245 |
+
elif not breaks:
|
| 1246 |
+
chunks.append(' ')
|
| 1247 |
+
chunks.extend(breaks)
|
| 1248 |
+
else:
|
| 1249 |
+
chunks.append(whitespaces)
|
| 1250 |
+
return chunks
|
| 1251 |
+
|
| 1252 |
+
def scan_flow_scalar_breaks(self, double, start_mark):
|
| 1253 |
+
# See the specification for details.
|
| 1254 |
+
chunks = []
|
| 1255 |
+
while True:
|
| 1256 |
+
# Instead of checking indentation, we check for document
|
| 1257 |
+
# separators.
|
| 1258 |
+
prefix = self.prefix(3)
|
| 1259 |
+
if (prefix == '---' or prefix == '...') \
|
| 1260 |
+
and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
|
| 1261 |
+
raise ScannerError("while scanning a quoted scalar", start_mark,
|
| 1262 |
+
"found unexpected document separator", self.get_mark())
|
| 1263 |
+
while self.peek() in ' \t':
|
| 1264 |
+
self.forward()
|
| 1265 |
+
if self.peek() in '\r\n\x85\u2028\u2029':
|
| 1266 |
+
chunks.append(self.scan_line_break())
|
| 1267 |
+
else:
|
| 1268 |
+
return chunks
|
| 1269 |
+
|
| 1270 |
+
def scan_plain(self):
|
| 1271 |
+
# See the specification for details.
|
| 1272 |
+
# We add an additional restriction for the flow context:
|
| 1273 |
+
# plain scalars in the flow context cannot contain ',' or '?'.
|
| 1274 |
+
# We also keep track of the `allow_simple_key` flag here.
|
| 1275 |
+
# Indentation rules are loosed for the flow context.
|
| 1276 |
+
chunks = []
|
| 1277 |
+
start_mark = self.get_mark()
|
| 1278 |
+
end_mark = start_mark
|
| 1279 |
+
indent = self.indent+1
|
| 1280 |
+
# We allow zero indentation for scalars, but then we need to check for
|
| 1281 |
+
# document separators at the beginning of the line.
|
| 1282 |
+
#if indent == 0:
|
| 1283 |
+
# indent = 1
|
| 1284 |
+
spaces = []
|
| 1285 |
+
while True:
|
| 1286 |
+
length = 0
|
| 1287 |
+
if self.peek() == '#':
|
| 1288 |
+
break
|
| 1289 |
+
while True:
|
| 1290 |
+
ch = self.peek(length)
|
| 1291 |
+
if ch in '\0 \t\r\n\x85\u2028\u2029' \
|
| 1292 |
+
or (ch == ':' and
|
| 1293 |
+
self.peek(length+1) in '\0 \t\r\n\x85\u2028\u2029'
|
| 1294 |
+
+ (u',[]{}' if self.flow_level else u''))\
|
| 1295 |
+
or (self.flow_level and ch in ',?[]{}'):
|
| 1296 |
+
break
|
| 1297 |
+
length += 1
|
| 1298 |
+
if length == 0:
|
| 1299 |
+
break
|
| 1300 |
+
self.allow_simple_key = False
|
| 1301 |
+
chunks.extend(spaces)
|
| 1302 |
+
chunks.append(self.prefix(length))
|
| 1303 |
+
self.forward(length)
|
| 1304 |
+
end_mark = self.get_mark()
|
| 1305 |
+
spaces = self.scan_plain_spaces(indent, start_mark)
|
| 1306 |
+
if not spaces or self.peek() == '#' \
|
| 1307 |
+
or (not self.flow_level and self.column < indent):
|
| 1308 |
+
break
|
| 1309 |
+
return ScalarToken(''.join(chunks), True, start_mark, end_mark)
|
| 1310 |
+
|
| 1311 |
+
def scan_plain_spaces(self, indent, start_mark):
|
| 1312 |
+
# See the specification for details.
|
| 1313 |
+
# The specification is really confusing about tabs in plain scalars.
|
| 1314 |
+
# We just forbid them completely. Do not use tabs in YAML!
|
| 1315 |
+
chunks = []
|
| 1316 |
+
length = 0
|
| 1317 |
+
while self.peek(length) in ' ':
|
| 1318 |
+
length += 1
|
| 1319 |
+
whitespaces = self.prefix(length)
|
| 1320 |
+
self.forward(length)
|
| 1321 |
+
ch = self.peek()
|
| 1322 |
+
if ch in '\r\n\x85\u2028\u2029':
|
| 1323 |
+
line_break = self.scan_line_break()
|
| 1324 |
+
self.allow_simple_key = True
|
| 1325 |
+
prefix = self.prefix(3)
|
| 1326 |
+
if (prefix == '---' or prefix == '...') \
|
| 1327 |
+
and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
|
| 1328 |
+
return
|
| 1329 |
+
breaks = []
|
| 1330 |
+
while self.peek() in ' \r\n\x85\u2028\u2029':
|
| 1331 |
+
if self.peek() == ' ':
|
| 1332 |
+
self.forward()
|
| 1333 |
+
else:
|
| 1334 |
+
breaks.append(self.scan_line_break())
|
| 1335 |
+
prefix = self.prefix(3)
|
| 1336 |
+
if (prefix == '---' or prefix == '...') \
|
| 1337 |
+
and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
|
| 1338 |
+
return
|
| 1339 |
+
if line_break != '\n':
|
| 1340 |
+
chunks.append(line_break)
|
| 1341 |
+
elif not breaks:
|
| 1342 |
+
chunks.append(' ')
|
| 1343 |
+
chunks.extend(breaks)
|
| 1344 |
+
elif whitespaces:
|
| 1345 |
+
chunks.append(whitespaces)
|
| 1346 |
+
return chunks
|
| 1347 |
+
|
| 1348 |
+
def scan_tag_handle(self, name, start_mark):
|
| 1349 |
+
# See the specification for details.
|
| 1350 |
+
# For some strange reasons, the specification does not allow '_' in
|
| 1351 |
+
# tag handles. I have allowed it anyway.
|
| 1352 |
+
ch = self.peek()
|
| 1353 |
+
if ch != '!':
|
| 1354 |
+
raise ScannerError("while scanning a %s" % name, start_mark,
|
| 1355 |
+
"expected '!', but found %r" % ch, self.get_mark())
|
| 1356 |
+
length = 1
|
| 1357 |
+
ch = self.peek(length)
|
| 1358 |
+
if ch != ' ':
|
| 1359 |
+
while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
|
| 1360 |
+
or ch in '-_':
|
| 1361 |
+
length += 1
|
| 1362 |
+
ch = self.peek(length)
|
| 1363 |
+
if ch != '!':
|
| 1364 |
+
self.forward(length)
|
| 1365 |
+
raise ScannerError("while scanning a %s" % name, start_mark,
|
| 1366 |
+
"expected '!', but found %r" % ch, self.get_mark())
|
| 1367 |
+
length += 1
|
| 1368 |
+
value = self.prefix(length)
|
| 1369 |
+
self.forward(length)
|
| 1370 |
+
return value
|
| 1371 |
+
|
| 1372 |
+
def scan_tag_uri(self, name, start_mark):
|
| 1373 |
+
# See the specification for details.
|
| 1374 |
+
# Note: we do not check if URI is well-formed.
|
| 1375 |
+
chunks = []
|
| 1376 |
+
length = 0
|
| 1377 |
+
ch = self.peek(length)
|
| 1378 |
+
while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
|
| 1379 |
+
or ch in '-;/?:@&=+$,_.!~*\'()[]%':
|
| 1380 |
+
if ch == '%':
|
| 1381 |
+
chunks.append(self.prefix(length))
|
| 1382 |
+
self.forward(length)
|
| 1383 |
+
length = 0
|
| 1384 |
+
chunks.append(self.scan_uri_escapes(name, start_mark))
|
| 1385 |
+
else:
|
| 1386 |
+
length += 1
|
| 1387 |
+
ch = self.peek(length)
|
| 1388 |
+
if length:
|
| 1389 |
+
chunks.append(self.prefix(length))
|
| 1390 |
+
self.forward(length)
|
| 1391 |
+
length = 0
|
| 1392 |
+
if not chunks:
|
| 1393 |
+
raise ScannerError("while parsing a %s" % name, start_mark,
|
| 1394 |
+
"expected URI, but found %r" % ch, self.get_mark())
|
| 1395 |
+
return ''.join(chunks)
|
| 1396 |
+
|
| 1397 |
+
def scan_uri_escapes(self, name, start_mark):
|
| 1398 |
+
# See the specification for details.
|
| 1399 |
+
codes = []
|
| 1400 |
+
mark = self.get_mark()
|
| 1401 |
+
while self.peek() == '%':
|
| 1402 |
+
self.forward()
|
| 1403 |
+
for k in range(2):
|
| 1404 |
+
if self.peek(k) not in '0123456789ABCDEFabcdef':
|
| 1405 |
+
raise ScannerError("while scanning a %s" % name, start_mark,
|
| 1406 |
+
"expected URI escape sequence of 2 hexadecimal numbers, but found %r"
|
| 1407 |
+
% self.peek(k), self.get_mark())
|
| 1408 |
+
codes.append(int(self.prefix(2), 16))
|
| 1409 |
+
self.forward(2)
|
| 1410 |
+
try:
|
| 1411 |
+
value = bytes(codes).decode('utf-8')
|
| 1412 |
+
except UnicodeDecodeError as exc:
|
| 1413 |
+
raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark)
|
| 1414 |
+
return value
|
| 1415 |
+
|
| 1416 |
+
def scan_line_break(self):
|
| 1417 |
+
# Transforms:
|
| 1418 |
+
# '\r\n' : '\n'
|
| 1419 |
+
# '\r' : '\n'
|
| 1420 |
+
# '\n' : '\n'
|
| 1421 |
+
# '\x85' : '\n'
|
| 1422 |
+
# '\u2028' : '\u2028'
|
| 1423 |
+
# '\u2029 : '\u2029'
|
| 1424 |
+
# default : ''
|
| 1425 |
+
ch = self.peek()
|
| 1426 |
+
if ch in '\r\n\x85':
|
| 1427 |
+
if self.prefix(2) == '\r\n':
|
| 1428 |
+
self.forward(2)
|
| 1429 |
+
else:
|
| 1430 |
+
self.forward()
|
| 1431 |
+
return '\n'
|
| 1432 |
+
elif ch in '\u2028\u2029':
|
| 1433 |
+
self.forward()
|
| 1434 |
+
return ch
|
| 1435 |
+
return ''
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/serializer.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
__all__ = ['Serializer', 'SerializerError']
|
| 3 |
+
|
| 4 |
+
from .error import YAMLError
|
| 5 |
+
from .events import *
|
| 6 |
+
from .nodes import *
|
| 7 |
+
|
| 8 |
+
class SerializerError(YAMLError):
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
class Serializer:
|
| 12 |
+
|
| 13 |
+
ANCHOR_TEMPLATE = 'id%03d'
|
| 14 |
+
|
| 15 |
+
def __init__(self, encoding=None,
|
| 16 |
+
explicit_start=None, explicit_end=None, version=None, tags=None):
|
| 17 |
+
self.use_encoding = encoding
|
| 18 |
+
self.use_explicit_start = explicit_start
|
| 19 |
+
self.use_explicit_end = explicit_end
|
| 20 |
+
self.use_version = version
|
| 21 |
+
self.use_tags = tags
|
| 22 |
+
self.serialized_nodes = {}
|
| 23 |
+
self.anchors = {}
|
| 24 |
+
self.last_anchor_id = 0
|
| 25 |
+
self.closed = None
|
| 26 |
+
|
| 27 |
+
def open(self):
|
| 28 |
+
if self.closed is None:
|
| 29 |
+
self.emit(StreamStartEvent(encoding=self.use_encoding))
|
| 30 |
+
self.closed = False
|
| 31 |
+
elif self.closed:
|
| 32 |
+
raise SerializerError("serializer is closed")
|
| 33 |
+
else:
|
| 34 |
+
raise SerializerError("serializer is already opened")
|
| 35 |
+
|
| 36 |
+
def close(self):
|
| 37 |
+
if self.closed is None:
|
| 38 |
+
raise SerializerError("serializer is not opened")
|
| 39 |
+
elif not self.closed:
|
| 40 |
+
self.emit(StreamEndEvent())
|
| 41 |
+
self.closed = True
|
| 42 |
+
|
| 43 |
+
#def __del__(self):
|
| 44 |
+
# self.close()
|
| 45 |
+
|
| 46 |
+
def serialize(self, node):
|
| 47 |
+
if self.closed is None:
|
| 48 |
+
raise SerializerError("serializer is not opened")
|
| 49 |
+
elif self.closed:
|
| 50 |
+
raise SerializerError("serializer is closed")
|
| 51 |
+
self.emit(DocumentStartEvent(explicit=self.use_explicit_start,
|
| 52 |
+
version=self.use_version, tags=self.use_tags))
|
| 53 |
+
self.anchor_node(node)
|
| 54 |
+
self.serialize_node(node, None, None)
|
| 55 |
+
self.emit(DocumentEndEvent(explicit=self.use_explicit_end))
|
| 56 |
+
self.serialized_nodes = {}
|
| 57 |
+
self.anchors = {}
|
| 58 |
+
self.last_anchor_id = 0
|
| 59 |
+
|
| 60 |
+
def anchor_node(self, node):
|
| 61 |
+
if node in self.anchors:
|
| 62 |
+
if self.anchors[node] is None:
|
| 63 |
+
self.anchors[node] = self.generate_anchor(node)
|
| 64 |
+
else:
|
| 65 |
+
self.anchors[node] = None
|
| 66 |
+
if isinstance(node, SequenceNode):
|
| 67 |
+
for item in node.value:
|
| 68 |
+
self.anchor_node(item)
|
| 69 |
+
elif isinstance(node, MappingNode):
|
| 70 |
+
for key, value in node.value:
|
| 71 |
+
self.anchor_node(key)
|
| 72 |
+
self.anchor_node(value)
|
| 73 |
+
|
| 74 |
+
def generate_anchor(self, node):
|
| 75 |
+
self.last_anchor_id += 1
|
| 76 |
+
return self.ANCHOR_TEMPLATE % self.last_anchor_id
|
| 77 |
+
|
| 78 |
+
def serialize_node(self, node, parent, index):
|
| 79 |
+
alias = self.anchors[node]
|
| 80 |
+
if node in self.serialized_nodes:
|
| 81 |
+
self.emit(AliasEvent(alias))
|
| 82 |
+
else:
|
| 83 |
+
self.serialized_nodes[node] = True
|
| 84 |
+
self.descend_resolver(parent, index)
|
| 85 |
+
if isinstance(node, ScalarNode):
|
| 86 |
+
detected_tag = self.resolve(ScalarNode, node.value, (True, False))
|
| 87 |
+
default_tag = self.resolve(ScalarNode, node.value, (False, True))
|
| 88 |
+
implicit = (node.tag == detected_tag), (node.tag == default_tag)
|
| 89 |
+
self.emit(ScalarEvent(alias, node.tag, implicit, node.value,
|
| 90 |
+
style=node.style))
|
| 91 |
+
elif isinstance(node, SequenceNode):
|
| 92 |
+
implicit = (node.tag
|
| 93 |
+
== self.resolve(SequenceNode, node.value, True))
|
| 94 |
+
self.emit(SequenceStartEvent(alias, node.tag, implicit,
|
| 95 |
+
flow_style=node.flow_style))
|
| 96 |
+
index = 0
|
| 97 |
+
for item in node.value:
|
| 98 |
+
self.serialize_node(item, node, index)
|
| 99 |
+
index += 1
|
| 100 |
+
self.emit(SequenceEndEvent())
|
| 101 |
+
elif isinstance(node, MappingNode):
|
| 102 |
+
implicit = (node.tag
|
| 103 |
+
== self.resolve(MappingNode, node.value, True))
|
| 104 |
+
self.emit(MappingStartEvent(alias, node.tag, implicit,
|
| 105 |
+
flow_style=node.flow_style))
|
| 106 |
+
for key, value in node.value:
|
| 107 |
+
self.serialize_node(key, node, None)
|
| 108 |
+
self.serialize_node(value, node, key)
|
| 109 |
+
self.emit(MappingEndEvent())
|
| 110 |
+
self.ascend_resolver()
|
| 111 |
+
|
.cache/uv/archive-v0/1Tisl13xos2240bfZE_Z8/yaml/tokens.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
class Token(object):
|
| 3 |
+
def __init__(self, start_mark, end_mark):
|
| 4 |
+
self.start_mark = start_mark
|
| 5 |
+
self.end_mark = end_mark
|
| 6 |
+
def __repr__(self):
|
| 7 |
+
attributes = [key for key in self.__dict__
|
| 8 |
+
if not key.endswith('_mark')]
|
| 9 |
+
attributes.sort()
|
| 10 |
+
arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
|
| 11 |
+
for key in attributes])
|
| 12 |
+
return '%s(%s)' % (self.__class__.__name__, arguments)
|
| 13 |
+
|
| 14 |
+
#class BOMToken(Token):
|
| 15 |
+
# id = '<byte order mark>'
|
| 16 |
+
|
| 17 |
+
class DirectiveToken(Token):
|
| 18 |
+
id = '<directive>'
|
| 19 |
+
def __init__(self, name, value, start_mark, end_mark):
|
| 20 |
+
self.name = name
|
| 21 |
+
self.value = value
|
| 22 |
+
self.start_mark = start_mark
|
| 23 |
+
self.end_mark = end_mark
|
| 24 |
+
|
| 25 |
+
class DocumentStartToken(Token):
|
| 26 |
+
id = '<document start>'
|
| 27 |
+
|
| 28 |
+
class DocumentEndToken(Token):
|
| 29 |
+
id = '<document end>'
|
| 30 |
+
|
| 31 |
+
class StreamStartToken(Token):
|
| 32 |
+
id = '<stream start>'
|
| 33 |
+
def __init__(self, start_mark=None, end_mark=None,
|
| 34 |
+
encoding=None):
|
| 35 |
+
self.start_mark = start_mark
|
| 36 |
+
self.end_mark = end_mark
|
| 37 |
+
self.encoding = encoding
|
| 38 |
+
|
| 39 |
+
class StreamEndToken(Token):
|
| 40 |
+
id = '<stream end>'
|
| 41 |
+
|
| 42 |
+
class BlockSequenceStartToken(Token):
|
| 43 |
+
id = '<block sequence start>'
|
| 44 |
+
|
| 45 |
+
class BlockMappingStartToken(Token):
|
| 46 |
+
id = '<block mapping start>'
|
| 47 |
+
|
| 48 |
+
class BlockEndToken(Token):
|
| 49 |
+
id = '<block end>'
|
| 50 |
+
|
| 51 |
+
class FlowSequenceStartToken(Token):
|
| 52 |
+
id = '['
|
| 53 |
+
|
| 54 |
+
class FlowMappingStartToken(Token):
|
| 55 |
+
id = '{'
|
| 56 |
+
|
| 57 |
+
class FlowSequenceEndToken(Token):
|
| 58 |
+
id = ']'
|
| 59 |
+
|
| 60 |
+
class FlowMappingEndToken(Token):
|
| 61 |
+
id = '}'
|
| 62 |
+
|
| 63 |
+
class KeyToken(Token):
|
| 64 |
+
id = '?'
|
| 65 |
+
|
| 66 |
+
class ValueToken(Token):
|
| 67 |
+
id = ':'
|
| 68 |
+
|
| 69 |
+
class BlockEntryToken(Token):
|
| 70 |
+
id = '-'
|
| 71 |
+
|
| 72 |
+
class FlowEntryToken(Token):
|
| 73 |
+
id = ','
|
| 74 |
+
|
| 75 |
+
class AliasToken(Token):
|
| 76 |
+
id = '<alias>'
|
| 77 |
+
def __init__(self, value, start_mark, end_mark):
|
| 78 |
+
self.value = value
|
| 79 |
+
self.start_mark = start_mark
|
| 80 |
+
self.end_mark = end_mark
|
| 81 |
+
|
| 82 |
+
class AnchorToken(Token):
|
| 83 |
+
id = '<anchor>'
|
| 84 |
+
def __init__(self, value, start_mark, end_mark):
|
| 85 |
+
self.value = value
|
| 86 |
+
self.start_mark = start_mark
|
| 87 |
+
self.end_mark = end_mark
|
| 88 |
+
|
| 89 |
+
class TagToken(Token):
|
| 90 |
+
id = '<tag>'
|
| 91 |
+
def __init__(self, value, start_mark, end_mark):
|
| 92 |
+
self.value = value
|
| 93 |
+
self.start_mark = start_mark
|
| 94 |
+
self.end_mark = end_mark
|
| 95 |
+
|
| 96 |
+
class ScalarToken(Token):
|
| 97 |
+
id = '<scalar>'
|
| 98 |
+
def __init__(self, value, plain, start_mark, end_mark, style=None):
|
| 99 |
+
self.value = value
|
| 100 |
+
self.plain = plain
|
| 101 |
+
self.start_mark = start_mark
|
| 102 |
+
self.end_mark = end_mark
|
| 103 |
+
self.style = style
|
| 104 |
+
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore-1.0.9.dist-info/METADATA
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: httpcore
|
| 3 |
+
Version: 1.0.9
|
| 4 |
+
Summary: A minimal low-level HTTP client.
|
| 5 |
+
Project-URL: Documentation, https://www.encode.io/httpcore
|
| 6 |
+
Project-URL: Homepage, https://www.encode.io/httpcore/
|
| 7 |
+
Project-URL: Source, https://github.com/encode/httpcore
|
| 8 |
+
Author-email: Tom Christie <tom@tomchristie.com>
|
| 9 |
+
License-Expression: BSD-3-Clause
|
| 10 |
+
License-File: LICENSE.md
|
| 11 |
+
Classifier: Development Status :: 3 - Alpha
|
| 12 |
+
Classifier: Environment :: Web Environment
|
| 13 |
+
Classifier: Framework :: AsyncIO
|
| 14 |
+
Classifier: Framework :: Trio
|
| 15 |
+
Classifier: Intended Audience :: Developers
|
| 16 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 17 |
+
Classifier: Operating System :: OS Independent
|
| 18 |
+
Classifier: Programming Language :: Python :: 3
|
| 19 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 25 |
+
Classifier: Topic :: Internet :: WWW/HTTP
|
| 26 |
+
Requires-Python: >=3.8
|
| 27 |
+
Requires-Dist: certifi
|
| 28 |
+
Requires-Dist: h11>=0.16
|
| 29 |
+
Provides-Extra: asyncio
|
| 30 |
+
Requires-Dist: anyio<5.0,>=4.0; extra == 'asyncio'
|
| 31 |
+
Provides-Extra: http2
|
| 32 |
+
Requires-Dist: h2<5,>=3; extra == 'http2'
|
| 33 |
+
Provides-Extra: socks
|
| 34 |
+
Requires-Dist: socksio==1.*; extra == 'socks'
|
| 35 |
+
Provides-Extra: trio
|
| 36 |
+
Requires-Dist: trio<1.0,>=0.22.0; extra == 'trio'
|
| 37 |
+
Description-Content-Type: text/markdown
|
| 38 |
+
|
| 39 |
+
# HTTP Core
|
| 40 |
+
|
| 41 |
+
[](https://github.com/encode/httpcore/actions)
|
| 42 |
+
[](https://pypi.org/project/httpcore/)
|
| 43 |
+
|
| 44 |
+
> *Do one thing, and do it well.*
|
| 45 |
+
|
| 46 |
+
The HTTP Core package provides a minimal low-level HTTP client, which does
|
| 47 |
+
one thing only. Sending HTTP requests.
|
| 48 |
+
|
| 49 |
+
It does not provide any high level model abstractions over the API,
|
| 50 |
+
does not handle redirects, multipart uploads, building authentication headers,
|
| 51 |
+
transparent HTTP caching, URL parsing, session cookie handling,
|
| 52 |
+
content or charset decoding, handling JSON, environment based configuration
|
| 53 |
+
defaults, or any of that Jazz.
|
| 54 |
+
|
| 55 |
+
Some things HTTP Core does do:
|
| 56 |
+
|
| 57 |
+
* Sending HTTP requests.
|
| 58 |
+
* Thread-safe / task-safe connection pooling.
|
| 59 |
+
* HTTP(S) proxy & SOCKS proxy support.
|
| 60 |
+
* Supports HTTP/1.1 and HTTP/2.
|
| 61 |
+
* Provides both sync and async interfaces.
|
| 62 |
+
* Async backend support for `asyncio` and `trio`.
|
| 63 |
+
|
| 64 |
+
## Requirements
|
| 65 |
+
|
| 66 |
+
Python 3.8+
|
| 67 |
+
|
| 68 |
+
## Installation
|
| 69 |
+
|
| 70 |
+
For HTTP/1.1 only support, install with:
|
| 71 |
+
|
| 72 |
+
```shell
|
| 73 |
+
$ pip install httpcore
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
There are also a number of optional extras available...
|
| 77 |
+
|
| 78 |
+
```shell
|
| 79 |
+
$ pip install httpcore['asyncio,trio,http2,socks']
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
## Sending requests
|
| 83 |
+
|
| 84 |
+
Send an HTTP request:
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
import httpcore
|
| 88 |
+
|
| 89 |
+
response = httpcore.request("GET", "https://www.example.com/")
|
| 90 |
+
|
| 91 |
+
print(response)
|
| 92 |
+
# <Response [200]>
|
| 93 |
+
print(response.status)
|
| 94 |
+
# 200
|
| 95 |
+
print(response.headers)
|
| 96 |
+
# [(b'Accept-Ranges', b'bytes'), (b'Age', b'557328'), (b'Cache-Control', b'max-age=604800'), ...]
|
| 97 |
+
print(response.content)
|
| 98 |
+
# b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>\n\n<meta charset="utf-8"/>\n ...'
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
The top-level `httpcore.request()` function is provided for convenience. In practice whenever you're working with `httpcore` you'll want to use the connection pooling functionality that it provides.
|
| 102 |
+
|
| 103 |
+
```python
|
| 104 |
+
import httpcore
|
| 105 |
+
|
| 106 |
+
http = httpcore.ConnectionPool()
|
| 107 |
+
response = http.request("GET", "https://www.example.com/")
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
Once you're ready to get going, [head over to the documentation](https://www.encode.io/httpcore/).
|
| 111 |
+
|
| 112 |
+
## Motivation
|
| 113 |
+
|
| 114 |
+
You *probably* don't want to be using HTTP Core directly. It might make sense if
|
| 115 |
+
you're writing something like a proxy service in Python, and you just want
|
| 116 |
+
something at the lowest possible level, but more typically you'll want to use
|
| 117 |
+
a higher level client library, such as `httpx`.
|
| 118 |
+
|
| 119 |
+
The motivation for `httpcore` is:
|
| 120 |
+
|
| 121 |
+
* To provide a reusable low-level client library, that other packages can then build on top of.
|
| 122 |
+
* To provide a *really clear interface split* between the networking code and client logic,
|
| 123 |
+
so that each is easier to understand and reason about in isolation.
|
| 124 |
+
|
| 125 |
+
## Dependencies
|
| 126 |
+
|
| 127 |
+
The `httpcore` package has the following dependencies...
|
| 128 |
+
|
| 129 |
+
* `h11`
|
| 130 |
+
* `certifi`
|
| 131 |
+
|
| 132 |
+
And the following optional extras...
|
| 133 |
+
|
| 134 |
+
* `anyio` - Required by `pip install httpcore['asyncio']`.
|
| 135 |
+
* `trio` - Required by `pip install httpcore['trio']`.
|
| 136 |
+
* `h2` - Required by `pip install httpcore['http2']`.
|
| 137 |
+
* `socksio` - Required by `pip install httpcore['socks']`.
|
| 138 |
+
|
| 139 |
+
## Versioning
|
| 140 |
+
|
| 141 |
+
We use [SEMVER for our versioning policy](https://semver.org/).
|
| 142 |
+
|
| 143 |
+
For changes between package versions please see our [project changelog](CHANGELOG.md).
|
| 144 |
+
|
| 145 |
+
We recommend pinning your requirements either the most current major version, or a more specific version range:
|
| 146 |
+
|
| 147 |
+
```python
|
| 148 |
+
pip install 'httpcore==1.*'
|
| 149 |
+
```
|
| 150 |
+
# Changelog
|
| 151 |
+
|
| 152 |
+
All notable changes to this project will be documented in this file.
|
| 153 |
+
|
| 154 |
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
| 155 |
+
|
| 156 |
+
## Version 1.0.9 (April 24th, 2025)
|
| 157 |
+
|
| 158 |
+
- Resolve https://github.com/advisories/GHSA-vqfr-h8mv-ghfj with h11 dependency update. (#1008)
|
| 159 |
+
|
| 160 |
+
## Version 1.0.8 (April 11th, 2025)
|
| 161 |
+
|
| 162 |
+
- Fix `AttributeError` when importing on Python 3.14. (#1005)
|
| 163 |
+
|
| 164 |
+
## Version 1.0.7 (November 15th, 2024)
|
| 165 |
+
|
| 166 |
+
- Support `proxy=…` configuration on `ConnectionPool()`. (#974)
|
| 167 |
+
|
| 168 |
+
## Version 1.0.6 (October 1st, 2024)
|
| 169 |
+
|
| 170 |
+
- Relax `trio` dependency pinning. (#956)
|
| 171 |
+
- Handle `trio` raising `NotImplementedError` on unsupported platforms. (#955)
|
| 172 |
+
- Handle mapping `ssl.SSLError` to `httpcore.ConnectError`. (#918)
|
| 173 |
+
|
| 174 |
+
## 1.0.5 (March 27th, 2024)
|
| 175 |
+
|
| 176 |
+
- Handle `EndOfStream` exception for anyio backend. (#899)
|
| 177 |
+
- Allow trio `0.25.*` series in package dependancies. (#903)
|
| 178 |
+
|
| 179 |
+
## 1.0.4 (February 21st, 2024)
|
| 180 |
+
|
| 181 |
+
- Add `target` request extension. (#888)
|
| 182 |
+
- Fix support for connection `Upgrade` and `CONNECT` when some data in the stream has been read. (#882)
|
| 183 |
+
|
| 184 |
+
## 1.0.3 (February 13th, 2024)
|
| 185 |
+
|
| 186 |
+
- Fix support for async cancellations. (#880)
|
| 187 |
+
- Fix trace extension when used with socks proxy. (#849)
|
| 188 |
+
- Fix SSL context for connections using the "wss" scheme (#869)
|
| 189 |
+
|
| 190 |
+
## 1.0.2 (November 10th, 2023)
|
| 191 |
+
|
| 192 |
+
- Fix `float("inf")` timeouts in `Event.wait` function. (#846)
|
| 193 |
+
|
| 194 |
+
## 1.0.1 (November 3rd, 2023)
|
| 195 |
+
|
| 196 |
+
- Fix pool timeout to account for the total time spent retrying. (#823)
|
| 197 |
+
- Raise a neater RuntimeError when the correct async deps are not installed. (#826)
|
| 198 |
+
- Add support for synchronous TLS-in-TLS streams. (#840)
|
| 199 |
+
|
| 200 |
+
## 1.0.0 (October 6th, 2023)
|
| 201 |
+
|
| 202 |
+
From version 1.0 our async support is now optional, as the package has minimal dependencies by default.
|
| 203 |
+
|
| 204 |
+
For async support use either `pip install 'httpcore[asyncio]'` or `pip install 'httpcore[trio]'`.
|
| 205 |
+
|
| 206 |
+
The project versioning policy is now explicitly governed by SEMVER. See https://semver.org/.
|
| 207 |
+
|
| 208 |
+
- Async support becomes fully optional. (#809)
|
| 209 |
+
- Add support for Python 3.12. (#807)
|
| 210 |
+
|
| 211 |
+
## 0.18.0 (September 8th, 2023)
|
| 212 |
+
|
| 213 |
+
- Add support for HTTPS proxies. (#745, #786)
|
| 214 |
+
- Drop Python 3.7 support. (#727)
|
| 215 |
+
- Handle `sni_hostname` extension with SOCKS proxy. (#774)
|
| 216 |
+
- Handle HTTP/1.1 half-closed connections gracefully. (#641)
|
| 217 |
+
- Change the type of `Extensions` from `Mapping[Str, Any]` to `MutableMapping[Str, Any]`. (#762)
|
| 218 |
+
|
| 219 |
+
## 0.17.3 (July 5th, 2023)
|
| 220 |
+
|
| 221 |
+
- Support async cancellations, ensuring that the connection pool is left in a clean state when cancellations occur. (#726)
|
| 222 |
+
- The networking backend interface has [been added to the public API](https://www.encode.io/httpcore/network-backends). Some classes which were previously private implementation detail are now part of the top-level public API. (#699)
|
| 223 |
+
- Graceful handling of HTTP/2 GoAway frames, with requests being transparently retried on a new connection. (#730)
|
| 224 |
+
- Add exceptions when a synchronous `trace callback` is passed to an asynchronous request or an asynchronous `trace callback` is passed to a synchronous request. (#717)
|
| 225 |
+
- Drop Python 3.7 support. (#727)
|
| 226 |
+
|
| 227 |
+
## 0.17.2 (May 23th, 2023)
|
| 228 |
+
|
| 229 |
+
- Add `socket_options` argument to `ConnectionPool` and `HTTProxy` classes. (#668)
|
| 230 |
+
- Improve logging with per-module logger names. (#690)
|
| 231 |
+
- Add `sni_hostname` request extension. (#696)
|
| 232 |
+
- Resolve race condition during import of `anyio` package. (#692)
|
| 233 |
+
- Enable TCP_NODELAY for all synchronous sockets. (#651)
|
| 234 |
+
|
| 235 |
+
## 0.17.1 (May 17th, 2023)
|
| 236 |
+
|
| 237 |
+
- If 'retries' is set, then allow retries if an SSL handshake error occurs. (#669)
|
| 238 |
+
- Improve correctness of tracebacks on network exceptions, by raising properly chained exceptions. (#678)
|
| 239 |
+
- Prevent connection-hanging behaviour when HTTP/2 connections are closed by a server-sent 'GoAway' frame. (#679)
|
| 240 |
+
- Fix edge-case exception when removing requests from the connection pool. (#680)
|
| 241 |
+
- Fix pool timeout edge-case. (#688)
|
| 242 |
+
|
| 243 |
+
## 0.17.0 (March 16th, 2023)
|
| 244 |
+
|
| 245 |
+
- Add DEBUG level logging. (#648)
|
| 246 |
+
- Respect HTTP/2 max concurrent streams when settings updates are sent by server. (#652)
|
| 247 |
+
- Increase the allowable HTTP header size to 100kB. (#647)
|
| 248 |
+
- Add `retries` option to SOCKS proxy classes. (#643)
|
| 249 |
+
|
| 250 |
+
## 0.16.3 (December 20th, 2022)
|
| 251 |
+
|
| 252 |
+
- Allow `ws` and `wss` schemes. Allows us to properly support websocket upgrade connections. (#625)
|
| 253 |
+
- Forwarding HTTP proxies use a connection-per-remote-host. Required by some proxy implementations. (#637)
|
| 254 |
+
- Don't raise `RuntimeError` when closing a connection pool with active connections. Removes some error cases when cancellations are used. (#631)
|
| 255 |
+
- Lazy import `anyio`, so that it's no longer a hard dependancy, and isn't imported if unused. (#639)
|
| 256 |
+
|
| 257 |
+
## 0.16.2 (November 25th, 2022)
|
| 258 |
+
|
| 259 |
+
- Revert 'Fix async cancellation behaviour', which introduced race conditions. (#627)
|
| 260 |
+
- Raise `RuntimeError` if attempting to us UNIX domain sockets on Windows. (#619)
|
| 261 |
+
|
| 262 |
+
## 0.16.1 (November 17th, 2022)
|
| 263 |
+
|
| 264 |
+
- Fix HTTP/1.1 interim informational responses, such as "100 Continue". (#605)
|
| 265 |
+
|
| 266 |
+
## 0.16.0 (October 11th, 2022)
|
| 267 |
+
|
| 268 |
+
- Support HTTP/1.1 informational responses. (#581)
|
| 269 |
+
- Fix async cancellation behaviour. (#580)
|
| 270 |
+
- Support `h11` 0.14. (#579)
|
| 271 |
+
|
| 272 |
+
## 0.15.0 (May 17th, 2022)
|
| 273 |
+
|
| 274 |
+
- Drop Python 3.6 support (#535)
|
| 275 |
+
- Ensure HTTP proxy CONNECT requests include `timeout` configuration. (#506)
|
| 276 |
+
- Switch to explicit `typing.Optional` for type hints. (#513)
|
| 277 |
+
- For `trio` map OSError exceptions to `ConnectError`. (#543)
|
| 278 |
+
|
| 279 |
+
## 0.14.7 (February 4th, 2022)
|
| 280 |
+
|
| 281 |
+
- Requests which raise a PoolTimeout need to be removed from the pool queue. (#502)
|
| 282 |
+
- Fix AttributeError that happened when Socks5Connection were terminated. (#501)
|
| 283 |
+
|
| 284 |
+
## 0.14.6 (February 1st, 2022)
|
| 285 |
+
|
| 286 |
+
- Fix SOCKS support for `http://` URLs. (#492)
|
| 287 |
+
- Resolve race condition around exceptions during streaming a response. (#491)
|
| 288 |
+
|
| 289 |
+
## 0.14.5 (January 18th, 2022)
|
| 290 |
+
|
| 291 |
+
- SOCKS proxy support. (#478)
|
| 292 |
+
- Add proxy_auth argument to HTTPProxy. (#481)
|
| 293 |
+
- Improve error message on 'RemoteProtocolError' exception when server disconnects without sending a response. (#479)
|
| 294 |
+
|
| 295 |
+
## 0.14.4 (January 5th, 2022)
|
| 296 |
+
|
| 297 |
+
- Support HTTP/2 on HTTPS tunnelling proxies. (#468)
|
| 298 |
+
- Fix proxy headers missing on HTTP forwarding. (#456)
|
| 299 |
+
- Only instantiate SSL context if required. (#457)
|
| 300 |
+
- More robust HTTP/2 handling. (#253, #439, #440, #441)
|
| 301 |
+
|
| 302 |
+
## 0.14.3 (November 17th, 2021)
|
| 303 |
+
|
| 304 |
+
- Fix race condition when removing closed connections from the pool. (#437)
|
| 305 |
+
|
| 306 |
+
## 0.14.2 (November 16th, 2021)
|
| 307 |
+
|
| 308 |
+
- Failed connections no longer remain in the pool. (Pull #433)
|
| 309 |
+
|
| 310 |
+
## 0.14.1 (November 12th, 2021)
|
| 311 |
+
|
| 312 |
+
- `max_connections` becomes optional. (Pull #429)
|
| 313 |
+
- `certifi` is now included in the install dependancies. (Pull #428)
|
| 314 |
+
- `h2` is now strictly optional. (Pull #428)
|
| 315 |
+
|
| 316 |
+
## 0.14.0 (November 11th, 2021)
|
| 317 |
+
|
| 318 |
+
The 0.14 release is a complete reworking of `httpcore`, comprehensively addressing some underlying issues in the connection pooling, as well as substantially redesigning the API to be more user friendly.
|
| 319 |
+
|
| 320 |
+
Some of the lower-level API design also makes the components more easily testable in isolation, and the package now has 100% test coverage.
|
| 321 |
+
|
| 322 |
+
See [discussion #419](https://github.com/encode/httpcore/discussions/419) for a little more background.
|
| 323 |
+
|
| 324 |
+
There's some other neat bits in there too, such as the "trace" extension, which gives a hook into inspecting the internal events that occur during the request/response cycle. This extension is needed for the HTTPX cli, in order to...
|
| 325 |
+
|
| 326 |
+
* Log the point at which the connection is established, and the IP/port on which it is made.
|
| 327 |
+
* Determine if the outgoing request should log as HTTP/1.1 or HTTP/2, rather than having to assume it's HTTP/2 if the --http2 flag was passed. (Which may not actually be true.)
|
| 328 |
+
* Log SSL version info / certificate info.
|
| 329 |
+
|
| 330 |
+
Note that `curio` support is not currently available in 0.14.0. If you're using `httpcore` with `curio` please get in touch, so we can assess if we ought to prioritize it as a feature or not.
|
| 331 |
+
|
| 332 |
+
## 0.13.7 (September 13th, 2021)
|
| 333 |
+
|
| 334 |
+
- Fix broken error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #403)
|
| 335 |
+
|
| 336 |
+
## 0.13.6 (June 15th, 2021)
|
| 337 |
+
|
| 338 |
+
### Fixed
|
| 339 |
+
|
| 340 |
+
- Close sockets when read or write timeouts occur. (Pull #365)
|
| 341 |
+
|
| 342 |
+
## 0.13.5 (June 14th, 2021)
|
| 343 |
+
|
| 344 |
+
### Fixed
|
| 345 |
+
|
| 346 |
+
- Resolved niggles with AnyIO EOF behaviours. (Pull #358, #362)
|
| 347 |
+
|
| 348 |
+
## 0.13.4 (June 9th, 2021)
|
| 349 |
+
|
| 350 |
+
### Added
|
| 351 |
+
|
| 352 |
+
- Improved error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #354)
|
| 353 |
+
|
| 354 |
+
### Fixed
|
| 355 |
+
|
| 356 |
+
- Switched to `anyio` as the default backend implementation when running with `asyncio`. Resolves some awkward [TLS timeout issues](https://github.com/encode/httpx/discussions/1511).
|
| 357 |
+
|
| 358 |
+
## 0.13.3 (May 6th, 2021)
|
| 359 |
+
|
| 360 |
+
### Added
|
| 361 |
+
|
| 362 |
+
- Support HTTP/2 prior knowledge, using `httpcore.SyncConnectionPool(http1=False)`. (Pull #333)
|
| 363 |
+
|
| 364 |
+
### Fixed
|
| 365 |
+
|
| 366 |
+
- Handle cases where environment does not provide `select.poll` support. (Pull #331)
|
| 367 |
+
|
| 368 |
+
## 0.13.2 (April 29th, 2021)
|
| 369 |
+
|
| 370 |
+
### Added
|
| 371 |
+
|
| 372 |
+
- Improve error message for specific case of `RemoteProtocolError` where server disconnects without sending a response. (Pull #313)
|
| 373 |
+
|
| 374 |
+
## 0.13.1 (April 28th, 2021)
|
| 375 |
+
|
| 376 |
+
### Fixed
|
| 377 |
+
|
| 378 |
+
- More resiliant testing for closed connections. (Pull #311)
|
| 379 |
+
- Don't raise exceptions on ungraceful connection closes. (Pull #310)
|
| 380 |
+
|
| 381 |
+
## 0.13.0 (April 21st, 2021)
|
| 382 |
+
|
| 383 |
+
The 0.13 release updates the core API in order to match the HTTPX Transport API,
|
| 384 |
+
introduced in HTTPX 0.18 onwards.
|
| 385 |
+
|
| 386 |
+
An example of making requests with the new interface is:
|
| 387 |
+
|
| 388 |
+
```python
|
| 389 |
+
with httpcore.SyncConnectionPool() as http:
|
| 390 |
+
status_code, headers, stream, extensions = http.handle_request(
|
| 391 |
+
method=b'GET',
|
| 392 |
+
url=(b'https', b'example.org', 443, b'/'),
|
| 393 |
+
headers=[(b'host', b'example.org'), (b'user-agent', b'httpcore')]
|
| 394 |
+
stream=httpcore.ByteStream(b''),
|
| 395 |
+
extensions={}
|
| 396 |
+
)
|
| 397 |
+
body = stream.read()
|
| 398 |
+
print(status_code, body)
|
| 399 |
+
```
|
| 400 |
+
|
| 401 |
+
### Changed
|
| 402 |
+
|
| 403 |
+
- The `.request()` method is now `handle_request()`. (Pull #296)
|
| 404 |
+
- The `.arequest()` method is now `.handle_async_request()`. (Pull #296)
|
| 405 |
+
- The `headers` argument is no longer optional. (Pull #296)
|
| 406 |
+
- The `stream` argument is no longer optional. (Pull #296)
|
| 407 |
+
- The `ext` argument is now named `extensions`, and is no longer optional. (Pull #296)
|
| 408 |
+
- The `"reason"` extension keyword is now named `"reason_phrase"`. (Pull #296)
|
| 409 |
+
- The `"reason_phrase"` and `"http_version"` extensions now use byte strings for their values. (Pull #296)
|
| 410 |
+
- The `httpcore.PlainByteStream()` class becomes `httpcore.ByteStream()`. (Pull #296)
|
| 411 |
+
|
| 412 |
+
### Added
|
| 413 |
+
|
| 414 |
+
- Streams now support a `.read()` interface. (Pull #296)
|
| 415 |
+
|
| 416 |
+
### Fixed
|
| 417 |
+
|
| 418 |
+
- Task cancellation no longer leaks connections from the connection pool. (Pull #305)
|
| 419 |
+
|
| 420 |
+
## 0.12.3 (December 7th, 2020)
|
| 421 |
+
|
| 422 |
+
### Fixed
|
| 423 |
+
|
| 424 |
+
- Abort SSL connections on close rather than waiting for remote EOF when using `asyncio`. (Pull #167)
|
| 425 |
+
- Fix exception raised in case of connect timeouts when using the `anyio` backend. (Pull #236)
|
| 426 |
+
- Fix `Host` header precedence for `:authority` in HTTP/2. (Pull #241, #243)
|
| 427 |
+
- Handle extra edge case when detecting for socket readability when using `asyncio`. (Pull #242, #244)
|
| 428 |
+
- Fix `asyncio` SSL warning when using proxy tunneling. (Pull #249)
|
| 429 |
+
|
| 430 |
+
## 0.12.2 (November 20th, 2020)
|
| 431 |
+
|
| 432 |
+
### Fixed
|
| 433 |
+
|
| 434 |
+
- Properly wrap connect errors on the asyncio backend. (Pull #235)
|
| 435 |
+
- Fix `ImportError` occurring on Python 3.9 when using the HTTP/1.1 sync client in a multithreaded context. (Pull #237)
|
| 436 |
+
|
| 437 |
+
## 0.12.1 (November 7th, 2020)
|
| 438 |
+
|
| 439 |
+
### Added
|
| 440 |
+
|
| 441 |
+
- Add connect retries. (Pull #221)
|
| 442 |
+
|
| 443 |
+
### Fixed
|
| 444 |
+
|
| 445 |
+
- Tweak detection of dropped connections, resolving an issue with open files limits on Linux. (Pull #185)
|
| 446 |
+
- Avoid leaking connections when establishing an HTTP tunnel to a proxy has failed. (Pull #223)
|
| 447 |
+
- Properly wrap OS errors when using `trio`. (Pull #225)
|
| 448 |
+
|
| 449 |
+
## 0.12.0 (October 6th, 2020)
|
| 450 |
+
|
| 451 |
+
### Changed
|
| 452 |
+
|
| 453 |
+
- HTTP header casing is now preserved, rather than always sent in lowercase. (#216 and python-hyper/h11#104)
|
| 454 |
+
|
| 455 |
+
### Added
|
| 456 |
+
|
| 457 |
+
- Add Python 3.9 to officially supported versions.
|
| 458 |
+
|
| 459 |
+
### Fixed
|
| 460 |
+
|
| 461 |
+
- Gracefully handle a stdlib asyncio bug when a connection is closed while it is in a paused-for-reading state. (#201)
|
| 462 |
+
|
| 463 |
+
## 0.11.1 (September 28nd, 2020)
|
| 464 |
+
|
| 465 |
+
### Fixed
|
| 466 |
+
|
| 467 |
+
- Add await to async semaphore release() coroutine (#197)
|
| 468 |
+
- Drop incorrect curio classifier (#192)
|
| 469 |
+
|
| 470 |
+
## 0.11.0 (September 22nd, 2020)
|
| 471 |
+
|
| 472 |
+
The Transport API with 0.11.0 has a couple of significant changes.
|
| 473 |
+
|
| 474 |
+
Firstly we've moved changed the request interface in order to allow extensions, which will later enable us to support features
|
| 475 |
+
such as trailing headers, HTTP/2 server push, and CONNECT/Upgrade connections.
|
| 476 |
+
|
| 477 |
+
The interface changes from:
|
| 478 |
+
|
| 479 |
+
```python
|
| 480 |
+
def request(method, url, headers, stream, timeout):
|
| 481 |
+
return (http_version, status_code, reason, headers, stream)
|
| 482 |
+
```
|
| 483 |
+
|
| 484 |
+
To instead including an optional dictionary of extensions on the request and response:
|
| 485 |
+
|
| 486 |
+
```python
|
| 487 |
+
def request(method, url, headers, stream, ext):
|
| 488 |
+
return (status_code, headers, stream, ext)
|
| 489 |
+
```
|
| 490 |
+
|
| 491 |
+
Having an open-ended extensions point will allow us to add later support for various optional features, that wouldn't otherwise be supported without these API changes.
|
| 492 |
+
|
| 493 |
+
In particular:
|
| 494 |
+
|
| 495 |
+
* Trailing headers support.
|
| 496 |
+
* HTTP/2 Server Push
|
| 497 |
+
* sendfile.
|
| 498 |
+
* Exposing raw connection on CONNECT, Upgrade, HTTP/2 bi-di streaming.
|
| 499 |
+
* Exposing debug information out of the API, including template name, template context.
|
| 500 |
+
|
| 501 |
+
Currently extensions are limited to:
|
| 502 |
+
|
| 503 |
+
* request: `timeout` - Optional. Timeout dictionary.
|
| 504 |
+
* response: `http_version` - Optional. Include the HTTP version used on the response.
|
| 505 |
+
* response: `reason` - Optional. Include the reason phrase used on the response. Only valid with HTTP/1.*.
|
| 506 |
+
|
| 507 |
+
See https://github.com/encode/httpx/issues/1274#issuecomment-694884553 for the history behind this.
|
| 508 |
+
|
| 509 |
+
Secondly, the async version of `request` is now namespaced as `arequest`.
|
| 510 |
+
|
| 511 |
+
This allows concrete transports to support both sync and async implementations on the same class.
|
| 512 |
+
|
| 513 |
+
### Added
|
| 514 |
+
|
| 515 |
+
- Add curio support. (Pull #168)
|
| 516 |
+
- Add anyio support, with `backend="anyio"`. (Pull #169)
|
| 517 |
+
|
| 518 |
+
### Changed
|
| 519 |
+
|
| 520 |
+
- Update the Transport API to use 'ext' for optional extensions. (Pull #190)
|
| 521 |
+
- Update the Transport API to use `.request` and `.arequest` so implementations can support both sync and async. (Pull #189)
|
| 522 |
+
|
| 523 |
+
## 0.10.2 (August 20th, 2020)
|
| 524 |
+
|
| 525 |
+
### Added
|
| 526 |
+
|
| 527 |
+
- Added Unix Domain Socket support. (Pull #139)
|
| 528 |
+
|
| 529 |
+
### Fixed
|
| 530 |
+
|
| 531 |
+
- Always include the port on proxy CONNECT requests. (Pull #154)
|
| 532 |
+
- Fix `max_keepalive_connections` configuration. (Pull #153)
|
| 533 |
+
- Fixes behaviour in HTTP/1.1 where server disconnects can be used to signal the end of the response body. (Pull #164)
|
| 534 |
+
|
| 535 |
+
## 0.10.1 (August 7th, 2020)
|
| 536 |
+
|
| 537 |
+
- Include `max_keepalive_connections` on `AsyncHTTPProxy`/`SyncHTTPProxy` classes.
|
| 538 |
+
|
| 539 |
+
## 0.10.0 (August 7th, 2020)
|
| 540 |
+
|
| 541 |
+
The most notable change in the 0.10.0 release is that HTTP/2 support is now fully optional.
|
| 542 |
+
|
| 543 |
+
Use either `pip install httpcore` for HTTP/1.1 support only, or `pip install httpcore[http2]` for HTTP/1.1 and HTTP/2 support.
|
| 544 |
+
|
| 545 |
+
### Added
|
| 546 |
+
|
| 547 |
+
- HTTP/2 support becomes optional. (Pull #121, #130)
|
| 548 |
+
- Add `local_address=...` support. (Pull #100, #134)
|
| 549 |
+
- Add `PlainByteStream`, `IteratorByteStream`, `AsyncIteratorByteStream`. The `AsyncByteSteam` and `SyncByteStream` classes are now pure interface classes. (#133)
|
| 550 |
+
- Add `LocalProtocolError`, `RemoteProtocolError` exceptions. (Pull #129)
|
| 551 |
+
- Add `UnsupportedProtocol` exception. (Pull #128)
|
| 552 |
+
- Add `.get_connection_info()` method. (Pull #102, #137)
|
| 553 |
+
- Add better TRACE logs. (Pull #101)
|
| 554 |
+
|
| 555 |
+
### Changed
|
| 556 |
+
|
| 557 |
+
- `max_keepalive` is deprecated in favour of `max_keepalive_connections`. (Pull #140)
|
| 558 |
+
|
| 559 |
+
### Fixed
|
| 560 |
+
|
| 561 |
+
- Improve handling of server disconnects. (Pull #112)
|
| 562 |
+
|
| 563 |
+
## 0.9.1 (May 27th, 2020)
|
| 564 |
+
|
| 565 |
+
### Fixed
|
| 566 |
+
|
| 567 |
+
- Proper host resolution for sync case, including IPv6 support. (Pull #97)
|
| 568 |
+
- Close outstanding connections when connection pool is closed. (Pull #98)
|
| 569 |
+
|
| 570 |
+
## 0.9.0 (May 21th, 2020)
|
| 571 |
+
|
| 572 |
+
### Changed
|
| 573 |
+
|
| 574 |
+
- URL port becomes an `Optional[int]` instead of `int`. (Pull #92)
|
| 575 |
+
|
| 576 |
+
### Fixed
|
| 577 |
+
|
| 578 |
+
- Honor HTTP/2 max concurrent streams settings. (Pull #89, #90)
|
| 579 |
+
- Remove incorrect debug log. (Pull #83)
|
| 580 |
+
|
| 581 |
+
## 0.8.4 (May 11th, 2020)
|
| 582 |
+
|
| 583 |
+
### Added
|
| 584 |
+
|
| 585 |
+
- Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variables
|
| 586 |
+
and TRACE level logging. (Pull #79)
|
| 587 |
+
|
| 588 |
+
### Fixed
|
| 589 |
+
|
| 590 |
+
- Reuse of connections on HTTP/2 in close concurrency situations. (Pull #81)
|
| 591 |
+
|
| 592 |
+
## 0.8.3 (May 6rd, 2020)
|
| 593 |
+
|
| 594 |
+
### Fixed
|
| 595 |
+
|
| 596 |
+
- Include `Host` and `Accept` headers on proxy "CONNECT" requests.
|
| 597 |
+
- De-duplicate any headers also contained in proxy_headers.
|
| 598 |
+
- HTTP/2 flag not being passed down to proxy connections.
|
| 599 |
+
|
| 600 |
+
## 0.8.2 (May 3rd, 2020)
|
| 601 |
+
|
| 602 |
+
### Fixed
|
| 603 |
+
|
| 604 |
+
- Fix connections using proxy forwarding requests not being added to the
|
| 605 |
+
connection pool properly. (Pull #70)
|
| 606 |
+
|
| 607 |
+
## 0.8.1 (April 30th, 2020)
|
| 608 |
+
|
| 609 |
+
### Changed
|
| 610 |
+
|
| 611 |
+
- Allow inherintance of both `httpcore.AsyncByteStream`, `httpcore.SyncByteStream` without type conflicts.
|
| 612 |
+
|
| 613 |
+
## 0.8.0 (April 30th, 2020)
|
| 614 |
+
|
| 615 |
+
### Fixed
|
| 616 |
+
|
| 617 |
+
- Fixed tunnel proxy support.
|
| 618 |
+
|
| 619 |
+
### Added
|
| 620 |
+
|
| 621 |
+
- New `TimeoutException` base class.
|
| 622 |
+
|
| 623 |
+
## 0.7.0 (March 5th, 2020)
|
| 624 |
+
|
| 625 |
+
- First integration with HTTPX.
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore-1.0.9.dist-info/RECORD
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
httpcore/__init__.py,sha256=9kT_kqChCCJUTHww24ZmR_ezcdbpRYWksD-gYNzkZP8,3445
|
| 2 |
+
httpcore/_api.py,sha256=unZmeDschBWCGCPCwkS3Wot9euK6bg_kKxLtGTxw214,3146
|
| 3 |
+
httpcore/_exceptions.py,sha256=looCKga3_YVYu3s-d3L9RMPRJyhsY7fiuuGxvkOD0c0,1184
|
| 4 |
+
httpcore/_models.py,sha256=IO2CcXcdpovRcLTdGFGB6RyBZdEm2h_TOmoCc4rEKho,17623
|
| 5 |
+
httpcore/_ssl.py,sha256=srqmSNU4iOUvWF-SrJvb8G_YEbHFELOXQOwdDIBTS9c,187
|
| 6 |
+
httpcore/_synchronization.py,sha256=zSi13mAColBnknjZBknUC6hKNDQT4C6ijnezZ-r0T2s,9434
|
| 7 |
+
httpcore/_trace.py,sha256=ck6ZoIzYTkdNAIfq5MGeKqBXDtqjOX-qfYwmZFbrGco,3952
|
| 8 |
+
httpcore/_utils.py,sha256=_RLgXYOAYC350ikALV59GZ68IJrdocRZxPs9PjmzdFY,1537
|
| 9 |
+
httpcore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 10 |
+
httpcore/_async/__init__.py,sha256=EWdl2v4thnAHzJpqjU4h2a8DUiGAvNiWrkii9pfhTf0,1221
|
| 11 |
+
httpcore/_async/connection.py,sha256=6OcPXqMEfc0BU38_-iHUNDd1vKSTc2UVT09XqNb_BOk,8449
|
| 12 |
+
httpcore/_async/connection_pool.py,sha256=DOIQ2s2ZCf9qfwxhzMprTPLqCL8OxGXiKF6qRHxvVyY,17307
|
| 13 |
+
httpcore/_async/http11.py,sha256=-qM9bV7PjSQF5vxs37-eUXOIFwbIjPcZbNliuX9TtBw,13880
|
| 14 |
+
httpcore/_async/http2.py,sha256=azX1fcmtXaIwjputFlZ4vd92J8xwjGOa9ax9QIv4394,23936
|
| 15 |
+
httpcore/_async/http_proxy.py,sha256=2zVkrlv-Ds-rWGaqaXlrhEJiAQFPo23BT3Gq_sWoBXU,14701
|
| 16 |
+
httpcore/_async/interfaces.py,sha256=jTiaWL83pgpGC9ziv90ZfwaKNMmHwmOalzaKiuTxATo,4455
|
| 17 |
+
httpcore/_async/socks_proxy.py,sha256=lLKgLlggPfhFlqi0ODeBkOWvt9CghBBUyqsnsU1tx6Q,13841
|
| 18 |
+
httpcore/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 19 |
+
httpcore/_backends/anyio.py,sha256=x8PgEhXRC8bVqsdzk_YJx8Y6d9Tub06CuUSwnbmtqoY,5252
|
| 20 |
+
httpcore/_backends/auto.py,sha256=zO136PKZmsaTDK-HRk84eA-MUg8_2wJf4NvmK432Aio,1662
|
| 21 |
+
httpcore/_backends/base.py,sha256=aShgRdZnMmRhFWHetjumlM73f8Kz1YOAyCUP_4kHslA,3042
|
| 22 |
+
httpcore/_backends/mock.py,sha256=er9T436uSe7NLrfiLa4x6Nuqg5ivQ693CxWYCWsgbH4,4077
|
| 23 |
+
httpcore/_backends/sync.py,sha256=bhE4d9iK9Umxdsdsgm2EfKnXaBms2WggGYU-7jmUujU,7977
|
| 24 |
+
httpcore/_backends/trio.py,sha256=LHu4_Mr5MswQmmT3yE4oLgf9b_JJfeVS4BjDxeJc7Ro,5996
|
| 25 |
+
httpcore/_sync/__init__.py,sha256=JBDIgXt5la1LCJ1sLQeKhjKFpLnpNr8Svs6z2ni3fgg,1141
|
| 26 |
+
httpcore/_sync/connection.py,sha256=9exGOb3PB-Mp2T1-sckSeL2t-tJ_9-NXomV8ihmWCgU,8238
|
| 27 |
+
httpcore/_sync/connection_pool.py,sha256=a-T8LTsUxc7r0Ww1atfHSDoWPjQ0fA8Ul7S3-F0Mj70,16955
|
| 28 |
+
httpcore/_sync/http11.py,sha256=IFobD1Md5JFlJGKWnh1_Q3epikUryI8qo09v8MiJIEA,13476
|
| 29 |
+
httpcore/_sync/http2.py,sha256=AxU4yhcq68Bn5vqdJYtiXKYUj7nvhYbxz3v4rT4xnvA,23400
|
| 30 |
+
httpcore/_sync/http_proxy.py,sha256=_al_6crKuEZu2wyvu493RZImJdBJnj5oGKNjLOJL2Zo,14463
|
| 31 |
+
httpcore/_sync/interfaces.py,sha256=snXON42vUDHO5JBJvo8D4VWk2Wat44z2OXXHDrjbl94,4344
|
| 32 |
+
httpcore/_sync/socks_proxy.py,sha256=zegZW9Snqj2_992DFJa8_CppOVBkVL4AgwduRkStakQ,13614
|
| 33 |
+
httpcore-1.0.9.dist-info/METADATA,sha256=_i1P2mGZEol4d54M8n88BFxTGGP83Zh-rMdPOhjUHCE,21529
|
| 34 |
+
httpcore-1.0.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
| 35 |
+
httpcore-1.0.9.dist-info/licenses/LICENSE.md,sha256=_ctZFUx0y6uhahEkL3dAvqnyPW_rVUeRfYxflKgDkqU,1518
|
| 36 |
+
httpcore-1.0.9.dist-info/RECORD,,
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore-1.0.9.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.27.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore-1.0.9.dist-info/licenses/LICENSE.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright © 2020, [Encode OSS Ltd](https://www.encode.io/).
|
| 2 |
+
All rights reserved.
|
| 3 |
+
|
| 4 |
+
Redistribution and use in source and binary forms, with or without
|
| 5 |
+
modification, are permitted provided that the following conditions are met:
|
| 6 |
+
|
| 7 |
+
* Redistributions of source code must retain the above copyright notice, this
|
| 8 |
+
list of conditions and the following disclaimer.
|
| 9 |
+
|
| 10 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 11 |
+
this list of conditions and the following disclaimer in the documentation
|
| 12 |
+
and/or other materials provided with the distribution.
|
| 13 |
+
|
| 14 |
+
* Neither the name of the copyright holder nor the names of its
|
| 15 |
+
contributors may be used to endorse or promote products derived from
|
| 16 |
+
this software without specific prior written permission.
|
| 17 |
+
|
| 18 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 19 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 20 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 21 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 22 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 23 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 24 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 26 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 27 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/__init__.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._api import request, stream
|
| 2 |
+
from ._async import (
|
| 3 |
+
AsyncConnectionInterface,
|
| 4 |
+
AsyncConnectionPool,
|
| 5 |
+
AsyncHTTP2Connection,
|
| 6 |
+
AsyncHTTP11Connection,
|
| 7 |
+
AsyncHTTPConnection,
|
| 8 |
+
AsyncHTTPProxy,
|
| 9 |
+
AsyncSOCKSProxy,
|
| 10 |
+
)
|
| 11 |
+
from ._backends.base import (
|
| 12 |
+
SOCKET_OPTION,
|
| 13 |
+
AsyncNetworkBackend,
|
| 14 |
+
AsyncNetworkStream,
|
| 15 |
+
NetworkBackend,
|
| 16 |
+
NetworkStream,
|
| 17 |
+
)
|
| 18 |
+
from ._backends.mock import AsyncMockBackend, AsyncMockStream, MockBackend, MockStream
|
| 19 |
+
from ._backends.sync import SyncBackend
|
| 20 |
+
from ._exceptions import (
|
| 21 |
+
ConnectError,
|
| 22 |
+
ConnectionNotAvailable,
|
| 23 |
+
ConnectTimeout,
|
| 24 |
+
LocalProtocolError,
|
| 25 |
+
NetworkError,
|
| 26 |
+
PoolTimeout,
|
| 27 |
+
ProtocolError,
|
| 28 |
+
ProxyError,
|
| 29 |
+
ReadError,
|
| 30 |
+
ReadTimeout,
|
| 31 |
+
RemoteProtocolError,
|
| 32 |
+
TimeoutException,
|
| 33 |
+
UnsupportedProtocol,
|
| 34 |
+
WriteError,
|
| 35 |
+
WriteTimeout,
|
| 36 |
+
)
|
| 37 |
+
from ._models import URL, Origin, Proxy, Request, Response
|
| 38 |
+
from ._ssl import default_ssl_context
|
| 39 |
+
from ._sync import (
|
| 40 |
+
ConnectionInterface,
|
| 41 |
+
ConnectionPool,
|
| 42 |
+
HTTP2Connection,
|
| 43 |
+
HTTP11Connection,
|
| 44 |
+
HTTPConnection,
|
| 45 |
+
HTTPProxy,
|
| 46 |
+
SOCKSProxy,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# The 'httpcore.AnyIOBackend' class is conditional on 'anyio' being installed.
|
| 50 |
+
try:
|
| 51 |
+
from ._backends.anyio import AnyIOBackend
|
| 52 |
+
except ImportError: # pragma: nocover
|
| 53 |
+
|
| 54 |
+
class AnyIOBackend: # type: ignore
|
| 55 |
+
def __init__(self, *args, **kwargs): # type: ignore
|
| 56 |
+
msg = (
|
| 57 |
+
"Attempted to use 'httpcore.AnyIOBackend' but 'anyio' is not installed."
|
| 58 |
+
)
|
| 59 |
+
raise RuntimeError(msg)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# The 'httpcore.TrioBackend' class is conditional on 'trio' being installed.
|
| 63 |
+
try:
|
| 64 |
+
from ._backends.trio import TrioBackend
|
| 65 |
+
except ImportError: # pragma: nocover
|
| 66 |
+
|
| 67 |
+
class TrioBackend: # type: ignore
|
| 68 |
+
def __init__(self, *args, **kwargs): # type: ignore
|
| 69 |
+
msg = "Attempted to use 'httpcore.TrioBackend' but 'trio' is not installed."
|
| 70 |
+
raise RuntimeError(msg)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
__all__ = [
|
| 74 |
+
# top-level requests
|
| 75 |
+
"request",
|
| 76 |
+
"stream",
|
| 77 |
+
# models
|
| 78 |
+
"Origin",
|
| 79 |
+
"URL",
|
| 80 |
+
"Request",
|
| 81 |
+
"Response",
|
| 82 |
+
"Proxy",
|
| 83 |
+
# async
|
| 84 |
+
"AsyncHTTPConnection",
|
| 85 |
+
"AsyncConnectionPool",
|
| 86 |
+
"AsyncHTTPProxy",
|
| 87 |
+
"AsyncHTTP11Connection",
|
| 88 |
+
"AsyncHTTP2Connection",
|
| 89 |
+
"AsyncConnectionInterface",
|
| 90 |
+
"AsyncSOCKSProxy",
|
| 91 |
+
# sync
|
| 92 |
+
"HTTPConnection",
|
| 93 |
+
"ConnectionPool",
|
| 94 |
+
"HTTPProxy",
|
| 95 |
+
"HTTP11Connection",
|
| 96 |
+
"HTTP2Connection",
|
| 97 |
+
"ConnectionInterface",
|
| 98 |
+
"SOCKSProxy",
|
| 99 |
+
# network backends, implementations
|
| 100 |
+
"SyncBackend",
|
| 101 |
+
"AnyIOBackend",
|
| 102 |
+
"TrioBackend",
|
| 103 |
+
# network backends, mock implementations
|
| 104 |
+
"AsyncMockBackend",
|
| 105 |
+
"AsyncMockStream",
|
| 106 |
+
"MockBackend",
|
| 107 |
+
"MockStream",
|
| 108 |
+
# network backends, interface
|
| 109 |
+
"AsyncNetworkStream",
|
| 110 |
+
"AsyncNetworkBackend",
|
| 111 |
+
"NetworkStream",
|
| 112 |
+
"NetworkBackend",
|
| 113 |
+
# util
|
| 114 |
+
"default_ssl_context",
|
| 115 |
+
"SOCKET_OPTION",
|
| 116 |
+
# exceptions
|
| 117 |
+
"ConnectionNotAvailable",
|
| 118 |
+
"ProxyError",
|
| 119 |
+
"ProtocolError",
|
| 120 |
+
"LocalProtocolError",
|
| 121 |
+
"RemoteProtocolError",
|
| 122 |
+
"UnsupportedProtocol",
|
| 123 |
+
"TimeoutException",
|
| 124 |
+
"PoolTimeout",
|
| 125 |
+
"ConnectTimeout",
|
| 126 |
+
"ReadTimeout",
|
| 127 |
+
"WriteTimeout",
|
| 128 |
+
"NetworkError",
|
| 129 |
+
"ConnectError",
|
| 130 |
+
"ReadError",
|
| 131 |
+
"WriteError",
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
__version__ = "1.0.9"
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
__locals = locals()
|
| 138 |
+
for __name in __all__:
|
| 139 |
+
# Exclude SOCKET_OPTION, it causes AttributeError on Python 3.14
|
| 140 |
+
if not __name.startswith(("__", "SOCKET_OPTION")):
|
| 141 |
+
setattr(__locals[__name], "__module__", "httpcore") # noqa
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_api.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import typing
|
| 5 |
+
|
| 6 |
+
from ._models import URL, Extensions, HeaderTypes, Response
|
| 7 |
+
from ._sync.connection_pool import ConnectionPool
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def request(
|
| 11 |
+
method: bytes | str,
|
| 12 |
+
url: URL | bytes | str,
|
| 13 |
+
*,
|
| 14 |
+
headers: HeaderTypes = None,
|
| 15 |
+
content: bytes | typing.Iterator[bytes] | None = None,
|
| 16 |
+
extensions: Extensions | None = None,
|
| 17 |
+
) -> Response:
|
| 18 |
+
"""
|
| 19 |
+
Sends an HTTP request, returning the response.
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
response = httpcore.request("GET", "https://www.example.com/")
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
Arguments:
|
| 26 |
+
method: The HTTP method for the request. Typically one of `"GET"`,
|
| 27 |
+
`"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`.
|
| 28 |
+
url: The URL of the HTTP request. Either as an instance of `httpcore.URL`,
|
| 29 |
+
or as str/bytes.
|
| 30 |
+
headers: The HTTP request headers. Either as a dictionary of str/bytes,
|
| 31 |
+
or as a list of two-tuples of str/bytes.
|
| 32 |
+
content: The content of the request body. Either as bytes,
|
| 33 |
+
or as a bytes iterator.
|
| 34 |
+
extensions: A dictionary of optional extra information included on the request.
|
| 35 |
+
Possible keys include `"timeout"`.
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
An instance of `httpcore.Response`.
|
| 39 |
+
"""
|
| 40 |
+
with ConnectionPool() as pool:
|
| 41 |
+
return pool.request(
|
| 42 |
+
method=method,
|
| 43 |
+
url=url,
|
| 44 |
+
headers=headers,
|
| 45 |
+
content=content,
|
| 46 |
+
extensions=extensions,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@contextlib.contextmanager
|
| 51 |
+
def stream(
|
| 52 |
+
method: bytes | str,
|
| 53 |
+
url: URL | bytes | str,
|
| 54 |
+
*,
|
| 55 |
+
headers: HeaderTypes = None,
|
| 56 |
+
content: bytes | typing.Iterator[bytes] | None = None,
|
| 57 |
+
extensions: Extensions | None = None,
|
| 58 |
+
) -> typing.Iterator[Response]:
|
| 59 |
+
"""
|
| 60 |
+
Sends an HTTP request, returning the response within a content manager.
|
| 61 |
+
|
| 62 |
+
```
|
| 63 |
+
with httpcore.stream("GET", "https://www.example.com/") as response:
|
| 64 |
+
...
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
When using the `stream()` function, the body of the response will not be
|
| 68 |
+
automatically read. If you want to access the response body you should
|
| 69 |
+
either use `content = response.read()`, or `for chunk in response.iter_content()`.
|
| 70 |
+
|
| 71 |
+
Arguments:
|
| 72 |
+
method: The HTTP method for the request. Typically one of `"GET"`,
|
| 73 |
+
`"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`.
|
| 74 |
+
url: The URL of the HTTP request. Either as an instance of `httpcore.URL`,
|
| 75 |
+
or as str/bytes.
|
| 76 |
+
headers: The HTTP request headers. Either as a dictionary of str/bytes,
|
| 77 |
+
or as a list of two-tuples of str/bytes.
|
| 78 |
+
content: The content of the request body. Either as bytes,
|
| 79 |
+
or as a bytes iterator.
|
| 80 |
+
extensions: A dictionary of optional extra information included on the request.
|
| 81 |
+
Possible keys include `"timeout"`.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
An instance of `httpcore.Response`.
|
| 85 |
+
"""
|
| 86 |
+
with ConnectionPool() as pool:
|
| 87 |
+
with pool.stream(
|
| 88 |
+
method=method,
|
| 89 |
+
url=url,
|
| 90 |
+
headers=headers,
|
| 91 |
+
content=content,
|
| 92 |
+
extensions=extensions,
|
| 93 |
+
) as response:
|
| 94 |
+
yield response
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .connection import AsyncHTTPConnection
|
| 2 |
+
from .connection_pool import AsyncConnectionPool
|
| 3 |
+
from .http11 import AsyncHTTP11Connection
|
| 4 |
+
from .http_proxy import AsyncHTTPProxy
|
| 5 |
+
from .interfaces import AsyncConnectionInterface
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from .http2 import AsyncHTTP2Connection
|
| 9 |
+
except ImportError: # pragma: nocover
|
| 10 |
+
|
| 11 |
+
class AsyncHTTP2Connection: # type: ignore
|
| 12 |
+
def __init__(self, *args, **kwargs) -> None: # type: ignore
|
| 13 |
+
raise RuntimeError(
|
| 14 |
+
"Attempted to use http2 support, but the `h2` package is not "
|
| 15 |
+
"installed. Use 'pip install httpcore[http2]'."
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
from .socks_proxy import AsyncSOCKSProxy
|
| 21 |
+
except ImportError: # pragma: nocover
|
| 22 |
+
|
| 23 |
+
class AsyncSOCKSProxy: # type: ignore
|
| 24 |
+
def __init__(self, *args, **kwargs) -> None: # type: ignore
|
| 25 |
+
raise RuntimeError(
|
| 26 |
+
"Attempted to use SOCKS support, but the `socksio` package is not "
|
| 27 |
+
"installed. Use 'pip install httpcore[socks]'."
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
__all__ = [
|
| 32 |
+
"AsyncHTTPConnection",
|
| 33 |
+
"AsyncConnectionPool",
|
| 34 |
+
"AsyncHTTPProxy",
|
| 35 |
+
"AsyncHTTP11Connection",
|
| 36 |
+
"AsyncHTTP2Connection",
|
| 37 |
+
"AsyncConnectionInterface",
|
| 38 |
+
"AsyncSOCKSProxy",
|
| 39 |
+
]
|
.cache/uv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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import itertools
|
| 4 |
+
import logging
|
| 5 |
+
import ssl
|
| 6 |
+
import types
|
| 7 |
+
import typing
|
| 8 |
+
|
| 9 |
+
from .._backends.auto import AutoBackend
|
| 10 |
+
from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
|
| 11 |
+
from .._exceptions import ConnectError, ConnectTimeout
|
| 12 |
+
from .._models import Origin, Request, Response
|
| 13 |
+
from .._ssl import default_ssl_context
|
| 14 |
+
from .._synchronization import AsyncLock
|
| 15 |
+
from .._trace import Trace
|
| 16 |
+
from .http11 import AsyncHTTP11Connection
|
| 17 |
+
from .interfaces import AsyncConnectionInterface
|
| 18 |
+
|
| 19 |
+
RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger("httpcore.connection")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def exponential_backoff(factor: float) -> typing.Iterator[float]:
|
| 26 |
+
"""
|
| 27 |
+
Generate a geometric sequence that has a ratio of 2 and starts with 0.
|
| 28 |
+
|
| 29 |
+
For example:
|
| 30 |
+
- `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...`
|
| 31 |
+
- `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...`
|
| 32 |
+
"""
|
| 33 |
+
yield 0
|
| 34 |
+
for n in itertools.count():
|
| 35 |
+
yield factor * 2**n
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class AsyncHTTPConnection(AsyncConnectionInterface):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
origin: Origin,
|
| 42 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 43 |
+
keepalive_expiry: float | None = None,
|
| 44 |
+
http1: bool = True,
|
| 45 |
+
http2: bool = False,
|
| 46 |
+
retries: int = 0,
|
| 47 |
+
local_address: str | None = None,
|
| 48 |
+
uds: str | None = None,
|
| 49 |
+
network_backend: AsyncNetworkBackend | None = None,
|
| 50 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 51 |
+
) -> None:
|
| 52 |
+
self._origin = origin
|
| 53 |
+
self._ssl_context = ssl_context
|
| 54 |
+
self._keepalive_expiry = keepalive_expiry
|
| 55 |
+
self._http1 = http1
|
| 56 |
+
self._http2 = http2
|
| 57 |
+
self._retries = retries
|
| 58 |
+
self._local_address = local_address
|
| 59 |
+
self._uds = uds
|
| 60 |
+
|
| 61 |
+
self._network_backend: AsyncNetworkBackend = (
|
| 62 |
+
AutoBackend() if network_backend is None else network_backend
|
| 63 |
+
)
|
| 64 |
+
self._connection: AsyncConnectionInterface | None = None
|
| 65 |
+
self._connect_failed: bool = False
|
| 66 |
+
self._request_lock = AsyncLock()
|
| 67 |
+
self._socket_options = socket_options
|
| 68 |
+
|
| 69 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 70 |
+
if not self.can_handle_request(request.url.origin):
|
| 71 |
+
raise RuntimeError(
|
| 72 |
+
f"Attempted to send request to {request.url.origin} on connection to {self._origin}"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
async with self._request_lock:
|
| 77 |
+
if self._connection is None:
|
| 78 |
+
stream = await self._connect(request)
|
| 79 |
+
|
| 80 |
+
ssl_object = stream.get_extra_info("ssl_object")
|
| 81 |
+
http2_negotiated = (
|
| 82 |
+
ssl_object is not None
|
| 83 |
+
and ssl_object.selected_alpn_protocol() == "h2"
|
| 84 |
+
)
|
| 85 |
+
if http2_negotiated or (self._http2 and not self._http1):
|
| 86 |
+
from .http2 import AsyncHTTP2Connection
|
| 87 |
+
|
| 88 |
+
self._connection = AsyncHTTP2Connection(
|
| 89 |
+
origin=self._origin,
|
| 90 |
+
stream=stream,
|
| 91 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 92 |
+
)
|
| 93 |
+
else:
|
| 94 |
+
self._connection = AsyncHTTP11Connection(
|
| 95 |
+
origin=self._origin,
|
| 96 |
+
stream=stream,
|
| 97 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 98 |
+
)
|
| 99 |
+
except BaseException as exc:
|
| 100 |
+
self._connect_failed = True
|
| 101 |
+
raise exc
|
| 102 |
+
|
| 103 |
+
return await self._connection.handle_async_request(request)
|
| 104 |
+
|
| 105 |
+
async def _connect(self, request: Request) -> AsyncNetworkStream:
|
| 106 |
+
timeouts = request.extensions.get("timeout", {})
|
| 107 |
+
sni_hostname = request.extensions.get("sni_hostname", None)
|
| 108 |
+
timeout = timeouts.get("connect", None)
|
| 109 |
+
|
| 110 |
+
retries_left = self._retries
|
| 111 |
+
delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR)
|
| 112 |
+
|
| 113 |
+
while True:
|
| 114 |
+
try:
|
| 115 |
+
if self._uds is None:
|
| 116 |
+
kwargs = {
|
| 117 |
+
"host": self._origin.host.decode("ascii"),
|
| 118 |
+
"port": self._origin.port,
|
| 119 |
+
"local_address": self._local_address,
|
| 120 |
+
"timeout": timeout,
|
| 121 |
+
"socket_options": self._socket_options,
|
| 122 |
+
}
|
| 123 |
+
async with Trace("connect_tcp", logger, request, kwargs) as trace:
|
| 124 |
+
stream = await self._network_backend.connect_tcp(**kwargs)
|
| 125 |
+
trace.return_value = stream
|
| 126 |
+
else:
|
| 127 |
+
kwargs = {
|
| 128 |
+
"path": self._uds,
|
| 129 |
+
"timeout": timeout,
|
| 130 |
+
"socket_options": self._socket_options,
|
| 131 |
+
}
|
| 132 |
+
async with Trace(
|
| 133 |
+
"connect_unix_socket", logger, request, kwargs
|
| 134 |
+
) as trace:
|
| 135 |
+
stream = await self._network_backend.connect_unix_socket(
|
| 136 |
+
**kwargs
|
| 137 |
+
)
|
| 138 |
+
trace.return_value = stream
|
| 139 |
+
|
| 140 |
+
if self._origin.scheme in (b"https", b"wss"):
|
| 141 |
+
ssl_context = (
|
| 142 |
+
default_ssl_context()
|
| 143 |
+
if self._ssl_context is None
|
| 144 |
+
else self._ssl_context
|
| 145 |
+
)
|
| 146 |
+
alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"]
|
| 147 |
+
ssl_context.set_alpn_protocols(alpn_protocols)
|
| 148 |
+
|
| 149 |
+
kwargs = {
|
| 150 |
+
"ssl_context": ssl_context,
|
| 151 |
+
"server_hostname": sni_hostname
|
| 152 |
+
or self._origin.host.decode("ascii"),
|
| 153 |
+
"timeout": timeout,
|
| 154 |
+
}
|
| 155 |
+
async with Trace("start_tls", logger, request, kwargs) as trace:
|
| 156 |
+
stream = await stream.start_tls(**kwargs)
|
| 157 |
+
trace.return_value = stream
|
| 158 |
+
return stream
|
| 159 |
+
except (ConnectError, ConnectTimeout):
|
| 160 |
+
if retries_left <= 0:
|
| 161 |
+
raise
|
| 162 |
+
retries_left -= 1
|
| 163 |
+
delay = next(delays)
|
| 164 |
+
async with Trace("retry", logger, request, kwargs) as trace:
|
| 165 |
+
await self._network_backend.sleep(delay)
|
| 166 |
+
|
| 167 |
+
def can_handle_request(self, origin: Origin) -> bool:
|
| 168 |
+
return origin == self._origin
|
| 169 |
+
|
| 170 |
+
async def aclose(self) -> None:
|
| 171 |
+
if self._connection is not None:
|
| 172 |
+
async with Trace("close", logger, None, {}):
|
| 173 |
+
await self._connection.aclose()
|
| 174 |
+
|
| 175 |
+
def is_available(self) -> bool:
|
| 176 |
+
if self._connection is None:
|
| 177 |
+
# If HTTP/2 support is enabled, and the resulting connection could
|
| 178 |
+
# end up as HTTP/2 then we should indicate the connection as being
|
| 179 |
+
# available to service multiple requests.
|
| 180 |
+
return (
|
| 181 |
+
self._http2
|
| 182 |
+
and (self._origin.scheme == b"https" or not self._http1)
|
| 183 |
+
and not self._connect_failed
|
| 184 |
+
)
|
| 185 |
+
return self._connection.is_available()
|
| 186 |
+
|
| 187 |
+
def has_expired(self) -> bool:
|
| 188 |
+
if self._connection is None:
|
| 189 |
+
return self._connect_failed
|
| 190 |
+
return self._connection.has_expired()
|
| 191 |
+
|
| 192 |
+
def is_idle(self) -> bool:
|
| 193 |
+
if self._connection is None:
|
| 194 |
+
return self._connect_failed
|
| 195 |
+
return self._connection.is_idle()
|
| 196 |
+
|
| 197 |
+
def is_closed(self) -> bool:
|
| 198 |
+
if self._connection is None:
|
| 199 |
+
return self._connect_failed
|
| 200 |
+
return self._connection.is_closed()
|
| 201 |
+
|
| 202 |
+
def info(self) -> str:
|
| 203 |
+
if self._connection is None:
|
| 204 |
+
return "CONNECTION FAILED" if self._connect_failed else "CONNECTING"
|
| 205 |
+
return self._connection.info()
|
| 206 |
+
|
| 207 |
+
def __repr__(self) -> str:
|
| 208 |
+
return f"<{self.__class__.__name__} [{self.info()}]>"
|
| 209 |
+
|
| 210 |
+
# These context managers are not used in the standard flow, but are
|
| 211 |
+
# useful for testing or working with connection instances directly.
|
| 212 |
+
|
| 213 |
+
async def __aenter__(self) -> AsyncHTTPConnection:
|
| 214 |
+
return self
|
| 215 |
+
|
| 216 |
+
async def __aexit__(
|
| 217 |
+
self,
|
| 218 |
+
exc_type: type[BaseException] | None = None,
|
| 219 |
+
exc_value: BaseException | None = None,
|
| 220 |
+
traceback: types.TracebackType | None = None,
|
| 221 |
+
) -> None:
|
| 222 |
+
await self.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ssl
|
| 4 |
+
import sys
|
| 5 |
+
import types
|
| 6 |
+
import typing
|
| 7 |
+
|
| 8 |
+
from .._backends.auto import AutoBackend
|
| 9 |
+
from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend
|
| 10 |
+
from .._exceptions import ConnectionNotAvailable, UnsupportedProtocol
|
| 11 |
+
from .._models import Origin, Proxy, Request, Response
|
| 12 |
+
from .._synchronization import AsyncEvent, AsyncShieldCancellation, AsyncThreadLock
|
| 13 |
+
from .connection import AsyncHTTPConnection
|
| 14 |
+
from .interfaces import AsyncConnectionInterface, AsyncRequestInterface
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class AsyncPoolRequest:
|
| 18 |
+
def __init__(self, request: Request) -> None:
|
| 19 |
+
self.request = request
|
| 20 |
+
self.connection: AsyncConnectionInterface | None = None
|
| 21 |
+
self._connection_acquired = AsyncEvent()
|
| 22 |
+
|
| 23 |
+
def assign_to_connection(self, connection: AsyncConnectionInterface | None) -> None:
|
| 24 |
+
self.connection = connection
|
| 25 |
+
self._connection_acquired.set()
|
| 26 |
+
|
| 27 |
+
def clear_connection(self) -> None:
|
| 28 |
+
self.connection = None
|
| 29 |
+
self._connection_acquired = AsyncEvent()
|
| 30 |
+
|
| 31 |
+
async def wait_for_connection(
|
| 32 |
+
self, timeout: float | None = None
|
| 33 |
+
) -> AsyncConnectionInterface:
|
| 34 |
+
if self.connection is None:
|
| 35 |
+
await self._connection_acquired.wait(timeout=timeout)
|
| 36 |
+
assert self.connection is not None
|
| 37 |
+
return self.connection
|
| 38 |
+
|
| 39 |
+
def is_queued(self) -> bool:
|
| 40 |
+
return self.connection is None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class AsyncConnectionPool(AsyncRequestInterface):
|
| 44 |
+
"""
|
| 45 |
+
A connection pool for making HTTP requests.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 51 |
+
proxy: Proxy | None = None,
|
| 52 |
+
max_connections: int | None = 10,
|
| 53 |
+
max_keepalive_connections: int | None = None,
|
| 54 |
+
keepalive_expiry: float | None = None,
|
| 55 |
+
http1: bool = True,
|
| 56 |
+
http2: bool = False,
|
| 57 |
+
retries: int = 0,
|
| 58 |
+
local_address: str | None = None,
|
| 59 |
+
uds: str | None = None,
|
| 60 |
+
network_backend: AsyncNetworkBackend | None = None,
|
| 61 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 62 |
+
) -> None:
|
| 63 |
+
"""
|
| 64 |
+
A connection pool for making HTTP requests.
|
| 65 |
+
|
| 66 |
+
Parameters:
|
| 67 |
+
ssl_context: An SSL context to use for verifying connections.
|
| 68 |
+
If not specified, the default `httpcore.default_ssl_context()`
|
| 69 |
+
will be used.
|
| 70 |
+
max_connections: The maximum number of concurrent HTTP connections that
|
| 71 |
+
the pool should allow. Any attempt to send a request on a pool that
|
| 72 |
+
would exceed this amount will block until a connection is available.
|
| 73 |
+
max_keepalive_connections: The maximum number of idle HTTP connections
|
| 74 |
+
that will be maintained in the pool.
|
| 75 |
+
keepalive_expiry: The duration in seconds that an idle HTTP connection
|
| 76 |
+
may be maintained for before being expired from the pool.
|
| 77 |
+
http1: A boolean indicating if HTTP/1.1 requests should be supported
|
| 78 |
+
by the connection pool. Defaults to True.
|
| 79 |
+
http2: A boolean indicating if HTTP/2 requests should be supported by
|
| 80 |
+
the connection pool. Defaults to False.
|
| 81 |
+
retries: The maximum number of retries when trying to establish a
|
| 82 |
+
connection.
|
| 83 |
+
local_address: Local address to connect from. Can also be used to connect
|
| 84 |
+
using a particular address family. Using `local_address="0.0.0.0"`
|
| 85 |
+
will connect using an `AF_INET` address (IPv4), while using
|
| 86 |
+
`local_address="::"` will connect using an `AF_INET6` address (IPv6).
|
| 87 |
+
uds: Path to a Unix Domain Socket to use instead of TCP sockets.
|
| 88 |
+
network_backend: A backend instance to use for handling network I/O.
|
| 89 |
+
socket_options: Socket options that have to be included
|
| 90 |
+
in the TCP socket when the connection was established.
|
| 91 |
+
"""
|
| 92 |
+
self._ssl_context = ssl_context
|
| 93 |
+
self._proxy = proxy
|
| 94 |
+
self._max_connections = (
|
| 95 |
+
sys.maxsize if max_connections is None else max_connections
|
| 96 |
+
)
|
| 97 |
+
self._max_keepalive_connections = (
|
| 98 |
+
sys.maxsize
|
| 99 |
+
if max_keepalive_connections is None
|
| 100 |
+
else max_keepalive_connections
|
| 101 |
+
)
|
| 102 |
+
self._max_keepalive_connections = min(
|
| 103 |
+
self._max_connections, self._max_keepalive_connections
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
self._keepalive_expiry = keepalive_expiry
|
| 107 |
+
self._http1 = http1
|
| 108 |
+
self._http2 = http2
|
| 109 |
+
self._retries = retries
|
| 110 |
+
self._local_address = local_address
|
| 111 |
+
self._uds = uds
|
| 112 |
+
|
| 113 |
+
self._network_backend = (
|
| 114 |
+
AutoBackend() if network_backend is None else network_backend
|
| 115 |
+
)
|
| 116 |
+
self._socket_options = socket_options
|
| 117 |
+
|
| 118 |
+
# The mutable state on a connection pool is the queue of incoming requests,
|
| 119 |
+
# and the set of connections that are servicing those requests.
|
| 120 |
+
self._connections: list[AsyncConnectionInterface] = []
|
| 121 |
+
self._requests: list[AsyncPoolRequest] = []
|
| 122 |
+
|
| 123 |
+
# We only mutate the state of the connection pool within an 'optional_thread_lock'
|
| 124 |
+
# context. This holds a threading lock unless we're running in async mode,
|
| 125 |
+
# in which case it is a no-op.
|
| 126 |
+
self._optional_thread_lock = AsyncThreadLock()
|
| 127 |
+
|
| 128 |
+
def create_connection(self, origin: Origin) -> AsyncConnectionInterface:
|
| 129 |
+
if self._proxy is not None:
|
| 130 |
+
if self._proxy.url.scheme in (b"socks5", b"socks5h"):
|
| 131 |
+
from .socks_proxy import AsyncSocks5Connection
|
| 132 |
+
|
| 133 |
+
return AsyncSocks5Connection(
|
| 134 |
+
proxy_origin=self._proxy.url.origin,
|
| 135 |
+
proxy_auth=self._proxy.auth,
|
| 136 |
+
remote_origin=origin,
|
| 137 |
+
ssl_context=self._ssl_context,
|
| 138 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 139 |
+
http1=self._http1,
|
| 140 |
+
http2=self._http2,
|
| 141 |
+
network_backend=self._network_backend,
|
| 142 |
+
)
|
| 143 |
+
elif origin.scheme == b"http":
|
| 144 |
+
from .http_proxy import AsyncForwardHTTPConnection
|
| 145 |
+
|
| 146 |
+
return AsyncForwardHTTPConnection(
|
| 147 |
+
proxy_origin=self._proxy.url.origin,
|
| 148 |
+
proxy_headers=self._proxy.headers,
|
| 149 |
+
proxy_ssl_context=self._proxy.ssl_context,
|
| 150 |
+
remote_origin=origin,
|
| 151 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 152 |
+
network_backend=self._network_backend,
|
| 153 |
+
)
|
| 154 |
+
from .http_proxy import AsyncTunnelHTTPConnection
|
| 155 |
+
|
| 156 |
+
return AsyncTunnelHTTPConnection(
|
| 157 |
+
proxy_origin=self._proxy.url.origin,
|
| 158 |
+
proxy_headers=self._proxy.headers,
|
| 159 |
+
proxy_ssl_context=self._proxy.ssl_context,
|
| 160 |
+
remote_origin=origin,
|
| 161 |
+
ssl_context=self._ssl_context,
|
| 162 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 163 |
+
http1=self._http1,
|
| 164 |
+
http2=self._http2,
|
| 165 |
+
network_backend=self._network_backend,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
return AsyncHTTPConnection(
|
| 169 |
+
origin=origin,
|
| 170 |
+
ssl_context=self._ssl_context,
|
| 171 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 172 |
+
http1=self._http1,
|
| 173 |
+
http2=self._http2,
|
| 174 |
+
retries=self._retries,
|
| 175 |
+
local_address=self._local_address,
|
| 176 |
+
uds=self._uds,
|
| 177 |
+
network_backend=self._network_backend,
|
| 178 |
+
socket_options=self._socket_options,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
@property
|
| 182 |
+
def connections(self) -> list[AsyncConnectionInterface]:
|
| 183 |
+
"""
|
| 184 |
+
Return a list of the connections currently in the pool.
|
| 185 |
+
|
| 186 |
+
For example:
|
| 187 |
+
|
| 188 |
+
```python
|
| 189 |
+
>>> pool.connections
|
| 190 |
+
[
|
| 191 |
+
<AsyncHTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 6]>,
|
| 192 |
+
<AsyncHTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 9]> ,
|
| 193 |
+
<AsyncHTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>,
|
| 194 |
+
]
|
| 195 |
+
```
|
| 196 |
+
"""
|
| 197 |
+
return list(self._connections)
|
| 198 |
+
|
| 199 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 200 |
+
"""
|
| 201 |
+
Send an HTTP request, and return an HTTP response.
|
| 202 |
+
|
| 203 |
+
This is the core implementation that is called into by `.request()` or `.stream()`.
|
| 204 |
+
"""
|
| 205 |
+
scheme = request.url.scheme.decode()
|
| 206 |
+
if scheme == "":
|
| 207 |
+
raise UnsupportedProtocol(
|
| 208 |
+
"Request URL is missing an 'http://' or 'https://' protocol."
|
| 209 |
+
)
|
| 210 |
+
if scheme not in ("http", "https", "ws", "wss"):
|
| 211 |
+
raise UnsupportedProtocol(
|
| 212 |
+
f"Request URL has an unsupported protocol '{scheme}://'."
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
timeouts = request.extensions.get("timeout", {})
|
| 216 |
+
timeout = timeouts.get("pool", None)
|
| 217 |
+
|
| 218 |
+
with self._optional_thread_lock:
|
| 219 |
+
# Add the incoming request to our request queue.
|
| 220 |
+
pool_request = AsyncPoolRequest(request)
|
| 221 |
+
self._requests.append(pool_request)
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
while True:
|
| 225 |
+
with self._optional_thread_lock:
|
| 226 |
+
# Assign incoming requests to available connections,
|
| 227 |
+
# closing or creating new connections as required.
|
| 228 |
+
closing = self._assign_requests_to_connections()
|
| 229 |
+
await self._close_connections(closing)
|
| 230 |
+
|
| 231 |
+
# Wait until this request has an assigned connection.
|
| 232 |
+
connection = await pool_request.wait_for_connection(timeout=timeout)
|
| 233 |
+
|
| 234 |
+
try:
|
| 235 |
+
# Send the request on the assigned connection.
|
| 236 |
+
response = await connection.handle_async_request(
|
| 237 |
+
pool_request.request
|
| 238 |
+
)
|
| 239 |
+
except ConnectionNotAvailable:
|
| 240 |
+
# In some cases a connection may initially be available to
|
| 241 |
+
# handle a request, but then become unavailable.
|
| 242 |
+
#
|
| 243 |
+
# In this case we clear the connection and try again.
|
| 244 |
+
pool_request.clear_connection()
|
| 245 |
+
else:
|
| 246 |
+
break # pragma: nocover
|
| 247 |
+
|
| 248 |
+
except BaseException as exc:
|
| 249 |
+
with self._optional_thread_lock:
|
| 250 |
+
# For any exception or cancellation we remove the request from
|
| 251 |
+
# the queue, and then re-assign requests to connections.
|
| 252 |
+
self._requests.remove(pool_request)
|
| 253 |
+
closing = self._assign_requests_to_connections()
|
| 254 |
+
|
| 255 |
+
await self._close_connections(closing)
|
| 256 |
+
raise exc from None
|
| 257 |
+
|
| 258 |
+
# Return the response. Note that in this case we still have to manage
|
| 259 |
+
# the point at which the response is closed.
|
| 260 |
+
assert isinstance(response.stream, typing.AsyncIterable)
|
| 261 |
+
return Response(
|
| 262 |
+
status=response.status,
|
| 263 |
+
headers=response.headers,
|
| 264 |
+
content=PoolByteStream(
|
| 265 |
+
stream=response.stream, pool_request=pool_request, pool=self
|
| 266 |
+
),
|
| 267 |
+
extensions=response.extensions,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
def _assign_requests_to_connections(self) -> list[AsyncConnectionInterface]:
|
| 271 |
+
"""
|
| 272 |
+
Manage the state of the connection pool, assigning incoming
|
| 273 |
+
requests to connections as available.
|
| 274 |
+
|
| 275 |
+
Called whenever a new request is added or removed from the pool.
|
| 276 |
+
|
| 277 |
+
Any closing connections are returned, allowing the I/O for closing
|
| 278 |
+
those connections to be handled seperately.
|
| 279 |
+
"""
|
| 280 |
+
closing_connections = []
|
| 281 |
+
|
| 282 |
+
# First we handle cleaning up any connections that are closed,
|
| 283 |
+
# have expired their keep-alive, or surplus idle connections.
|
| 284 |
+
for connection in list(self._connections):
|
| 285 |
+
if connection.is_closed():
|
| 286 |
+
# log: "removing closed connection"
|
| 287 |
+
self._connections.remove(connection)
|
| 288 |
+
elif connection.has_expired():
|
| 289 |
+
# log: "closing expired connection"
|
| 290 |
+
self._connections.remove(connection)
|
| 291 |
+
closing_connections.append(connection)
|
| 292 |
+
elif (
|
| 293 |
+
connection.is_idle()
|
| 294 |
+
and len([connection.is_idle() for connection in self._connections])
|
| 295 |
+
> self._max_keepalive_connections
|
| 296 |
+
):
|
| 297 |
+
# log: "closing idle connection"
|
| 298 |
+
self._connections.remove(connection)
|
| 299 |
+
closing_connections.append(connection)
|
| 300 |
+
|
| 301 |
+
# Assign queued requests to connections.
|
| 302 |
+
queued_requests = [request for request in self._requests if request.is_queued()]
|
| 303 |
+
for pool_request in queued_requests:
|
| 304 |
+
origin = pool_request.request.url.origin
|
| 305 |
+
available_connections = [
|
| 306 |
+
connection
|
| 307 |
+
for connection in self._connections
|
| 308 |
+
if connection.can_handle_request(origin) and connection.is_available()
|
| 309 |
+
]
|
| 310 |
+
idle_connections = [
|
| 311 |
+
connection for connection in self._connections if connection.is_idle()
|
| 312 |
+
]
|
| 313 |
+
|
| 314 |
+
# There are three cases for how we may be able to handle the request:
|
| 315 |
+
#
|
| 316 |
+
# 1. There is an existing connection that can handle the request.
|
| 317 |
+
# 2. We can create a new connection to handle the request.
|
| 318 |
+
# 3. We can close an idle connection and then create a new connection
|
| 319 |
+
# to handle the request.
|
| 320 |
+
if available_connections:
|
| 321 |
+
# log: "reusing existing connection"
|
| 322 |
+
connection = available_connections[0]
|
| 323 |
+
pool_request.assign_to_connection(connection)
|
| 324 |
+
elif len(self._connections) < self._max_connections:
|
| 325 |
+
# log: "creating new connection"
|
| 326 |
+
connection = self.create_connection(origin)
|
| 327 |
+
self._connections.append(connection)
|
| 328 |
+
pool_request.assign_to_connection(connection)
|
| 329 |
+
elif idle_connections:
|
| 330 |
+
# log: "closing idle connection"
|
| 331 |
+
connection = idle_connections[0]
|
| 332 |
+
self._connections.remove(connection)
|
| 333 |
+
closing_connections.append(connection)
|
| 334 |
+
# log: "creating new connection"
|
| 335 |
+
connection = self.create_connection(origin)
|
| 336 |
+
self._connections.append(connection)
|
| 337 |
+
pool_request.assign_to_connection(connection)
|
| 338 |
+
|
| 339 |
+
return closing_connections
|
| 340 |
+
|
| 341 |
+
async def _close_connections(self, closing: list[AsyncConnectionInterface]) -> None:
|
| 342 |
+
# Close connections which have been removed from the pool.
|
| 343 |
+
with AsyncShieldCancellation():
|
| 344 |
+
for connection in closing:
|
| 345 |
+
await connection.aclose()
|
| 346 |
+
|
| 347 |
+
async def aclose(self) -> None:
|
| 348 |
+
# Explicitly close the connection pool.
|
| 349 |
+
# Clears all existing requests and connections.
|
| 350 |
+
with self._optional_thread_lock:
|
| 351 |
+
closing_connections = list(self._connections)
|
| 352 |
+
self._connections = []
|
| 353 |
+
await self._close_connections(closing_connections)
|
| 354 |
+
|
| 355 |
+
async def __aenter__(self) -> AsyncConnectionPool:
|
| 356 |
+
return self
|
| 357 |
+
|
| 358 |
+
async def __aexit__(
|
| 359 |
+
self,
|
| 360 |
+
exc_type: type[BaseException] | None = None,
|
| 361 |
+
exc_value: BaseException | None = None,
|
| 362 |
+
traceback: types.TracebackType | None = None,
|
| 363 |
+
) -> None:
|
| 364 |
+
await self.aclose()
|
| 365 |
+
|
| 366 |
+
def __repr__(self) -> str:
|
| 367 |
+
class_name = self.__class__.__name__
|
| 368 |
+
with self._optional_thread_lock:
|
| 369 |
+
request_is_queued = [request.is_queued() for request in self._requests]
|
| 370 |
+
connection_is_idle = [
|
| 371 |
+
connection.is_idle() for connection in self._connections
|
| 372 |
+
]
|
| 373 |
+
|
| 374 |
+
num_active_requests = request_is_queued.count(False)
|
| 375 |
+
num_queued_requests = request_is_queued.count(True)
|
| 376 |
+
num_active_connections = connection_is_idle.count(False)
|
| 377 |
+
num_idle_connections = connection_is_idle.count(True)
|
| 378 |
+
|
| 379 |
+
requests_info = (
|
| 380 |
+
f"Requests: {num_active_requests} active, {num_queued_requests} queued"
|
| 381 |
+
)
|
| 382 |
+
connection_info = (
|
| 383 |
+
f"Connections: {num_active_connections} active, {num_idle_connections} idle"
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
return f"<{class_name} [{requests_info} | {connection_info}]>"
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class PoolByteStream:
|
| 390 |
+
def __init__(
|
| 391 |
+
self,
|
| 392 |
+
stream: typing.AsyncIterable[bytes],
|
| 393 |
+
pool_request: AsyncPoolRequest,
|
| 394 |
+
pool: AsyncConnectionPool,
|
| 395 |
+
) -> None:
|
| 396 |
+
self._stream = stream
|
| 397 |
+
self._pool_request = pool_request
|
| 398 |
+
self._pool = pool
|
| 399 |
+
self._closed = False
|
| 400 |
+
|
| 401 |
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
| 402 |
+
try:
|
| 403 |
+
async for part in self._stream:
|
| 404 |
+
yield part
|
| 405 |
+
except BaseException as exc:
|
| 406 |
+
await self.aclose()
|
| 407 |
+
raise exc from None
|
| 408 |
+
|
| 409 |
+
async def aclose(self) -> None:
|
| 410 |
+
if not self._closed:
|
| 411 |
+
self._closed = True
|
| 412 |
+
with AsyncShieldCancellation():
|
| 413 |
+
if hasattr(self._stream, "aclose"):
|
| 414 |
+
await self._stream.aclose()
|
| 415 |
+
|
| 416 |
+
with self._pool._optional_thread_lock:
|
| 417 |
+
self._pool._requests.remove(self._pool_request)
|
| 418 |
+
closing = self._pool._assign_requests_to_connections()
|
| 419 |
+
|
| 420 |
+
await self._pool._close_connections(closing)
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/http11.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import enum
|
| 4 |
+
import logging
|
| 5 |
+
import ssl
|
| 6 |
+
import time
|
| 7 |
+
import types
|
| 8 |
+
import typing
|
| 9 |
+
|
| 10 |
+
import h11
|
| 11 |
+
|
| 12 |
+
from .._backends.base import AsyncNetworkStream
|
| 13 |
+
from .._exceptions import (
|
| 14 |
+
ConnectionNotAvailable,
|
| 15 |
+
LocalProtocolError,
|
| 16 |
+
RemoteProtocolError,
|
| 17 |
+
WriteError,
|
| 18 |
+
map_exceptions,
|
| 19 |
+
)
|
| 20 |
+
from .._models import Origin, Request, Response
|
| 21 |
+
from .._synchronization import AsyncLock, AsyncShieldCancellation
|
| 22 |
+
from .._trace import Trace
|
| 23 |
+
from .interfaces import AsyncConnectionInterface
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger("httpcore.http11")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# A subset of `h11.Event` types supported by `_send_event`
|
| 29 |
+
H11SendEvent = typing.Union[
|
| 30 |
+
h11.Request,
|
| 31 |
+
h11.Data,
|
| 32 |
+
h11.EndOfMessage,
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class HTTPConnectionState(enum.IntEnum):
|
| 37 |
+
NEW = 0
|
| 38 |
+
ACTIVE = 1
|
| 39 |
+
IDLE = 2
|
| 40 |
+
CLOSED = 3
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class AsyncHTTP11Connection(AsyncConnectionInterface):
|
| 44 |
+
READ_NUM_BYTES = 64 * 1024
|
| 45 |
+
MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
origin: Origin,
|
| 50 |
+
stream: AsyncNetworkStream,
|
| 51 |
+
keepalive_expiry: float | None = None,
|
| 52 |
+
) -> None:
|
| 53 |
+
self._origin = origin
|
| 54 |
+
self._network_stream = stream
|
| 55 |
+
self._keepalive_expiry: float | None = keepalive_expiry
|
| 56 |
+
self._expire_at: float | None = None
|
| 57 |
+
self._state = HTTPConnectionState.NEW
|
| 58 |
+
self._state_lock = AsyncLock()
|
| 59 |
+
self._request_count = 0
|
| 60 |
+
self._h11_state = h11.Connection(
|
| 61 |
+
our_role=h11.CLIENT,
|
| 62 |
+
max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 66 |
+
if not self.can_handle_request(request.url.origin):
|
| 67 |
+
raise RuntimeError(
|
| 68 |
+
f"Attempted to send request to {request.url.origin} on connection "
|
| 69 |
+
f"to {self._origin}"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
async with self._state_lock:
|
| 73 |
+
if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE):
|
| 74 |
+
self._request_count += 1
|
| 75 |
+
self._state = HTTPConnectionState.ACTIVE
|
| 76 |
+
self._expire_at = None
|
| 77 |
+
else:
|
| 78 |
+
raise ConnectionNotAvailable()
|
| 79 |
+
|
| 80 |
+
try:
|
| 81 |
+
kwargs = {"request": request}
|
| 82 |
+
try:
|
| 83 |
+
async with Trace(
|
| 84 |
+
"send_request_headers", logger, request, kwargs
|
| 85 |
+
) as trace:
|
| 86 |
+
await self._send_request_headers(**kwargs)
|
| 87 |
+
async with Trace("send_request_body", logger, request, kwargs) as trace:
|
| 88 |
+
await self._send_request_body(**kwargs)
|
| 89 |
+
except WriteError:
|
| 90 |
+
# If we get a write error while we're writing the request,
|
| 91 |
+
# then we supress this error and move on to attempting to
|
| 92 |
+
# read the response. Servers can sometimes close the request
|
| 93 |
+
# pre-emptively and then respond with a well formed HTTP
|
| 94 |
+
# error response.
|
| 95 |
+
pass
|
| 96 |
+
|
| 97 |
+
async with Trace(
|
| 98 |
+
"receive_response_headers", logger, request, kwargs
|
| 99 |
+
) as trace:
|
| 100 |
+
(
|
| 101 |
+
http_version,
|
| 102 |
+
status,
|
| 103 |
+
reason_phrase,
|
| 104 |
+
headers,
|
| 105 |
+
trailing_data,
|
| 106 |
+
) = await self._receive_response_headers(**kwargs)
|
| 107 |
+
trace.return_value = (
|
| 108 |
+
http_version,
|
| 109 |
+
status,
|
| 110 |
+
reason_phrase,
|
| 111 |
+
headers,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
network_stream = self._network_stream
|
| 115 |
+
|
| 116 |
+
# CONNECT or Upgrade request
|
| 117 |
+
if (status == 101) or (
|
| 118 |
+
(request.method == b"CONNECT") and (200 <= status < 300)
|
| 119 |
+
):
|
| 120 |
+
network_stream = AsyncHTTP11UpgradeStream(network_stream, trailing_data)
|
| 121 |
+
|
| 122 |
+
return Response(
|
| 123 |
+
status=status,
|
| 124 |
+
headers=headers,
|
| 125 |
+
content=HTTP11ConnectionByteStream(self, request),
|
| 126 |
+
extensions={
|
| 127 |
+
"http_version": http_version,
|
| 128 |
+
"reason_phrase": reason_phrase,
|
| 129 |
+
"network_stream": network_stream,
|
| 130 |
+
},
|
| 131 |
+
)
|
| 132 |
+
except BaseException as exc:
|
| 133 |
+
with AsyncShieldCancellation():
|
| 134 |
+
async with Trace("response_closed", logger, request) as trace:
|
| 135 |
+
await self._response_closed()
|
| 136 |
+
raise exc
|
| 137 |
+
|
| 138 |
+
# Sending the request...
|
| 139 |
+
|
| 140 |
+
async def _send_request_headers(self, request: Request) -> None:
|
| 141 |
+
timeouts = request.extensions.get("timeout", {})
|
| 142 |
+
timeout = timeouts.get("write", None)
|
| 143 |
+
|
| 144 |
+
with map_exceptions({h11.LocalProtocolError: LocalProtocolError}):
|
| 145 |
+
event = h11.Request(
|
| 146 |
+
method=request.method,
|
| 147 |
+
target=request.url.target,
|
| 148 |
+
headers=request.headers,
|
| 149 |
+
)
|
| 150 |
+
await self._send_event(event, timeout=timeout)
|
| 151 |
+
|
| 152 |
+
async def _send_request_body(self, request: Request) -> None:
|
| 153 |
+
timeouts = request.extensions.get("timeout", {})
|
| 154 |
+
timeout = timeouts.get("write", None)
|
| 155 |
+
|
| 156 |
+
assert isinstance(request.stream, typing.AsyncIterable)
|
| 157 |
+
async for chunk in request.stream:
|
| 158 |
+
event = h11.Data(data=chunk)
|
| 159 |
+
await self._send_event(event, timeout=timeout)
|
| 160 |
+
|
| 161 |
+
await self._send_event(h11.EndOfMessage(), timeout=timeout)
|
| 162 |
+
|
| 163 |
+
async def _send_event(self, event: h11.Event, timeout: float | None = None) -> None:
|
| 164 |
+
bytes_to_send = self._h11_state.send(event)
|
| 165 |
+
if bytes_to_send is not None:
|
| 166 |
+
await self._network_stream.write(bytes_to_send, timeout=timeout)
|
| 167 |
+
|
| 168 |
+
# Receiving the response...
|
| 169 |
+
|
| 170 |
+
async def _receive_response_headers(
|
| 171 |
+
self, request: Request
|
| 172 |
+
) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]:
|
| 173 |
+
timeouts = request.extensions.get("timeout", {})
|
| 174 |
+
timeout = timeouts.get("read", None)
|
| 175 |
+
|
| 176 |
+
while True:
|
| 177 |
+
event = await self._receive_event(timeout=timeout)
|
| 178 |
+
if isinstance(event, h11.Response):
|
| 179 |
+
break
|
| 180 |
+
if (
|
| 181 |
+
isinstance(event, h11.InformationalResponse)
|
| 182 |
+
and event.status_code == 101
|
| 183 |
+
):
|
| 184 |
+
break
|
| 185 |
+
|
| 186 |
+
http_version = b"HTTP/" + event.http_version
|
| 187 |
+
|
| 188 |
+
# h11 version 0.11+ supports a `raw_items` interface to get the
|
| 189 |
+
# raw header casing, rather than the enforced lowercase headers.
|
| 190 |
+
headers = event.headers.raw_items()
|
| 191 |
+
|
| 192 |
+
trailing_data, _ = self._h11_state.trailing_data
|
| 193 |
+
|
| 194 |
+
return http_version, event.status_code, event.reason, headers, trailing_data
|
| 195 |
+
|
| 196 |
+
async def _receive_response_body(
|
| 197 |
+
self, request: Request
|
| 198 |
+
) -> typing.AsyncIterator[bytes]:
|
| 199 |
+
timeouts = request.extensions.get("timeout", {})
|
| 200 |
+
timeout = timeouts.get("read", None)
|
| 201 |
+
|
| 202 |
+
while True:
|
| 203 |
+
event = await self._receive_event(timeout=timeout)
|
| 204 |
+
if isinstance(event, h11.Data):
|
| 205 |
+
yield bytes(event.data)
|
| 206 |
+
elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)):
|
| 207 |
+
break
|
| 208 |
+
|
| 209 |
+
async def _receive_event(
|
| 210 |
+
self, timeout: float | None = None
|
| 211 |
+
) -> h11.Event | type[h11.PAUSED]:
|
| 212 |
+
while True:
|
| 213 |
+
with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}):
|
| 214 |
+
event = self._h11_state.next_event()
|
| 215 |
+
|
| 216 |
+
if event is h11.NEED_DATA:
|
| 217 |
+
data = await self._network_stream.read(
|
| 218 |
+
self.READ_NUM_BYTES, timeout=timeout
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
# If we feed this case through h11 we'll raise an exception like:
|
| 222 |
+
#
|
| 223 |
+
# httpcore.RemoteProtocolError: can't handle event type
|
| 224 |
+
# ConnectionClosed when role=SERVER and state=SEND_RESPONSE
|
| 225 |
+
#
|
| 226 |
+
# Which is accurate, but not very informative from an end-user
|
| 227 |
+
# perspective. Instead we handle this case distinctly and treat
|
| 228 |
+
# it as a ConnectError.
|
| 229 |
+
if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE:
|
| 230 |
+
msg = "Server disconnected without sending a response."
|
| 231 |
+
raise RemoteProtocolError(msg)
|
| 232 |
+
|
| 233 |
+
self._h11_state.receive_data(data)
|
| 234 |
+
else:
|
| 235 |
+
# mypy fails to narrow the type in the above if statement above
|
| 236 |
+
return event # type: ignore[return-value]
|
| 237 |
+
|
| 238 |
+
async def _response_closed(self) -> None:
|
| 239 |
+
async with self._state_lock:
|
| 240 |
+
if (
|
| 241 |
+
self._h11_state.our_state is h11.DONE
|
| 242 |
+
and self._h11_state.their_state is h11.DONE
|
| 243 |
+
):
|
| 244 |
+
self._state = HTTPConnectionState.IDLE
|
| 245 |
+
self._h11_state.start_next_cycle()
|
| 246 |
+
if self._keepalive_expiry is not None:
|
| 247 |
+
now = time.monotonic()
|
| 248 |
+
self._expire_at = now + self._keepalive_expiry
|
| 249 |
+
else:
|
| 250 |
+
await self.aclose()
|
| 251 |
+
|
| 252 |
+
# Once the connection is no longer required...
|
| 253 |
+
|
| 254 |
+
async def aclose(self) -> None:
|
| 255 |
+
# Note that this method unilaterally closes the connection, and does
|
| 256 |
+
# not have any kind of locking in place around it.
|
| 257 |
+
self._state = HTTPConnectionState.CLOSED
|
| 258 |
+
await self._network_stream.aclose()
|
| 259 |
+
|
| 260 |
+
# The AsyncConnectionInterface methods provide information about the state of
|
| 261 |
+
# the connection, allowing for a connection pooling implementation to
|
| 262 |
+
# determine when to reuse and when to close the connection...
|
| 263 |
+
|
| 264 |
+
def can_handle_request(self, origin: Origin) -> bool:
|
| 265 |
+
return origin == self._origin
|
| 266 |
+
|
| 267 |
+
def is_available(self) -> bool:
|
| 268 |
+
# Note that HTTP/1.1 connections in the "NEW" state are not treated as
|
| 269 |
+
# being "available". The control flow which created the connection will
|
| 270 |
+
# be able to send an outgoing request, but the connection will not be
|
| 271 |
+
# acquired from the connection pool for any other request.
|
| 272 |
+
return self._state == HTTPConnectionState.IDLE
|
| 273 |
+
|
| 274 |
+
def has_expired(self) -> bool:
|
| 275 |
+
now = time.monotonic()
|
| 276 |
+
keepalive_expired = self._expire_at is not None and now > self._expire_at
|
| 277 |
+
|
| 278 |
+
# If the HTTP connection is idle but the socket is readable, then the
|
| 279 |
+
# only valid state is that the socket is about to return b"", indicating
|
| 280 |
+
# a server-initiated disconnect.
|
| 281 |
+
server_disconnected = (
|
| 282 |
+
self._state == HTTPConnectionState.IDLE
|
| 283 |
+
and self._network_stream.get_extra_info("is_readable")
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
return keepalive_expired or server_disconnected
|
| 287 |
+
|
| 288 |
+
def is_idle(self) -> bool:
|
| 289 |
+
return self._state == HTTPConnectionState.IDLE
|
| 290 |
+
|
| 291 |
+
def is_closed(self) -> bool:
|
| 292 |
+
return self._state == HTTPConnectionState.CLOSED
|
| 293 |
+
|
| 294 |
+
def info(self) -> str:
|
| 295 |
+
origin = str(self._origin)
|
| 296 |
+
return (
|
| 297 |
+
f"{origin!r}, HTTP/1.1, {self._state.name}, "
|
| 298 |
+
f"Request Count: {self._request_count}"
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
def __repr__(self) -> str:
|
| 302 |
+
class_name = self.__class__.__name__
|
| 303 |
+
origin = str(self._origin)
|
| 304 |
+
return (
|
| 305 |
+
f"<{class_name} [{origin!r}, {self._state.name}, "
|
| 306 |
+
f"Request Count: {self._request_count}]>"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
# These context managers are not used in the standard flow, but are
|
| 310 |
+
# useful for testing or working with connection instances directly.
|
| 311 |
+
|
| 312 |
+
async def __aenter__(self) -> AsyncHTTP11Connection:
|
| 313 |
+
return self
|
| 314 |
+
|
| 315 |
+
async def __aexit__(
|
| 316 |
+
self,
|
| 317 |
+
exc_type: type[BaseException] | None = None,
|
| 318 |
+
exc_value: BaseException | None = None,
|
| 319 |
+
traceback: types.TracebackType | None = None,
|
| 320 |
+
) -> None:
|
| 321 |
+
await self.aclose()
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class HTTP11ConnectionByteStream:
|
| 325 |
+
def __init__(self, connection: AsyncHTTP11Connection, request: Request) -> None:
|
| 326 |
+
self._connection = connection
|
| 327 |
+
self._request = request
|
| 328 |
+
self._closed = False
|
| 329 |
+
|
| 330 |
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
| 331 |
+
kwargs = {"request": self._request}
|
| 332 |
+
try:
|
| 333 |
+
async with Trace("receive_response_body", logger, self._request, kwargs):
|
| 334 |
+
async for chunk in self._connection._receive_response_body(**kwargs):
|
| 335 |
+
yield chunk
|
| 336 |
+
except BaseException as exc:
|
| 337 |
+
# If we get an exception while streaming the response,
|
| 338 |
+
# we want to close the response (and possibly the connection)
|
| 339 |
+
# before raising that exception.
|
| 340 |
+
with AsyncShieldCancellation():
|
| 341 |
+
await self.aclose()
|
| 342 |
+
raise exc
|
| 343 |
+
|
| 344 |
+
async def aclose(self) -> None:
|
| 345 |
+
if not self._closed:
|
| 346 |
+
self._closed = True
|
| 347 |
+
async with Trace("response_closed", logger, self._request):
|
| 348 |
+
await self._connection._response_closed()
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class AsyncHTTP11UpgradeStream(AsyncNetworkStream):
|
| 352 |
+
def __init__(self, stream: AsyncNetworkStream, leading_data: bytes) -> None:
|
| 353 |
+
self._stream = stream
|
| 354 |
+
self._leading_data = leading_data
|
| 355 |
+
|
| 356 |
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 357 |
+
if self._leading_data:
|
| 358 |
+
buffer = self._leading_data[:max_bytes]
|
| 359 |
+
self._leading_data = self._leading_data[max_bytes:]
|
| 360 |
+
return buffer
|
| 361 |
+
else:
|
| 362 |
+
return await self._stream.read(max_bytes, timeout)
|
| 363 |
+
|
| 364 |
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 365 |
+
await self._stream.write(buffer, timeout)
|
| 366 |
+
|
| 367 |
+
async def aclose(self) -> None:
|
| 368 |
+
await self._stream.aclose()
|
| 369 |
+
|
| 370 |
+
async def start_tls(
|
| 371 |
+
self,
|
| 372 |
+
ssl_context: ssl.SSLContext,
|
| 373 |
+
server_hostname: str | None = None,
|
| 374 |
+
timeout: float | None = None,
|
| 375 |
+
) -> AsyncNetworkStream:
|
| 376 |
+
return await self._stream.start_tls(ssl_context, server_hostname, timeout)
|
| 377 |
+
|
| 378 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 379 |
+
return self._stream.get_extra_info(info)
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/http2.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import enum
|
| 4 |
+
import logging
|
| 5 |
+
import time
|
| 6 |
+
import types
|
| 7 |
+
import typing
|
| 8 |
+
|
| 9 |
+
import h2.config
|
| 10 |
+
import h2.connection
|
| 11 |
+
import h2.events
|
| 12 |
+
import h2.exceptions
|
| 13 |
+
import h2.settings
|
| 14 |
+
|
| 15 |
+
from .._backends.base import AsyncNetworkStream
|
| 16 |
+
from .._exceptions import (
|
| 17 |
+
ConnectionNotAvailable,
|
| 18 |
+
LocalProtocolError,
|
| 19 |
+
RemoteProtocolError,
|
| 20 |
+
)
|
| 21 |
+
from .._models import Origin, Request, Response
|
| 22 |
+
from .._synchronization import AsyncLock, AsyncSemaphore, AsyncShieldCancellation
|
| 23 |
+
from .._trace import Trace
|
| 24 |
+
from .interfaces import AsyncConnectionInterface
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger("httpcore.http2")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def has_body_headers(request: Request) -> bool:
|
| 30 |
+
return any(
|
| 31 |
+
k.lower() == b"content-length" or k.lower() == b"transfer-encoding"
|
| 32 |
+
for k, v in request.headers
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class HTTPConnectionState(enum.IntEnum):
|
| 37 |
+
ACTIVE = 1
|
| 38 |
+
IDLE = 2
|
| 39 |
+
CLOSED = 3
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class AsyncHTTP2Connection(AsyncConnectionInterface):
|
| 43 |
+
READ_NUM_BYTES = 64 * 1024
|
| 44 |
+
CONFIG = h2.config.H2Configuration(validate_inbound_headers=False)
|
| 45 |
+
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
origin: Origin,
|
| 49 |
+
stream: AsyncNetworkStream,
|
| 50 |
+
keepalive_expiry: float | None = None,
|
| 51 |
+
):
|
| 52 |
+
self._origin = origin
|
| 53 |
+
self._network_stream = stream
|
| 54 |
+
self._keepalive_expiry: float | None = keepalive_expiry
|
| 55 |
+
self._h2_state = h2.connection.H2Connection(config=self.CONFIG)
|
| 56 |
+
self._state = HTTPConnectionState.IDLE
|
| 57 |
+
self._expire_at: float | None = None
|
| 58 |
+
self._request_count = 0
|
| 59 |
+
self._init_lock = AsyncLock()
|
| 60 |
+
self._state_lock = AsyncLock()
|
| 61 |
+
self._read_lock = AsyncLock()
|
| 62 |
+
self._write_lock = AsyncLock()
|
| 63 |
+
self._sent_connection_init = False
|
| 64 |
+
self._used_all_stream_ids = False
|
| 65 |
+
self._connection_error = False
|
| 66 |
+
|
| 67 |
+
# Mapping from stream ID to response stream events.
|
| 68 |
+
self._events: dict[
|
| 69 |
+
int,
|
| 70 |
+
list[
|
| 71 |
+
h2.events.ResponseReceived
|
| 72 |
+
| h2.events.DataReceived
|
| 73 |
+
| h2.events.StreamEnded
|
| 74 |
+
| h2.events.StreamReset,
|
| 75 |
+
],
|
| 76 |
+
] = {}
|
| 77 |
+
|
| 78 |
+
# Connection terminated events are stored as state since
|
| 79 |
+
# we need to handle them for all streams.
|
| 80 |
+
self._connection_terminated: h2.events.ConnectionTerminated | None = None
|
| 81 |
+
|
| 82 |
+
self._read_exception: Exception | None = None
|
| 83 |
+
self._write_exception: Exception | None = None
|
| 84 |
+
|
| 85 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 86 |
+
if not self.can_handle_request(request.url.origin):
|
| 87 |
+
# This cannot occur in normal operation, since the connection pool
|
| 88 |
+
# will only send requests on connections that handle them.
|
| 89 |
+
# It's in place simply for resilience as a guard against incorrect
|
| 90 |
+
# usage, for anyone working directly with httpcore connections.
|
| 91 |
+
raise RuntimeError(
|
| 92 |
+
f"Attempted to send request to {request.url.origin} on connection "
|
| 93 |
+
f"to {self._origin}"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
async with self._state_lock:
|
| 97 |
+
if self._state in (HTTPConnectionState.ACTIVE, HTTPConnectionState.IDLE):
|
| 98 |
+
self._request_count += 1
|
| 99 |
+
self._expire_at = None
|
| 100 |
+
self._state = HTTPConnectionState.ACTIVE
|
| 101 |
+
else:
|
| 102 |
+
raise ConnectionNotAvailable()
|
| 103 |
+
|
| 104 |
+
async with self._init_lock:
|
| 105 |
+
if not self._sent_connection_init:
|
| 106 |
+
try:
|
| 107 |
+
sci_kwargs = {"request": request}
|
| 108 |
+
async with Trace(
|
| 109 |
+
"send_connection_init", logger, request, sci_kwargs
|
| 110 |
+
):
|
| 111 |
+
await self._send_connection_init(**sci_kwargs)
|
| 112 |
+
except BaseException as exc:
|
| 113 |
+
with AsyncShieldCancellation():
|
| 114 |
+
await self.aclose()
|
| 115 |
+
raise exc
|
| 116 |
+
|
| 117 |
+
self._sent_connection_init = True
|
| 118 |
+
|
| 119 |
+
# Initially start with just 1 until the remote server provides
|
| 120 |
+
# its max_concurrent_streams value
|
| 121 |
+
self._max_streams = 1
|
| 122 |
+
|
| 123 |
+
local_settings_max_streams = (
|
| 124 |
+
self._h2_state.local_settings.max_concurrent_streams
|
| 125 |
+
)
|
| 126 |
+
self._max_streams_semaphore = AsyncSemaphore(local_settings_max_streams)
|
| 127 |
+
|
| 128 |
+
for _ in range(local_settings_max_streams - self._max_streams):
|
| 129 |
+
await self._max_streams_semaphore.acquire()
|
| 130 |
+
|
| 131 |
+
await self._max_streams_semaphore.acquire()
|
| 132 |
+
|
| 133 |
+
try:
|
| 134 |
+
stream_id = self._h2_state.get_next_available_stream_id()
|
| 135 |
+
self._events[stream_id] = []
|
| 136 |
+
except h2.exceptions.NoAvailableStreamIDError: # pragma: nocover
|
| 137 |
+
self._used_all_stream_ids = True
|
| 138 |
+
self._request_count -= 1
|
| 139 |
+
raise ConnectionNotAvailable()
|
| 140 |
+
|
| 141 |
+
try:
|
| 142 |
+
kwargs = {"request": request, "stream_id": stream_id}
|
| 143 |
+
async with Trace("send_request_headers", logger, request, kwargs):
|
| 144 |
+
await self._send_request_headers(request=request, stream_id=stream_id)
|
| 145 |
+
async with Trace("send_request_body", logger, request, kwargs):
|
| 146 |
+
await self._send_request_body(request=request, stream_id=stream_id)
|
| 147 |
+
async with Trace(
|
| 148 |
+
"receive_response_headers", logger, request, kwargs
|
| 149 |
+
) as trace:
|
| 150 |
+
status, headers = await self._receive_response(
|
| 151 |
+
request=request, stream_id=stream_id
|
| 152 |
+
)
|
| 153 |
+
trace.return_value = (status, headers)
|
| 154 |
+
|
| 155 |
+
return Response(
|
| 156 |
+
status=status,
|
| 157 |
+
headers=headers,
|
| 158 |
+
content=HTTP2ConnectionByteStream(self, request, stream_id=stream_id),
|
| 159 |
+
extensions={
|
| 160 |
+
"http_version": b"HTTP/2",
|
| 161 |
+
"network_stream": self._network_stream,
|
| 162 |
+
"stream_id": stream_id,
|
| 163 |
+
},
|
| 164 |
+
)
|
| 165 |
+
except BaseException as exc: # noqa: PIE786
|
| 166 |
+
with AsyncShieldCancellation():
|
| 167 |
+
kwargs = {"stream_id": stream_id}
|
| 168 |
+
async with Trace("response_closed", logger, request, kwargs):
|
| 169 |
+
await self._response_closed(stream_id=stream_id)
|
| 170 |
+
|
| 171 |
+
if isinstance(exc, h2.exceptions.ProtocolError):
|
| 172 |
+
# One case where h2 can raise a protocol error is when a
|
| 173 |
+
# closed frame has been seen by the state machine.
|
| 174 |
+
#
|
| 175 |
+
# This happens when one stream is reading, and encounters
|
| 176 |
+
# a GOAWAY event. Other flows of control may then raise
|
| 177 |
+
# a protocol error at any point they interact with the 'h2_state'.
|
| 178 |
+
#
|
| 179 |
+
# In this case we'll have stored the event, and should raise
|
| 180 |
+
# it as a RemoteProtocolError.
|
| 181 |
+
if self._connection_terminated: # pragma: nocover
|
| 182 |
+
raise RemoteProtocolError(self._connection_terminated)
|
| 183 |
+
# If h2 raises a protocol error in some other state then we
|
| 184 |
+
# must somehow have made a protocol violation.
|
| 185 |
+
raise LocalProtocolError(exc) # pragma: nocover
|
| 186 |
+
|
| 187 |
+
raise exc
|
| 188 |
+
|
| 189 |
+
async def _send_connection_init(self, request: Request) -> None:
|
| 190 |
+
"""
|
| 191 |
+
The HTTP/2 connection requires some initial setup before we can start
|
| 192 |
+
using individual request/response streams on it.
|
| 193 |
+
"""
|
| 194 |
+
# Need to set these manually here instead of manipulating via
|
| 195 |
+
# __setitem__() otherwise the H2Connection will emit SettingsUpdate
|
| 196 |
+
# frames in addition to sending the undesired defaults.
|
| 197 |
+
self._h2_state.local_settings = h2.settings.Settings(
|
| 198 |
+
client=True,
|
| 199 |
+
initial_values={
|
| 200 |
+
# Disable PUSH_PROMISE frames from the server since we don't do anything
|
| 201 |
+
# with them for now. Maybe when we support caching?
|
| 202 |
+
h2.settings.SettingCodes.ENABLE_PUSH: 0,
|
| 203 |
+
# These two are taken from h2 for safe defaults
|
| 204 |
+
h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100,
|
| 205 |
+
h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536,
|
| 206 |
+
},
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# Some websites (*cough* Yahoo *cough*) balk at this setting being
|
| 210 |
+
# present in the initial handshake since it's not defined in the original
|
| 211 |
+
# RFC despite the RFC mandating ignoring settings you don't know about.
|
| 212 |
+
del self._h2_state.local_settings[
|
| 213 |
+
h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL
|
| 214 |
+
]
|
| 215 |
+
|
| 216 |
+
self._h2_state.initiate_connection()
|
| 217 |
+
self._h2_state.increment_flow_control_window(2**24)
|
| 218 |
+
await self._write_outgoing_data(request)
|
| 219 |
+
|
| 220 |
+
# Sending the request...
|
| 221 |
+
|
| 222 |
+
async def _send_request_headers(self, request: Request, stream_id: int) -> None:
|
| 223 |
+
"""
|
| 224 |
+
Send the request headers to a given stream ID.
|
| 225 |
+
"""
|
| 226 |
+
end_stream = not has_body_headers(request)
|
| 227 |
+
|
| 228 |
+
# In HTTP/2 the ':authority' pseudo-header is used instead of 'Host'.
|
| 229 |
+
# In order to gracefully handle HTTP/1.1 and HTTP/2 we always require
|
| 230 |
+
# HTTP/1.1 style headers, and map them appropriately if we end up on
|
| 231 |
+
# an HTTP/2 connection.
|
| 232 |
+
authority = [v for k, v in request.headers if k.lower() == b"host"][0]
|
| 233 |
+
|
| 234 |
+
headers = [
|
| 235 |
+
(b":method", request.method),
|
| 236 |
+
(b":authority", authority),
|
| 237 |
+
(b":scheme", request.url.scheme),
|
| 238 |
+
(b":path", request.url.target),
|
| 239 |
+
] + [
|
| 240 |
+
(k.lower(), v)
|
| 241 |
+
for k, v in request.headers
|
| 242 |
+
if k.lower()
|
| 243 |
+
not in (
|
| 244 |
+
b"host",
|
| 245 |
+
b"transfer-encoding",
|
| 246 |
+
)
|
| 247 |
+
]
|
| 248 |
+
|
| 249 |
+
self._h2_state.send_headers(stream_id, headers, end_stream=end_stream)
|
| 250 |
+
self._h2_state.increment_flow_control_window(2**24, stream_id=stream_id)
|
| 251 |
+
await self._write_outgoing_data(request)
|
| 252 |
+
|
| 253 |
+
async def _send_request_body(self, request: Request, stream_id: int) -> None:
|
| 254 |
+
"""
|
| 255 |
+
Iterate over the request body sending it to a given stream ID.
|
| 256 |
+
"""
|
| 257 |
+
if not has_body_headers(request):
|
| 258 |
+
return
|
| 259 |
+
|
| 260 |
+
assert isinstance(request.stream, typing.AsyncIterable)
|
| 261 |
+
async for data in request.stream:
|
| 262 |
+
await self._send_stream_data(request, stream_id, data)
|
| 263 |
+
await self._send_end_stream(request, stream_id)
|
| 264 |
+
|
| 265 |
+
async def _send_stream_data(
|
| 266 |
+
self, request: Request, stream_id: int, data: bytes
|
| 267 |
+
) -> None:
|
| 268 |
+
"""
|
| 269 |
+
Send a single chunk of data in one or more data frames.
|
| 270 |
+
"""
|
| 271 |
+
while data:
|
| 272 |
+
max_flow = await self._wait_for_outgoing_flow(request, stream_id)
|
| 273 |
+
chunk_size = min(len(data), max_flow)
|
| 274 |
+
chunk, data = data[:chunk_size], data[chunk_size:]
|
| 275 |
+
self._h2_state.send_data(stream_id, chunk)
|
| 276 |
+
await self._write_outgoing_data(request)
|
| 277 |
+
|
| 278 |
+
async def _send_end_stream(self, request: Request, stream_id: int) -> None:
|
| 279 |
+
"""
|
| 280 |
+
Send an empty data frame on on a given stream ID with the END_STREAM flag set.
|
| 281 |
+
"""
|
| 282 |
+
self._h2_state.end_stream(stream_id)
|
| 283 |
+
await self._write_outgoing_data(request)
|
| 284 |
+
|
| 285 |
+
# Receiving the response...
|
| 286 |
+
|
| 287 |
+
async def _receive_response(
|
| 288 |
+
self, request: Request, stream_id: int
|
| 289 |
+
) -> tuple[int, list[tuple[bytes, bytes]]]:
|
| 290 |
+
"""
|
| 291 |
+
Return the response status code and headers for a given stream ID.
|
| 292 |
+
"""
|
| 293 |
+
while True:
|
| 294 |
+
event = await self._receive_stream_event(request, stream_id)
|
| 295 |
+
if isinstance(event, h2.events.ResponseReceived):
|
| 296 |
+
break
|
| 297 |
+
|
| 298 |
+
status_code = 200
|
| 299 |
+
headers = []
|
| 300 |
+
assert event.headers is not None
|
| 301 |
+
for k, v in event.headers:
|
| 302 |
+
if k == b":status":
|
| 303 |
+
status_code = int(v.decode("ascii", errors="ignore"))
|
| 304 |
+
elif not k.startswith(b":"):
|
| 305 |
+
headers.append((k, v))
|
| 306 |
+
|
| 307 |
+
return (status_code, headers)
|
| 308 |
+
|
| 309 |
+
async def _receive_response_body(
|
| 310 |
+
self, request: Request, stream_id: int
|
| 311 |
+
) -> typing.AsyncIterator[bytes]:
|
| 312 |
+
"""
|
| 313 |
+
Iterator that returns the bytes of the response body for a given stream ID.
|
| 314 |
+
"""
|
| 315 |
+
while True:
|
| 316 |
+
event = await self._receive_stream_event(request, stream_id)
|
| 317 |
+
if isinstance(event, h2.events.DataReceived):
|
| 318 |
+
assert event.flow_controlled_length is not None
|
| 319 |
+
assert event.data is not None
|
| 320 |
+
amount = event.flow_controlled_length
|
| 321 |
+
self._h2_state.acknowledge_received_data(amount, stream_id)
|
| 322 |
+
await self._write_outgoing_data(request)
|
| 323 |
+
yield event.data
|
| 324 |
+
elif isinstance(event, h2.events.StreamEnded):
|
| 325 |
+
break
|
| 326 |
+
|
| 327 |
+
async def _receive_stream_event(
|
| 328 |
+
self, request: Request, stream_id: int
|
| 329 |
+
) -> h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded:
|
| 330 |
+
"""
|
| 331 |
+
Return the next available event for a given stream ID.
|
| 332 |
+
|
| 333 |
+
Will read more data from the network if required.
|
| 334 |
+
"""
|
| 335 |
+
while not self._events.get(stream_id):
|
| 336 |
+
await self._receive_events(request, stream_id)
|
| 337 |
+
event = self._events[stream_id].pop(0)
|
| 338 |
+
if isinstance(event, h2.events.StreamReset):
|
| 339 |
+
raise RemoteProtocolError(event)
|
| 340 |
+
return event
|
| 341 |
+
|
| 342 |
+
async def _receive_events(
|
| 343 |
+
self, request: Request, stream_id: int | None = None
|
| 344 |
+
) -> None:
|
| 345 |
+
"""
|
| 346 |
+
Read some data from the network until we see one or more events
|
| 347 |
+
for a given stream ID.
|
| 348 |
+
"""
|
| 349 |
+
async with self._read_lock:
|
| 350 |
+
if self._connection_terminated is not None:
|
| 351 |
+
last_stream_id = self._connection_terminated.last_stream_id
|
| 352 |
+
if stream_id and last_stream_id and stream_id > last_stream_id:
|
| 353 |
+
self._request_count -= 1
|
| 354 |
+
raise ConnectionNotAvailable()
|
| 355 |
+
raise RemoteProtocolError(self._connection_terminated)
|
| 356 |
+
|
| 357 |
+
# This conditional is a bit icky. We don't want to block reading if we've
|
| 358 |
+
# actually got an event to return for a given stream. We need to do that
|
| 359 |
+
# check *within* the atomic read lock. Though it also need to be optional,
|
| 360 |
+
# because when we call it from `_wait_for_outgoing_flow` we *do* want to
|
| 361 |
+
# block until we've available flow control, event when we have events
|
| 362 |
+
# pending for the stream ID we're attempting to send on.
|
| 363 |
+
if stream_id is None or not self._events.get(stream_id):
|
| 364 |
+
events = await self._read_incoming_data(request)
|
| 365 |
+
for event in events:
|
| 366 |
+
if isinstance(event, h2.events.RemoteSettingsChanged):
|
| 367 |
+
async with Trace(
|
| 368 |
+
"receive_remote_settings", logger, request
|
| 369 |
+
) as trace:
|
| 370 |
+
await self._receive_remote_settings_change(event)
|
| 371 |
+
trace.return_value = event
|
| 372 |
+
|
| 373 |
+
elif isinstance(
|
| 374 |
+
event,
|
| 375 |
+
(
|
| 376 |
+
h2.events.ResponseReceived,
|
| 377 |
+
h2.events.DataReceived,
|
| 378 |
+
h2.events.StreamEnded,
|
| 379 |
+
h2.events.StreamReset,
|
| 380 |
+
),
|
| 381 |
+
):
|
| 382 |
+
if event.stream_id in self._events:
|
| 383 |
+
self._events[event.stream_id].append(event)
|
| 384 |
+
|
| 385 |
+
elif isinstance(event, h2.events.ConnectionTerminated):
|
| 386 |
+
self._connection_terminated = event
|
| 387 |
+
|
| 388 |
+
await self._write_outgoing_data(request)
|
| 389 |
+
|
| 390 |
+
async def _receive_remote_settings_change(
|
| 391 |
+
self, event: h2.events.RemoteSettingsChanged
|
| 392 |
+
) -> None:
|
| 393 |
+
max_concurrent_streams = event.changed_settings.get(
|
| 394 |
+
h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS
|
| 395 |
+
)
|
| 396 |
+
if max_concurrent_streams:
|
| 397 |
+
new_max_streams = min(
|
| 398 |
+
max_concurrent_streams.new_value,
|
| 399 |
+
self._h2_state.local_settings.max_concurrent_streams,
|
| 400 |
+
)
|
| 401 |
+
if new_max_streams and new_max_streams != self._max_streams:
|
| 402 |
+
while new_max_streams > self._max_streams:
|
| 403 |
+
await self._max_streams_semaphore.release()
|
| 404 |
+
self._max_streams += 1
|
| 405 |
+
while new_max_streams < self._max_streams:
|
| 406 |
+
await self._max_streams_semaphore.acquire()
|
| 407 |
+
self._max_streams -= 1
|
| 408 |
+
|
| 409 |
+
async def _response_closed(self, stream_id: int) -> None:
|
| 410 |
+
await self._max_streams_semaphore.release()
|
| 411 |
+
del self._events[stream_id]
|
| 412 |
+
async with self._state_lock:
|
| 413 |
+
if self._connection_terminated and not self._events:
|
| 414 |
+
await self.aclose()
|
| 415 |
+
|
| 416 |
+
elif self._state == HTTPConnectionState.ACTIVE and not self._events:
|
| 417 |
+
self._state = HTTPConnectionState.IDLE
|
| 418 |
+
if self._keepalive_expiry is not None:
|
| 419 |
+
now = time.monotonic()
|
| 420 |
+
self._expire_at = now + self._keepalive_expiry
|
| 421 |
+
if self._used_all_stream_ids: # pragma: nocover
|
| 422 |
+
await self.aclose()
|
| 423 |
+
|
| 424 |
+
async def aclose(self) -> None:
|
| 425 |
+
# Note that this method unilaterally closes the connection, and does
|
| 426 |
+
# not have any kind of locking in place around it.
|
| 427 |
+
self._h2_state.close_connection()
|
| 428 |
+
self._state = HTTPConnectionState.CLOSED
|
| 429 |
+
await self._network_stream.aclose()
|
| 430 |
+
|
| 431 |
+
# Wrappers around network read/write operations...
|
| 432 |
+
|
| 433 |
+
async def _read_incoming_data(self, request: Request) -> list[h2.events.Event]:
|
| 434 |
+
timeouts = request.extensions.get("timeout", {})
|
| 435 |
+
timeout = timeouts.get("read", None)
|
| 436 |
+
|
| 437 |
+
if self._read_exception is not None:
|
| 438 |
+
raise self._read_exception # pragma: nocover
|
| 439 |
+
|
| 440 |
+
try:
|
| 441 |
+
data = await self._network_stream.read(self.READ_NUM_BYTES, timeout)
|
| 442 |
+
if data == b"":
|
| 443 |
+
raise RemoteProtocolError("Server disconnected")
|
| 444 |
+
except Exception as exc:
|
| 445 |
+
# If we get a network error we should:
|
| 446 |
+
#
|
| 447 |
+
# 1. Save the exception and just raise it immediately on any future reads.
|
| 448 |
+
# (For example, this means that a single read timeout or disconnect will
|
| 449 |
+
# immediately close all pending streams. Without requiring multiple
|
| 450 |
+
# sequential timeouts.)
|
| 451 |
+
# 2. Mark the connection as errored, so that we don't accept any other
|
| 452 |
+
# incoming requests.
|
| 453 |
+
self._read_exception = exc
|
| 454 |
+
self._connection_error = True
|
| 455 |
+
raise exc
|
| 456 |
+
|
| 457 |
+
events: list[h2.events.Event] = self._h2_state.receive_data(data)
|
| 458 |
+
|
| 459 |
+
return events
|
| 460 |
+
|
| 461 |
+
async def _write_outgoing_data(self, request: Request) -> None:
|
| 462 |
+
timeouts = request.extensions.get("timeout", {})
|
| 463 |
+
timeout = timeouts.get("write", None)
|
| 464 |
+
|
| 465 |
+
async with self._write_lock:
|
| 466 |
+
data_to_send = self._h2_state.data_to_send()
|
| 467 |
+
|
| 468 |
+
if self._write_exception is not None:
|
| 469 |
+
raise self._write_exception # pragma: nocover
|
| 470 |
+
|
| 471 |
+
try:
|
| 472 |
+
await self._network_stream.write(data_to_send, timeout)
|
| 473 |
+
except Exception as exc: # pragma: nocover
|
| 474 |
+
# If we get a network error we should:
|
| 475 |
+
#
|
| 476 |
+
# 1. Save the exception and just raise it immediately on any future write.
|
| 477 |
+
# (For example, this means that a single write timeout or disconnect will
|
| 478 |
+
# immediately close all pending streams. Without requiring multiple
|
| 479 |
+
# sequential timeouts.)
|
| 480 |
+
# 2. Mark the connection as errored, so that we don't accept any other
|
| 481 |
+
# incoming requests.
|
| 482 |
+
self._write_exception = exc
|
| 483 |
+
self._connection_error = True
|
| 484 |
+
raise exc
|
| 485 |
+
|
| 486 |
+
# Flow control...
|
| 487 |
+
|
| 488 |
+
async def _wait_for_outgoing_flow(self, request: Request, stream_id: int) -> int:
|
| 489 |
+
"""
|
| 490 |
+
Returns the maximum allowable outgoing flow for a given stream.
|
| 491 |
+
|
| 492 |
+
If the allowable flow is zero, then waits on the network until
|
| 493 |
+
WindowUpdated frames have increased the flow rate.
|
| 494 |
+
https://tools.ietf.org/html/rfc7540#section-6.9
|
| 495 |
+
"""
|
| 496 |
+
local_flow: int = self._h2_state.local_flow_control_window(stream_id)
|
| 497 |
+
max_frame_size: int = self._h2_state.max_outbound_frame_size
|
| 498 |
+
flow = min(local_flow, max_frame_size)
|
| 499 |
+
while flow == 0:
|
| 500 |
+
await self._receive_events(request)
|
| 501 |
+
local_flow = self._h2_state.local_flow_control_window(stream_id)
|
| 502 |
+
max_frame_size = self._h2_state.max_outbound_frame_size
|
| 503 |
+
flow = min(local_flow, max_frame_size)
|
| 504 |
+
return flow
|
| 505 |
+
|
| 506 |
+
# Interface for connection pooling...
|
| 507 |
+
|
| 508 |
+
def can_handle_request(self, origin: Origin) -> bool:
|
| 509 |
+
return origin == self._origin
|
| 510 |
+
|
| 511 |
+
def is_available(self) -> bool:
|
| 512 |
+
return (
|
| 513 |
+
self._state != HTTPConnectionState.CLOSED
|
| 514 |
+
and not self._connection_error
|
| 515 |
+
and not self._used_all_stream_ids
|
| 516 |
+
and not (
|
| 517 |
+
self._h2_state.state_machine.state
|
| 518 |
+
== h2.connection.ConnectionState.CLOSED
|
| 519 |
+
)
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
def has_expired(self) -> bool:
|
| 523 |
+
now = time.monotonic()
|
| 524 |
+
return self._expire_at is not None and now > self._expire_at
|
| 525 |
+
|
| 526 |
+
def is_idle(self) -> bool:
|
| 527 |
+
return self._state == HTTPConnectionState.IDLE
|
| 528 |
+
|
| 529 |
+
def is_closed(self) -> bool:
|
| 530 |
+
return self._state == HTTPConnectionState.CLOSED
|
| 531 |
+
|
| 532 |
+
def info(self) -> str:
|
| 533 |
+
origin = str(self._origin)
|
| 534 |
+
return (
|
| 535 |
+
f"{origin!r}, HTTP/2, {self._state.name}, "
|
| 536 |
+
f"Request Count: {self._request_count}"
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
def __repr__(self) -> str:
|
| 540 |
+
class_name = self.__class__.__name__
|
| 541 |
+
origin = str(self._origin)
|
| 542 |
+
return (
|
| 543 |
+
f"<{class_name} [{origin!r}, {self._state.name}, "
|
| 544 |
+
f"Request Count: {self._request_count}]>"
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
# These context managers are not used in the standard flow, but are
|
| 548 |
+
# useful for testing or working with connection instances directly.
|
| 549 |
+
|
| 550 |
+
async def __aenter__(self) -> AsyncHTTP2Connection:
|
| 551 |
+
return self
|
| 552 |
+
|
| 553 |
+
async def __aexit__(
|
| 554 |
+
self,
|
| 555 |
+
exc_type: type[BaseException] | None = None,
|
| 556 |
+
exc_value: BaseException | None = None,
|
| 557 |
+
traceback: types.TracebackType | None = None,
|
| 558 |
+
) -> None:
|
| 559 |
+
await self.aclose()
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
class HTTP2ConnectionByteStream:
|
| 563 |
+
def __init__(
|
| 564 |
+
self, connection: AsyncHTTP2Connection, request: Request, stream_id: int
|
| 565 |
+
) -> None:
|
| 566 |
+
self._connection = connection
|
| 567 |
+
self._request = request
|
| 568 |
+
self._stream_id = stream_id
|
| 569 |
+
self._closed = False
|
| 570 |
+
|
| 571 |
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
| 572 |
+
kwargs = {"request": self._request, "stream_id": self._stream_id}
|
| 573 |
+
try:
|
| 574 |
+
async with Trace("receive_response_body", logger, self._request, kwargs):
|
| 575 |
+
async for chunk in self._connection._receive_response_body(
|
| 576 |
+
request=self._request, stream_id=self._stream_id
|
| 577 |
+
):
|
| 578 |
+
yield chunk
|
| 579 |
+
except BaseException as exc:
|
| 580 |
+
# If we get an exception while streaming the response,
|
| 581 |
+
# we want to close the response (and possibly the connection)
|
| 582 |
+
# before raising that exception.
|
| 583 |
+
with AsyncShieldCancellation():
|
| 584 |
+
await self.aclose()
|
| 585 |
+
raise exc
|
| 586 |
+
|
| 587 |
+
async def aclose(self) -> None:
|
| 588 |
+
if not self._closed:
|
| 589 |
+
self._closed = True
|
| 590 |
+
kwargs = {"stream_id": self._stream_id}
|
| 591 |
+
async with Trace("response_closed", logger, self._request, kwargs):
|
| 592 |
+
await self._connection._response_closed(stream_id=self._stream_id)
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/http_proxy.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import logging
|
| 5 |
+
import ssl
|
| 6 |
+
import typing
|
| 7 |
+
|
| 8 |
+
from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend
|
| 9 |
+
from .._exceptions import ProxyError
|
| 10 |
+
from .._models import (
|
| 11 |
+
URL,
|
| 12 |
+
Origin,
|
| 13 |
+
Request,
|
| 14 |
+
Response,
|
| 15 |
+
enforce_bytes,
|
| 16 |
+
enforce_headers,
|
| 17 |
+
enforce_url,
|
| 18 |
+
)
|
| 19 |
+
from .._ssl import default_ssl_context
|
| 20 |
+
from .._synchronization import AsyncLock
|
| 21 |
+
from .._trace import Trace
|
| 22 |
+
from .connection import AsyncHTTPConnection
|
| 23 |
+
from .connection_pool import AsyncConnectionPool
|
| 24 |
+
from .http11 import AsyncHTTP11Connection
|
| 25 |
+
from .interfaces import AsyncConnectionInterface
|
| 26 |
+
|
| 27 |
+
ByteOrStr = typing.Union[bytes, str]
|
| 28 |
+
HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]]
|
| 29 |
+
HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger("httpcore.proxy")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def merge_headers(
|
| 36 |
+
default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,
|
| 37 |
+
override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,
|
| 38 |
+
) -> list[tuple[bytes, bytes]]:
|
| 39 |
+
"""
|
| 40 |
+
Append default_headers and override_headers, de-duplicating if a key exists
|
| 41 |
+
in both cases.
|
| 42 |
+
"""
|
| 43 |
+
default_headers = [] if default_headers is None else list(default_headers)
|
| 44 |
+
override_headers = [] if override_headers is None else list(override_headers)
|
| 45 |
+
has_override = set(key.lower() for key, value in override_headers)
|
| 46 |
+
default_headers = [
|
| 47 |
+
(key, value)
|
| 48 |
+
for key, value in default_headers
|
| 49 |
+
if key.lower() not in has_override
|
| 50 |
+
]
|
| 51 |
+
return default_headers + override_headers
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class AsyncHTTPProxy(AsyncConnectionPool): # pragma: nocover
|
| 55 |
+
"""
|
| 56 |
+
A connection pool that sends requests via an HTTP proxy.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
proxy_url: URL | bytes | str,
|
| 62 |
+
proxy_auth: tuple[bytes | str, bytes | str] | None = None,
|
| 63 |
+
proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None,
|
| 64 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 65 |
+
proxy_ssl_context: ssl.SSLContext | None = None,
|
| 66 |
+
max_connections: int | None = 10,
|
| 67 |
+
max_keepalive_connections: int | None = None,
|
| 68 |
+
keepalive_expiry: float | None = None,
|
| 69 |
+
http1: bool = True,
|
| 70 |
+
http2: bool = False,
|
| 71 |
+
retries: int = 0,
|
| 72 |
+
local_address: str | None = None,
|
| 73 |
+
uds: str | None = None,
|
| 74 |
+
network_backend: AsyncNetworkBackend | None = None,
|
| 75 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 76 |
+
) -> None:
|
| 77 |
+
"""
|
| 78 |
+
A connection pool for making HTTP requests.
|
| 79 |
+
|
| 80 |
+
Parameters:
|
| 81 |
+
proxy_url: The URL to use when connecting to the proxy server.
|
| 82 |
+
For example `"http://127.0.0.1:8080/"`.
|
| 83 |
+
proxy_auth: Any proxy authentication as a two-tuple of
|
| 84 |
+
(username, password). May be either bytes or ascii-only str.
|
| 85 |
+
proxy_headers: Any HTTP headers to use for the proxy requests.
|
| 86 |
+
For example `{"Proxy-Authorization": "Basic <username>:<password>"}`.
|
| 87 |
+
ssl_context: An SSL context to use for verifying connections.
|
| 88 |
+
If not specified, the default `httpcore.default_ssl_context()`
|
| 89 |
+
will be used.
|
| 90 |
+
proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin.
|
| 91 |
+
max_connections: The maximum number of concurrent HTTP connections that
|
| 92 |
+
the pool should allow. Any attempt to send a request on a pool that
|
| 93 |
+
would exceed this amount will block until a connection is available.
|
| 94 |
+
max_keepalive_connections: The maximum number of idle HTTP connections
|
| 95 |
+
that will be maintained in the pool.
|
| 96 |
+
keepalive_expiry: The duration in seconds that an idle HTTP connection
|
| 97 |
+
may be maintained for before being expired from the pool.
|
| 98 |
+
http1: A boolean indicating if HTTP/1.1 requests should be supported
|
| 99 |
+
by the connection pool. Defaults to True.
|
| 100 |
+
http2: A boolean indicating if HTTP/2 requests should be supported by
|
| 101 |
+
the connection pool. Defaults to False.
|
| 102 |
+
retries: The maximum number of retries when trying to establish
|
| 103 |
+
a connection.
|
| 104 |
+
local_address: Local address to connect from. Can also be used to
|
| 105 |
+
connect using a particular address family. Using
|
| 106 |
+
`local_address="0.0.0.0"` will connect using an `AF_INET` address
|
| 107 |
+
(IPv4), while using `local_address="::"` will connect using an
|
| 108 |
+
`AF_INET6` address (IPv6).
|
| 109 |
+
uds: Path to a Unix Domain Socket to use instead of TCP sockets.
|
| 110 |
+
network_backend: A backend instance to use for handling network I/O.
|
| 111 |
+
"""
|
| 112 |
+
super().__init__(
|
| 113 |
+
ssl_context=ssl_context,
|
| 114 |
+
max_connections=max_connections,
|
| 115 |
+
max_keepalive_connections=max_keepalive_connections,
|
| 116 |
+
keepalive_expiry=keepalive_expiry,
|
| 117 |
+
http1=http1,
|
| 118 |
+
http2=http2,
|
| 119 |
+
network_backend=network_backend,
|
| 120 |
+
retries=retries,
|
| 121 |
+
local_address=local_address,
|
| 122 |
+
uds=uds,
|
| 123 |
+
socket_options=socket_options,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
self._proxy_url = enforce_url(proxy_url, name="proxy_url")
|
| 127 |
+
if (
|
| 128 |
+
self._proxy_url.scheme == b"http" and proxy_ssl_context is not None
|
| 129 |
+
): # pragma: no cover
|
| 130 |
+
raise RuntimeError(
|
| 131 |
+
"The `proxy_ssl_context` argument is not allowed for the http scheme"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
self._ssl_context = ssl_context
|
| 135 |
+
self._proxy_ssl_context = proxy_ssl_context
|
| 136 |
+
self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers")
|
| 137 |
+
if proxy_auth is not None:
|
| 138 |
+
username = enforce_bytes(proxy_auth[0], name="proxy_auth")
|
| 139 |
+
password = enforce_bytes(proxy_auth[1], name="proxy_auth")
|
| 140 |
+
userpass = username + b":" + password
|
| 141 |
+
authorization = b"Basic " + base64.b64encode(userpass)
|
| 142 |
+
self._proxy_headers = [
|
| 143 |
+
(b"Proxy-Authorization", authorization)
|
| 144 |
+
] + self._proxy_headers
|
| 145 |
+
|
| 146 |
+
def create_connection(self, origin: Origin) -> AsyncConnectionInterface:
|
| 147 |
+
if origin.scheme == b"http":
|
| 148 |
+
return AsyncForwardHTTPConnection(
|
| 149 |
+
proxy_origin=self._proxy_url.origin,
|
| 150 |
+
proxy_headers=self._proxy_headers,
|
| 151 |
+
remote_origin=origin,
|
| 152 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 153 |
+
network_backend=self._network_backend,
|
| 154 |
+
proxy_ssl_context=self._proxy_ssl_context,
|
| 155 |
+
)
|
| 156 |
+
return AsyncTunnelHTTPConnection(
|
| 157 |
+
proxy_origin=self._proxy_url.origin,
|
| 158 |
+
proxy_headers=self._proxy_headers,
|
| 159 |
+
remote_origin=origin,
|
| 160 |
+
ssl_context=self._ssl_context,
|
| 161 |
+
proxy_ssl_context=self._proxy_ssl_context,
|
| 162 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 163 |
+
http1=self._http1,
|
| 164 |
+
http2=self._http2,
|
| 165 |
+
network_backend=self._network_backend,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class AsyncForwardHTTPConnection(AsyncConnectionInterface):
|
| 170 |
+
def __init__(
|
| 171 |
+
self,
|
| 172 |
+
proxy_origin: Origin,
|
| 173 |
+
remote_origin: Origin,
|
| 174 |
+
proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None,
|
| 175 |
+
keepalive_expiry: float | None = None,
|
| 176 |
+
network_backend: AsyncNetworkBackend | None = None,
|
| 177 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 178 |
+
proxy_ssl_context: ssl.SSLContext | None = None,
|
| 179 |
+
) -> None:
|
| 180 |
+
self._connection = AsyncHTTPConnection(
|
| 181 |
+
origin=proxy_origin,
|
| 182 |
+
keepalive_expiry=keepalive_expiry,
|
| 183 |
+
network_backend=network_backend,
|
| 184 |
+
socket_options=socket_options,
|
| 185 |
+
ssl_context=proxy_ssl_context,
|
| 186 |
+
)
|
| 187 |
+
self._proxy_origin = proxy_origin
|
| 188 |
+
self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers")
|
| 189 |
+
self._remote_origin = remote_origin
|
| 190 |
+
|
| 191 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 192 |
+
headers = merge_headers(self._proxy_headers, request.headers)
|
| 193 |
+
url = URL(
|
| 194 |
+
scheme=self._proxy_origin.scheme,
|
| 195 |
+
host=self._proxy_origin.host,
|
| 196 |
+
port=self._proxy_origin.port,
|
| 197 |
+
target=bytes(request.url),
|
| 198 |
+
)
|
| 199 |
+
proxy_request = Request(
|
| 200 |
+
method=request.method,
|
| 201 |
+
url=url,
|
| 202 |
+
headers=headers,
|
| 203 |
+
content=request.stream,
|
| 204 |
+
extensions=request.extensions,
|
| 205 |
+
)
|
| 206 |
+
return await self._connection.handle_async_request(proxy_request)
|
| 207 |
+
|
| 208 |
+
def can_handle_request(self, origin: Origin) -> bool:
|
| 209 |
+
return origin == self._remote_origin
|
| 210 |
+
|
| 211 |
+
async def aclose(self) -> None:
|
| 212 |
+
await self._connection.aclose()
|
| 213 |
+
|
| 214 |
+
def info(self) -> str:
|
| 215 |
+
return self._connection.info()
|
| 216 |
+
|
| 217 |
+
def is_available(self) -> bool:
|
| 218 |
+
return self._connection.is_available()
|
| 219 |
+
|
| 220 |
+
def has_expired(self) -> bool:
|
| 221 |
+
return self._connection.has_expired()
|
| 222 |
+
|
| 223 |
+
def is_idle(self) -> bool:
|
| 224 |
+
return self._connection.is_idle()
|
| 225 |
+
|
| 226 |
+
def is_closed(self) -> bool:
|
| 227 |
+
return self._connection.is_closed()
|
| 228 |
+
|
| 229 |
+
def __repr__(self) -> str:
|
| 230 |
+
return f"<{self.__class__.__name__} [{self.info()}]>"
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class AsyncTunnelHTTPConnection(AsyncConnectionInterface):
|
| 234 |
+
def __init__(
|
| 235 |
+
self,
|
| 236 |
+
proxy_origin: Origin,
|
| 237 |
+
remote_origin: Origin,
|
| 238 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 239 |
+
proxy_ssl_context: ssl.SSLContext | None = None,
|
| 240 |
+
proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,
|
| 241 |
+
keepalive_expiry: float | None = None,
|
| 242 |
+
http1: bool = True,
|
| 243 |
+
http2: bool = False,
|
| 244 |
+
network_backend: AsyncNetworkBackend | None = None,
|
| 245 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 246 |
+
) -> None:
|
| 247 |
+
self._connection: AsyncConnectionInterface = AsyncHTTPConnection(
|
| 248 |
+
origin=proxy_origin,
|
| 249 |
+
keepalive_expiry=keepalive_expiry,
|
| 250 |
+
network_backend=network_backend,
|
| 251 |
+
socket_options=socket_options,
|
| 252 |
+
ssl_context=proxy_ssl_context,
|
| 253 |
+
)
|
| 254 |
+
self._proxy_origin = proxy_origin
|
| 255 |
+
self._remote_origin = remote_origin
|
| 256 |
+
self._ssl_context = ssl_context
|
| 257 |
+
self._proxy_ssl_context = proxy_ssl_context
|
| 258 |
+
self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers")
|
| 259 |
+
self._keepalive_expiry = keepalive_expiry
|
| 260 |
+
self._http1 = http1
|
| 261 |
+
self._http2 = http2
|
| 262 |
+
self._connect_lock = AsyncLock()
|
| 263 |
+
self._connected = False
|
| 264 |
+
|
| 265 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 266 |
+
timeouts = request.extensions.get("timeout", {})
|
| 267 |
+
timeout = timeouts.get("connect", None)
|
| 268 |
+
|
| 269 |
+
async with self._connect_lock:
|
| 270 |
+
if not self._connected:
|
| 271 |
+
target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port)
|
| 272 |
+
|
| 273 |
+
connect_url = URL(
|
| 274 |
+
scheme=self._proxy_origin.scheme,
|
| 275 |
+
host=self._proxy_origin.host,
|
| 276 |
+
port=self._proxy_origin.port,
|
| 277 |
+
target=target,
|
| 278 |
+
)
|
| 279 |
+
connect_headers = merge_headers(
|
| 280 |
+
[(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers
|
| 281 |
+
)
|
| 282 |
+
connect_request = Request(
|
| 283 |
+
method=b"CONNECT",
|
| 284 |
+
url=connect_url,
|
| 285 |
+
headers=connect_headers,
|
| 286 |
+
extensions=request.extensions,
|
| 287 |
+
)
|
| 288 |
+
connect_response = await self._connection.handle_async_request(
|
| 289 |
+
connect_request
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
if connect_response.status < 200 or connect_response.status > 299:
|
| 293 |
+
reason_bytes = connect_response.extensions.get("reason_phrase", b"")
|
| 294 |
+
reason_str = reason_bytes.decode("ascii", errors="ignore")
|
| 295 |
+
msg = "%d %s" % (connect_response.status, reason_str)
|
| 296 |
+
await self._connection.aclose()
|
| 297 |
+
raise ProxyError(msg)
|
| 298 |
+
|
| 299 |
+
stream = connect_response.extensions["network_stream"]
|
| 300 |
+
|
| 301 |
+
# Upgrade the stream to SSL
|
| 302 |
+
ssl_context = (
|
| 303 |
+
default_ssl_context()
|
| 304 |
+
if self._ssl_context is None
|
| 305 |
+
else self._ssl_context
|
| 306 |
+
)
|
| 307 |
+
alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"]
|
| 308 |
+
ssl_context.set_alpn_protocols(alpn_protocols)
|
| 309 |
+
|
| 310 |
+
kwargs = {
|
| 311 |
+
"ssl_context": ssl_context,
|
| 312 |
+
"server_hostname": self._remote_origin.host.decode("ascii"),
|
| 313 |
+
"timeout": timeout,
|
| 314 |
+
}
|
| 315 |
+
async with Trace("start_tls", logger, request, kwargs) as trace:
|
| 316 |
+
stream = await stream.start_tls(**kwargs)
|
| 317 |
+
trace.return_value = stream
|
| 318 |
+
|
| 319 |
+
# Determine if we should be using HTTP/1.1 or HTTP/2
|
| 320 |
+
ssl_object = stream.get_extra_info("ssl_object")
|
| 321 |
+
http2_negotiated = (
|
| 322 |
+
ssl_object is not None
|
| 323 |
+
and ssl_object.selected_alpn_protocol() == "h2"
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
# Create the HTTP/1.1 or HTTP/2 connection
|
| 327 |
+
if http2_negotiated or (self._http2 and not self._http1):
|
| 328 |
+
from .http2 import AsyncHTTP2Connection
|
| 329 |
+
|
| 330 |
+
self._connection = AsyncHTTP2Connection(
|
| 331 |
+
origin=self._remote_origin,
|
| 332 |
+
stream=stream,
|
| 333 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 334 |
+
)
|
| 335 |
+
else:
|
| 336 |
+
self._connection = AsyncHTTP11Connection(
|
| 337 |
+
origin=self._remote_origin,
|
| 338 |
+
stream=stream,
|
| 339 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
self._connected = True
|
| 343 |
+
return await self._connection.handle_async_request(request)
|
| 344 |
+
|
| 345 |
+
def can_handle_request(self, origin: Origin) -> bool:
|
| 346 |
+
return origin == self._remote_origin
|
| 347 |
+
|
| 348 |
+
async def aclose(self) -> None:
|
| 349 |
+
await self._connection.aclose()
|
| 350 |
+
|
| 351 |
+
def info(self) -> str:
|
| 352 |
+
return self._connection.info()
|
| 353 |
+
|
| 354 |
+
def is_available(self) -> bool:
|
| 355 |
+
return self._connection.is_available()
|
| 356 |
+
|
| 357 |
+
def has_expired(self) -> bool:
|
| 358 |
+
return self._connection.has_expired()
|
| 359 |
+
|
| 360 |
+
def is_idle(self) -> bool:
|
| 361 |
+
return self._connection.is_idle()
|
| 362 |
+
|
| 363 |
+
def is_closed(self) -> bool:
|
| 364 |
+
return self._connection.is_closed()
|
| 365 |
+
|
| 366 |
+
def __repr__(self) -> str:
|
| 367 |
+
return f"<{self.__class__.__name__} [{self.info()}]>"
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/interfaces.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import typing
|
| 5 |
+
|
| 6 |
+
from .._models import (
|
| 7 |
+
URL,
|
| 8 |
+
Extensions,
|
| 9 |
+
HeaderTypes,
|
| 10 |
+
Origin,
|
| 11 |
+
Request,
|
| 12 |
+
Response,
|
| 13 |
+
enforce_bytes,
|
| 14 |
+
enforce_headers,
|
| 15 |
+
enforce_url,
|
| 16 |
+
include_request_headers,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class AsyncRequestInterface:
|
| 21 |
+
async def request(
|
| 22 |
+
self,
|
| 23 |
+
method: bytes | str,
|
| 24 |
+
url: URL | bytes | str,
|
| 25 |
+
*,
|
| 26 |
+
headers: HeaderTypes = None,
|
| 27 |
+
content: bytes | typing.AsyncIterator[bytes] | None = None,
|
| 28 |
+
extensions: Extensions | None = None,
|
| 29 |
+
) -> Response:
|
| 30 |
+
# Strict type checking on our parameters.
|
| 31 |
+
method = enforce_bytes(method, name="method")
|
| 32 |
+
url = enforce_url(url, name="url")
|
| 33 |
+
headers = enforce_headers(headers, name="headers")
|
| 34 |
+
|
| 35 |
+
# Include Host header, and optionally Content-Length or Transfer-Encoding.
|
| 36 |
+
headers = include_request_headers(headers, url=url, content=content)
|
| 37 |
+
|
| 38 |
+
request = Request(
|
| 39 |
+
method=method,
|
| 40 |
+
url=url,
|
| 41 |
+
headers=headers,
|
| 42 |
+
content=content,
|
| 43 |
+
extensions=extensions,
|
| 44 |
+
)
|
| 45 |
+
response = await self.handle_async_request(request)
|
| 46 |
+
try:
|
| 47 |
+
await response.aread()
|
| 48 |
+
finally:
|
| 49 |
+
await response.aclose()
|
| 50 |
+
return response
|
| 51 |
+
|
| 52 |
+
@contextlib.asynccontextmanager
|
| 53 |
+
async def stream(
|
| 54 |
+
self,
|
| 55 |
+
method: bytes | str,
|
| 56 |
+
url: URL | bytes | str,
|
| 57 |
+
*,
|
| 58 |
+
headers: HeaderTypes = None,
|
| 59 |
+
content: bytes | typing.AsyncIterator[bytes] | None = None,
|
| 60 |
+
extensions: Extensions | None = None,
|
| 61 |
+
) -> typing.AsyncIterator[Response]:
|
| 62 |
+
# Strict type checking on our parameters.
|
| 63 |
+
method = enforce_bytes(method, name="method")
|
| 64 |
+
url = enforce_url(url, name="url")
|
| 65 |
+
headers = enforce_headers(headers, name="headers")
|
| 66 |
+
|
| 67 |
+
# Include Host header, and optionally Content-Length or Transfer-Encoding.
|
| 68 |
+
headers = include_request_headers(headers, url=url, content=content)
|
| 69 |
+
|
| 70 |
+
request = Request(
|
| 71 |
+
method=method,
|
| 72 |
+
url=url,
|
| 73 |
+
headers=headers,
|
| 74 |
+
content=content,
|
| 75 |
+
extensions=extensions,
|
| 76 |
+
)
|
| 77 |
+
response = await self.handle_async_request(request)
|
| 78 |
+
try:
|
| 79 |
+
yield response
|
| 80 |
+
finally:
|
| 81 |
+
await response.aclose()
|
| 82 |
+
|
| 83 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 84 |
+
raise NotImplementedError() # pragma: nocover
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class AsyncConnectionInterface(AsyncRequestInterface):
|
| 88 |
+
async def aclose(self) -> None:
|
| 89 |
+
raise NotImplementedError() # pragma: nocover
|
| 90 |
+
|
| 91 |
+
def info(self) -> str:
|
| 92 |
+
raise NotImplementedError() # pragma: nocover
|
| 93 |
+
|
| 94 |
+
def can_handle_request(self, origin: Origin) -> bool:
|
| 95 |
+
raise NotImplementedError() # pragma: nocover
|
| 96 |
+
|
| 97 |
+
def is_available(self) -> bool:
|
| 98 |
+
"""
|
| 99 |
+
Return `True` if the connection is currently able to accept an
|
| 100 |
+
outgoing request.
|
| 101 |
+
|
| 102 |
+
An HTTP/1.1 connection will only be available if it is currently idle.
|
| 103 |
+
|
| 104 |
+
An HTTP/2 connection will be available so long as the stream ID space is
|
| 105 |
+
not yet exhausted, and the connection is not in an error state.
|
| 106 |
+
|
| 107 |
+
While the connection is being established we may not yet know if it is going
|
| 108 |
+
to result in an HTTP/1.1 or HTTP/2 connection. The connection should be
|
| 109 |
+
treated as being available, but might ultimately raise `NewConnectionRequired`
|
| 110 |
+
required exceptions if multiple requests are attempted over a connection
|
| 111 |
+
that ends up being established as HTTP/1.1.
|
| 112 |
+
"""
|
| 113 |
+
raise NotImplementedError() # pragma: nocover
|
| 114 |
+
|
| 115 |
+
def has_expired(self) -> bool:
|
| 116 |
+
"""
|
| 117 |
+
Return `True` if the connection is in a state where it should be closed.
|
| 118 |
+
|
| 119 |
+
This either means that the connection is idle and it has passed the
|
| 120 |
+
expiry time on its keep-alive, or that server has sent an EOF.
|
| 121 |
+
"""
|
| 122 |
+
raise NotImplementedError() # pragma: nocover
|
| 123 |
+
|
| 124 |
+
def is_idle(self) -> bool:
|
| 125 |
+
"""
|
| 126 |
+
Return `True` if the connection is currently idle.
|
| 127 |
+
"""
|
| 128 |
+
raise NotImplementedError() # pragma: nocover
|
| 129 |
+
|
| 130 |
+
def is_closed(self) -> bool:
|
| 131 |
+
"""
|
| 132 |
+
Return `True` if the connection has been closed.
|
| 133 |
+
|
| 134 |
+
Used when a response is closed to determine if the connection may be
|
| 135 |
+
returned to the connection pool or not.
|
| 136 |
+
"""
|
| 137 |
+
raise NotImplementedError() # pragma: nocover
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_async/socks_proxy.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import ssl
|
| 5 |
+
|
| 6 |
+
import socksio
|
| 7 |
+
|
| 8 |
+
from .._backends.auto import AutoBackend
|
| 9 |
+
from .._backends.base import AsyncNetworkBackend, AsyncNetworkStream
|
| 10 |
+
from .._exceptions import ConnectionNotAvailable, ProxyError
|
| 11 |
+
from .._models import URL, Origin, Request, Response, enforce_bytes, enforce_url
|
| 12 |
+
from .._ssl import default_ssl_context
|
| 13 |
+
from .._synchronization import AsyncLock
|
| 14 |
+
from .._trace import Trace
|
| 15 |
+
from .connection_pool import AsyncConnectionPool
|
| 16 |
+
from .http11 import AsyncHTTP11Connection
|
| 17 |
+
from .interfaces import AsyncConnectionInterface
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger("httpcore.socks")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
AUTH_METHODS = {
|
| 23 |
+
b"\x00": "NO AUTHENTICATION REQUIRED",
|
| 24 |
+
b"\x01": "GSSAPI",
|
| 25 |
+
b"\x02": "USERNAME/PASSWORD",
|
| 26 |
+
b"\xff": "NO ACCEPTABLE METHODS",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
REPLY_CODES = {
|
| 30 |
+
b"\x00": "Succeeded",
|
| 31 |
+
b"\x01": "General SOCKS server failure",
|
| 32 |
+
b"\x02": "Connection not allowed by ruleset",
|
| 33 |
+
b"\x03": "Network unreachable",
|
| 34 |
+
b"\x04": "Host unreachable",
|
| 35 |
+
b"\x05": "Connection refused",
|
| 36 |
+
b"\x06": "TTL expired",
|
| 37 |
+
b"\x07": "Command not supported",
|
| 38 |
+
b"\x08": "Address type not supported",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
async def _init_socks5_connection(
|
| 43 |
+
stream: AsyncNetworkStream,
|
| 44 |
+
*,
|
| 45 |
+
host: bytes,
|
| 46 |
+
port: int,
|
| 47 |
+
auth: tuple[bytes, bytes] | None = None,
|
| 48 |
+
) -> None:
|
| 49 |
+
conn = socksio.socks5.SOCKS5Connection()
|
| 50 |
+
|
| 51 |
+
# Auth method request
|
| 52 |
+
auth_method = (
|
| 53 |
+
socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED
|
| 54 |
+
if auth is None
|
| 55 |
+
else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD
|
| 56 |
+
)
|
| 57 |
+
conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method]))
|
| 58 |
+
outgoing_bytes = conn.data_to_send()
|
| 59 |
+
await stream.write(outgoing_bytes)
|
| 60 |
+
|
| 61 |
+
# Auth method response
|
| 62 |
+
incoming_bytes = await stream.read(max_bytes=4096)
|
| 63 |
+
response = conn.receive_data(incoming_bytes)
|
| 64 |
+
assert isinstance(response, socksio.socks5.SOCKS5AuthReply)
|
| 65 |
+
if response.method != auth_method:
|
| 66 |
+
requested = AUTH_METHODS.get(auth_method, "UNKNOWN")
|
| 67 |
+
responded = AUTH_METHODS.get(response.method, "UNKNOWN")
|
| 68 |
+
raise ProxyError(
|
| 69 |
+
f"Requested {requested} from proxy server, but got {responded}."
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD:
|
| 73 |
+
# Username/password request
|
| 74 |
+
assert auth is not None
|
| 75 |
+
username, password = auth
|
| 76 |
+
conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password))
|
| 77 |
+
outgoing_bytes = conn.data_to_send()
|
| 78 |
+
await stream.write(outgoing_bytes)
|
| 79 |
+
|
| 80 |
+
# Username/password response
|
| 81 |
+
incoming_bytes = await stream.read(max_bytes=4096)
|
| 82 |
+
response = conn.receive_data(incoming_bytes)
|
| 83 |
+
assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply)
|
| 84 |
+
if not response.success:
|
| 85 |
+
raise ProxyError("Invalid username/password")
|
| 86 |
+
|
| 87 |
+
# Connect request
|
| 88 |
+
conn.send(
|
| 89 |
+
socksio.socks5.SOCKS5CommandRequest.from_address(
|
| 90 |
+
socksio.socks5.SOCKS5Command.CONNECT, (host, port)
|
| 91 |
+
)
|
| 92 |
+
)
|
| 93 |
+
outgoing_bytes = conn.data_to_send()
|
| 94 |
+
await stream.write(outgoing_bytes)
|
| 95 |
+
|
| 96 |
+
# Connect response
|
| 97 |
+
incoming_bytes = await stream.read(max_bytes=4096)
|
| 98 |
+
response = conn.receive_data(incoming_bytes)
|
| 99 |
+
assert isinstance(response, socksio.socks5.SOCKS5Reply)
|
| 100 |
+
if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED:
|
| 101 |
+
reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN")
|
| 102 |
+
raise ProxyError(f"Proxy Server could not connect: {reply_code}.")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class AsyncSOCKSProxy(AsyncConnectionPool): # pragma: nocover
|
| 106 |
+
"""
|
| 107 |
+
A connection pool that sends requests via an HTTP proxy.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def __init__(
|
| 111 |
+
self,
|
| 112 |
+
proxy_url: URL | bytes | str,
|
| 113 |
+
proxy_auth: tuple[bytes | str, bytes | str] | None = None,
|
| 114 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 115 |
+
max_connections: int | None = 10,
|
| 116 |
+
max_keepalive_connections: int | None = None,
|
| 117 |
+
keepalive_expiry: float | None = None,
|
| 118 |
+
http1: bool = True,
|
| 119 |
+
http2: bool = False,
|
| 120 |
+
retries: int = 0,
|
| 121 |
+
network_backend: AsyncNetworkBackend | None = None,
|
| 122 |
+
) -> None:
|
| 123 |
+
"""
|
| 124 |
+
A connection pool for making HTTP requests.
|
| 125 |
+
|
| 126 |
+
Parameters:
|
| 127 |
+
proxy_url: The URL to use when connecting to the proxy server.
|
| 128 |
+
For example `"http://127.0.0.1:8080/"`.
|
| 129 |
+
ssl_context: An SSL context to use for verifying connections.
|
| 130 |
+
If not specified, the default `httpcore.default_ssl_context()`
|
| 131 |
+
will be used.
|
| 132 |
+
max_connections: The maximum number of concurrent HTTP connections that
|
| 133 |
+
the pool should allow. Any attempt to send a request on a pool that
|
| 134 |
+
would exceed this amount will block until a connection is available.
|
| 135 |
+
max_keepalive_connections: The maximum number of idle HTTP connections
|
| 136 |
+
that will be maintained in the pool.
|
| 137 |
+
keepalive_expiry: The duration in seconds that an idle HTTP connection
|
| 138 |
+
may be maintained for before being expired from the pool.
|
| 139 |
+
http1: A boolean indicating if HTTP/1.1 requests should be supported
|
| 140 |
+
by the connection pool. Defaults to True.
|
| 141 |
+
http2: A boolean indicating if HTTP/2 requests should be supported by
|
| 142 |
+
the connection pool. Defaults to False.
|
| 143 |
+
retries: The maximum number of retries when trying to establish
|
| 144 |
+
a connection.
|
| 145 |
+
local_address: Local address to connect from. Can also be used to
|
| 146 |
+
connect using a particular address family. Using
|
| 147 |
+
`local_address="0.0.0.0"` will connect using an `AF_INET` address
|
| 148 |
+
(IPv4), while using `local_address="::"` will connect using an
|
| 149 |
+
`AF_INET6` address (IPv6).
|
| 150 |
+
uds: Path to a Unix Domain Socket to use instead of TCP sockets.
|
| 151 |
+
network_backend: A backend instance to use for handling network I/O.
|
| 152 |
+
"""
|
| 153 |
+
super().__init__(
|
| 154 |
+
ssl_context=ssl_context,
|
| 155 |
+
max_connections=max_connections,
|
| 156 |
+
max_keepalive_connections=max_keepalive_connections,
|
| 157 |
+
keepalive_expiry=keepalive_expiry,
|
| 158 |
+
http1=http1,
|
| 159 |
+
http2=http2,
|
| 160 |
+
network_backend=network_backend,
|
| 161 |
+
retries=retries,
|
| 162 |
+
)
|
| 163 |
+
self._ssl_context = ssl_context
|
| 164 |
+
self._proxy_url = enforce_url(proxy_url, name="proxy_url")
|
| 165 |
+
if proxy_auth is not None:
|
| 166 |
+
username, password = proxy_auth
|
| 167 |
+
username_bytes = enforce_bytes(username, name="proxy_auth")
|
| 168 |
+
password_bytes = enforce_bytes(password, name="proxy_auth")
|
| 169 |
+
self._proxy_auth: tuple[bytes, bytes] | None = (
|
| 170 |
+
username_bytes,
|
| 171 |
+
password_bytes,
|
| 172 |
+
)
|
| 173 |
+
else:
|
| 174 |
+
self._proxy_auth = None
|
| 175 |
+
|
| 176 |
+
def create_connection(self, origin: Origin) -> AsyncConnectionInterface:
|
| 177 |
+
return AsyncSocks5Connection(
|
| 178 |
+
proxy_origin=self._proxy_url.origin,
|
| 179 |
+
remote_origin=origin,
|
| 180 |
+
proxy_auth=self._proxy_auth,
|
| 181 |
+
ssl_context=self._ssl_context,
|
| 182 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 183 |
+
http1=self._http1,
|
| 184 |
+
http2=self._http2,
|
| 185 |
+
network_backend=self._network_backend,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class AsyncSocks5Connection(AsyncConnectionInterface):
|
| 190 |
+
def __init__(
|
| 191 |
+
self,
|
| 192 |
+
proxy_origin: Origin,
|
| 193 |
+
remote_origin: Origin,
|
| 194 |
+
proxy_auth: tuple[bytes, bytes] | None = None,
|
| 195 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 196 |
+
keepalive_expiry: float | None = None,
|
| 197 |
+
http1: bool = True,
|
| 198 |
+
http2: bool = False,
|
| 199 |
+
network_backend: AsyncNetworkBackend | None = None,
|
| 200 |
+
) -> None:
|
| 201 |
+
self._proxy_origin = proxy_origin
|
| 202 |
+
self._remote_origin = remote_origin
|
| 203 |
+
self._proxy_auth = proxy_auth
|
| 204 |
+
self._ssl_context = ssl_context
|
| 205 |
+
self._keepalive_expiry = keepalive_expiry
|
| 206 |
+
self._http1 = http1
|
| 207 |
+
self._http2 = http2
|
| 208 |
+
|
| 209 |
+
self._network_backend: AsyncNetworkBackend = (
|
| 210 |
+
AutoBackend() if network_backend is None else network_backend
|
| 211 |
+
)
|
| 212 |
+
self._connect_lock = AsyncLock()
|
| 213 |
+
self._connection: AsyncConnectionInterface | None = None
|
| 214 |
+
self._connect_failed = False
|
| 215 |
+
|
| 216 |
+
async def handle_async_request(self, request: Request) -> Response:
|
| 217 |
+
timeouts = request.extensions.get("timeout", {})
|
| 218 |
+
sni_hostname = request.extensions.get("sni_hostname", None)
|
| 219 |
+
timeout = timeouts.get("connect", None)
|
| 220 |
+
|
| 221 |
+
async with self._connect_lock:
|
| 222 |
+
if self._connection is None:
|
| 223 |
+
try:
|
| 224 |
+
# Connect to the proxy
|
| 225 |
+
kwargs = {
|
| 226 |
+
"host": self._proxy_origin.host.decode("ascii"),
|
| 227 |
+
"port": self._proxy_origin.port,
|
| 228 |
+
"timeout": timeout,
|
| 229 |
+
}
|
| 230 |
+
async with Trace("connect_tcp", logger, request, kwargs) as trace:
|
| 231 |
+
stream = await self._network_backend.connect_tcp(**kwargs)
|
| 232 |
+
trace.return_value = stream
|
| 233 |
+
|
| 234 |
+
# Connect to the remote host using socks5
|
| 235 |
+
kwargs = {
|
| 236 |
+
"stream": stream,
|
| 237 |
+
"host": self._remote_origin.host.decode("ascii"),
|
| 238 |
+
"port": self._remote_origin.port,
|
| 239 |
+
"auth": self._proxy_auth,
|
| 240 |
+
}
|
| 241 |
+
async with Trace(
|
| 242 |
+
"setup_socks5_connection", logger, request, kwargs
|
| 243 |
+
) as trace:
|
| 244 |
+
await _init_socks5_connection(**kwargs)
|
| 245 |
+
trace.return_value = stream
|
| 246 |
+
|
| 247 |
+
# Upgrade the stream to SSL
|
| 248 |
+
if self._remote_origin.scheme == b"https":
|
| 249 |
+
ssl_context = (
|
| 250 |
+
default_ssl_context()
|
| 251 |
+
if self._ssl_context is None
|
| 252 |
+
else self._ssl_context
|
| 253 |
+
)
|
| 254 |
+
alpn_protocols = (
|
| 255 |
+
["http/1.1", "h2"] if self._http2 else ["http/1.1"]
|
| 256 |
+
)
|
| 257 |
+
ssl_context.set_alpn_protocols(alpn_protocols)
|
| 258 |
+
|
| 259 |
+
kwargs = {
|
| 260 |
+
"ssl_context": ssl_context,
|
| 261 |
+
"server_hostname": sni_hostname
|
| 262 |
+
or self._remote_origin.host.decode("ascii"),
|
| 263 |
+
"timeout": timeout,
|
| 264 |
+
}
|
| 265 |
+
async with Trace("start_tls", logger, request, kwargs) as trace:
|
| 266 |
+
stream = await stream.start_tls(**kwargs)
|
| 267 |
+
trace.return_value = stream
|
| 268 |
+
|
| 269 |
+
# Determine if we should be using HTTP/1.1 or HTTP/2
|
| 270 |
+
ssl_object = stream.get_extra_info("ssl_object")
|
| 271 |
+
http2_negotiated = (
|
| 272 |
+
ssl_object is not None
|
| 273 |
+
and ssl_object.selected_alpn_protocol() == "h2"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
# Create the HTTP/1.1 or HTTP/2 connection
|
| 277 |
+
if http2_negotiated or (
|
| 278 |
+
self._http2 and not self._http1
|
| 279 |
+
): # pragma: nocover
|
| 280 |
+
from .http2 import AsyncHTTP2Connection
|
| 281 |
+
|
| 282 |
+
self._connection = AsyncHTTP2Connection(
|
| 283 |
+
origin=self._remote_origin,
|
| 284 |
+
stream=stream,
|
| 285 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 286 |
+
)
|
| 287 |
+
else:
|
| 288 |
+
self._connection = AsyncHTTP11Connection(
|
| 289 |
+
origin=self._remote_origin,
|
| 290 |
+
stream=stream,
|
| 291 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 292 |
+
)
|
| 293 |
+
except Exception as exc:
|
| 294 |
+
self._connect_failed = True
|
| 295 |
+
raise exc
|
| 296 |
+
elif not self._connection.is_available(): # pragma: nocover
|
| 297 |
+
raise ConnectionNotAvailable()
|
| 298 |
+
|
| 299 |
+
return await self._connection.handle_async_request(request)
|
| 300 |
+
|
| 301 |
+
def can_handle_request(self, origin: Origin) -> bool:
|
| 302 |
+
return origin == self._remote_origin
|
| 303 |
+
|
| 304 |
+
async def aclose(self) -> None:
|
| 305 |
+
if self._connection is not None:
|
| 306 |
+
await self._connection.aclose()
|
| 307 |
+
|
| 308 |
+
def is_available(self) -> bool:
|
| 309 |
+
if self._connection is None: # pragma: nocover
|
| 310 |
+
# If HTTP/2 support is enabled, and the resulting connection could
|
| 311 |
+
# end up as HTTP/2 then we should indicate the connection as being
|
| 312 |
+
# available to service multiple requests.
|
| 313 |
+
return (
|
| 314 |
+
self._http2
|
| 315 |
+
and (self._remote_origin.scheme == b"https" or not self._http1)
|
| 316 |
+
and not self._connect_failed
|
| 317 |
+
)
|
| 318 |
+
return self._connection.is_available()
|
| 319 |
+
|
| 320 |
+
def has_expired(self) -> bool:
|
| 321 |
+
if self._connection is None: # pragma: nocover
|
| 322 |
+
return self._connect_failed
|
| 323 |
+
return self._connection.has_expired()
|
| 324 |
+
|
| 325 |
+
def is_idle(self) -> bool:
|
| 326 |
+
if self._connection is None: # pragma: nocover
|
| 327 |
+
return self._connect_failed
|
| 328 |
+
return self._connection.is_idle()
|
| 329 |
+
|
| 330 |
+
def is_closed(self) -> bool:
|
| 331 |
+
if self._connection is None: # pragma: nocover
|
| 332 |
+
return self._connect_failed
|
| 333 |
+
return self._connection.is_closed()
|
| 334 |
+
|
| 335 |
+
def info(self) -> str:
|
| 336 |
+
if self._connection is None: # pragma: nocover
|
| 337 |
+
return "CONNECTION FAILED" if self._connect_failed else "CONNECTING"
|
| 338 |
+
return self._connection.info()
|
| 339 |
+
|
| 340 |
+
def __repr__(self) -> str:
|
| 341 |
+
return f"<{self.__class__.__name__} [{self.info()}]>"
|
.cache/uv/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future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ssl
|
| 4 |
+
import typing
|
| 5 |
+
|
| 6 |
+
import anyio
|
| 7 |
+
|
| 8 |
+
from .._exceptions import (
|
| 9 |
+
ConnectError,
|
| 10 |
+
ConnectTimeout,
|
| 11 |
+
ReadError,
|
| 12 |
+
ReadTimeout,
|
| 13 |
+
WriteError,
|
| 14 |
+
WriteTimeout,
|
| 15 |
+
map_exceptions,
|
| 16 |
+
)
|
| 17 |
+
from .._utils import is_socket_readable
|
| 18 |
+
from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class AnyIOStream(AsyncNetworkStream):
|
| 22 |
+
def __init__(self, stream: anyio.abc.ByteStream) -> None:
|
| 23 |
+
self._stream = stream
|
| 24 |
+
|
| 25 |
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 26 |
+
exc_map = {
|
| 27 |
+
TimeoutError: ReadTimeout,
|
| 28 |
+
anyio.BrokenResourceError: ReadError,
|
| 29 |
+
anyio.ClosedResourceError: ReadError,
|
| 30 |
+
anyio.EndOfStream: ReadError,
|
| 31 |
+
}
|
| 32 |
+
with map_exceptions(exc_map):
|
| 33 |
+
with anyio.fail_after(timeout):
|
| 34 |
+
try:
|
| 35 |
+
return await self._stream.receive(max_bytes=max_bytes)
|
| 36 |
+
except anyio.EndOfStream: # pragma: nocover
|
| 37 |
+
return b""
|
| 38 |
+
|
| 39 |
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 40 |
+
if not buffer:
|
| 41 |
+
return
|
| 42 |
+
|
| 43 |
+
exc_map = {
|
| 44 |
+
TimeoutError: WriteTimeout,
|
| 45 |
+
anyio.BrokenResourceError: WriteError,
|
| 46 |
+
anyio.ClosedResourceError: WriteError,
|
| 47 |
+
}
|
| 48 |
+
with map_exceptions(exc_map):
|
| 49 |
+
with anyio.fail_after(timeout):
|
| 50 |
+
await self._stream.send(item=buffer)
|
| 51 |
+
|
| 52 |
+
async def aclose(self) -> None:
|
| 53 |
+
await self._stream.aclose()
|
| 54 |
+
|
| 55 |
+
async def start_tls(
|
| 56 |
+
self,
|
| 57 |
+
ssl_context: ssl.SSLContext,
|
| 58 |
+
server_hostname: str | None = None,
|
| 59 |
+
timeout: float | None = None,
|
| 60 |
+
) -> AsyncNetworkStream:
|
| 61 |
+
exc_map = {
|
| 62 |
+
TimeoutError: ConnectTimeout,
|
| 63 |
+
anyio.BrokenResourceError: ConnectError,
|
| 64 |
+
anyio.EndOfStream: ConnectError,
|
| 65 |
+
ssl.SSLError: ConnectError,
|
| 66 |
+
}
|
| 67 |
+
with map_exceptions(exc_map):
|
| 68 |
+
try:
|
| 69 |
+
with anyio.fail_after(timeout):
|
| 70 |
+
ssl_stream = await anyio.streams.tls.TLSStream.wrap(
|
| 71 |
+
self._stream,
|
| 72 |
+
ssl_context=ssl_context,
|
| 73 |
+
hostname=server_hostname,
|
| 74 |
+
standard_compatible=False,
|
| 75 |
+
server_side=False,
|
| 76 |
+
)
|
| 77 |
+
except Exception as exc: # pragma: nocover
|
| 78 |
+
await self.aclose()
|
| 79 |
+
raise exc
|
| 80 |
+
return AnyIOStream(ssl_stream)
|
| 81 |
+
|
| 82 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 83 |
+
if info == "ssl_object":
|
| 84 |
+
return self._stream.extra(anyio.streams.tls.TLSAttribute.ssl_object, None)
|
| 85 |
+
if info == "client_addr":
|
| 86 |
+
return self._stream.extra(anyio.abc.SocketAttribute.local_address, None)
|
| 87 |
+
if info == "server_addr":
|
| 88 |
+
return self._stream.extra(anyio.abc.SocketAttribute.remote_address, None)
|
| 89 |
+
if info == "socket":
|
| 90 |
+
return self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None)
|
| 91 |
+
if info == "is_readable":
|
| 92 |
+
sock = self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None)
|
| 93 |
+
return is_socket_readable(sock)
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class AnyIOBackend(AsyncNetworkBackend):
|
| 98 |
+
async def connect_tcp(
|
| 99 |
+
self,
|
| 100 |
+
host: str,
|
| 101 |
+
port: int,
|
| 102 |
+
timeout: float | None = None,
|
| 103 |
+
local_address: str | None = None,
|
| 104 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 105 |
+
) -> AsyncNetworkStream: # pragma: nocover
|
| 106 |
+
if socket_options is None:
|
| 107 |
+
socket_options = []
|
| 108 |
+
exc_map = {
|
| 109 |
+
TimeoutError: ConnectTimeout,
|
| 110 |
+
OSError: ConnectError,
|
| 111 |
+
anyio.BrokenResourceError: ConnectError,
|
| 112 |
+
}
|
| 113 |
+
with map_exceptions(exc_map):
|
| 114 |
+
with anyio.fail_after(timeout):
|
| 115 |
+
stream: anyio.abc.ByteStream = await anyio.connect_tcp(
|
| 116 |
+
remote_host=host,
|
| 117 |
+
remote_port=port,
|
| 118 |
+
local_host=local_address,
|
| 119 |
+
)
|
| 120 |
+
# By default TCP sockets opened in `asyncio` include TCP_NODELAY.
|
| 121 |
+
for option in socket_options:
|
| 122 |
+
stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover
|
| 123 |
+
return AnyIOStream(stream)
|
| 124 |
+
|
| 125 |
+
async def connect_unix_socket(
|
| 126 |
+
self,
|
| 127 |
+
path: str,
|
| 128 |
+
timeout: float | None = None,
|
| 129 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 130 |
+
) -> AsyncNetworkStream: # pragma: nocover
|
| 131 |
+
if socket_options is None:
|
| 132 |
+
socket_options = []
|
| 133 |
+
exc_map = {
|
| 134 |
+
TimeoutError: ConnectTimeout,
|
| 135 |
+
OSError: ConnectError,
|
| 136 |
+
anyio.BrokenResourceError: ConnectError,
|
| 137 |
+
}
|
| 138 |
+
with map_exceptions(exc_map):
|
| 139 |
+
with anyio.fail_after(timeout):
|
| 140 |
+
stream: anyio.abc.ByteStream = await anyio.connect_unix(path)
|
| 141 |
+
for option in socket_options:
|
| 142 |
+
stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover
|
| 143 |
+
return AnyIOStream(stream)
|
| 144 |
+
|
| 145 |
+
async def sleep(self, seconds: float) -> None:
|
| 146 |
+
await anyio.sleep(seconds) # pragma: nocover
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/auto.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
|
| 5 |
+
from .._synchronization import current_async_library
|
| 6 |
+
from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class AutoBackend(AsyncNetworkBackend):
|
| 10 |
+
async def _init_backend(self) -> None:
|
| 11 |
+
if not (hasattr(self, "_backend")):
|
| 12 |
+
backend = current_async_library()
|
| 13 |
+
if backend == "trio":
|
| 14 |
+
from .trio import TrioBackend
|
| 15 |
+
|
| 16 |
+
self._backend: AsyncNetworkBackend = TrioBackend()
|
| 17 |
+
else:
|
| 18 |
+
from .anyio import AnyIOBackend
|
| 19 |
+
|
| 20 |
+
self._backend = AnyIOBackend()
|
| 21 |
+
|
| 22 |
+
async def connect_tcp(
|
| 23 |
+
self,
|
| 24 |
+
host: str,
|
| 25 |
+
port: int,
|
| 26 |
+
timeout: float | None = None,
|
| 27 |
+
local_address: str | None = None,
|
| 28 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 29 |
+
) -> AsyncNetworkStream:
|
| 30 |
+
await self._init_backend()
|
| 31 |
+
return await self._backend.connect_tcp(
|
| 32 |
+
host,
|
| 33 |
+
port,
|
| 34 |
+
timeout=timeout,
|
| 35 |
+
local_address=local_address,
|
| 36 |
+
socket_options=socket_options,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
async def connect_unix_socket(
|
| 40 |
+
self,
|
| 41 |
+
path: str,
|
| 42 |
+
timeout: float | None = None,
|
| 43 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 44 |
+
) -> AsyncNetworkStream: # pragma: nocover
|
| 45 |
+
await self._init_backend()
|
| 46 |
+
return await self._backend.connect_unix_socket(
|
| 47 |
+
path, timeout=timeout, socket_options=socket_options
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
async def sleep(self, seconds: float) -> None: # pragma: nocover
|
| 51 |
+
await self._init_backend()
|
| 52 |
+
return await self._backend.sleep(seconds)
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/base.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ssl
|
| 4 |
+
import time
|
| 5 |
+
import typing
|
| 6 |
+
|
| 7 |
+
SOCKET_OPTION = typing.Union[
|
| 8 |
+
typing.Tuple[int, int, int],
|
| 9 |
+
typing.Tuple[int, int, typing.Union[bytes, bytearray]],
|
| 10 |
+
typing.Tuple[int, int, None, int],
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class NetworkStream:
|
| 15 |
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 16 |
+
raise NotImplementedError() # pragma: nocover
|
| 17 |
+
|
| 18 |
+
def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 19 |
+
raise NotImplementedError() # pragma: nocover
|
| 20 |
+
|
| 21 |
+
def close(self) -> None:
|
| 22 |
+
raise NotImplementedError() # pragma: nocover
|
| 23 |
+
|
| 24 |
+
def start_tls(
|
| 25 |
+
self,
|
| 26 |
+
ssl_context: ssl.SSLContext,
|
| 27 |
+
server_hostname: str | None = None,
|
| 28 |
+
timeout: float | None = None,
|
| 29 |
+
) -> NetworkStream:
|
| 30 |
+
raise NotImplementedError() # pragma: nocover
|
| 31 |
+
|
| 32 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 33 |
+
return None # pragma: nocover
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class NetworkBackend:
|
| 37 |
+
def connect_tcp(
|
| 38 |
+
self,
|
| 39 |
+
host: str,
|
| 40 |
+
port: int,
|
| 41 |
+
timeout: float | None = None,
|
| 42 |
+
local_address: str | None = None,
|
| 43 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 44 |
+
) -> NetworkStream:
|
| 45 |
+
raise NotImplementedError() # pragma: nocover
|
| 46 |
+
|
| 47 |
+
def connect_unix_socket(
|
| 48 |
+
self,
|
| 49 |
+
path: str,
|
| 50 |
+
timeout: float | None = None,
|
| 51 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 52 |
+
) -> NetworkStream:
|
| 53 |
+
raise NotImplementedError() # pragma: nocover
|
| 54 |
+
|
| 55 |
+
def sleep(self, seconds: float) -> None:
|
| 56 |
+
time.sleep(seconds) # pragma: nocover
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class AsyncNetworkStream:
|
| 60 |
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 61 |
+
raise NotImplementedError() # pragma: nocover
|
| 62 |
+
|
| 63 |
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 64 |
+
raise NotImplementedError() # pragma: nocover
|
| 65 |
+
|
| 66 |
+
async def aclose(self) -> None:
|
| 67 |
+
raise NotImplementedError() # pragma: nocover
|
| 68 |
+
|
| 69 |
+
async def start_tls(
|
| 70 |
+
self,
|
| 71 |
+
ssl_context: ssl.SSLContext,
|
| 72 |
+
server_hostname: str | None = None,
|
| 73 |
+
timeout: float | None = None,
|
| 74 |
+
) -> AsyncNetworkStream:
|
| 75 |
+
raise NotImplementedError() # pragma: nocover
|
| 76 |
+
|
| 77 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 78 |
+
return None # pragma: nocover
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class AsyncNetworkBackend:
|
| 82 |
+
async def connect_tcp(
|
| 83 |
+
self,
|
| 84 |
+
host: str,
|
| 85 |
+
port: int,
|
| 86 |
+
timeout: float | None = None,
|
| 87 |
+
local_address: str | None = None,
|
| 88 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 89 |
+
) -> AsyncNetworkStream:
|
| 90 |
+
raise NotImplementedError() # pragma: nocover
|
| 91 |
+
|
| 92 |
+
async def connect_unix_socket(
|
| 93 |
+
self,
|
| 94 |
+
path: str,
|
| 95 |
+
timeout: float | None = None,
|
| 96 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 97 |
+
) -> AsyncNetworkStream:
|
| 98 |
+
raise NotImplementedError() # pragma: nocover
|
| 99 |
+
|
| 100 |
+
async def sleep(self, seconds: float) -> None:
|
| 101 |
+
raise NotImplementedError() # pragma: nocover
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/mock.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ssl
|
| 4 |
+
import typing
|
| 5 |
+
|
| 6 |
+
from .._exceptions import ReadError
|
| 7 |
+
from .base import (
|
| 8 |
+
SOCKET_OPTION,
|
| 9 |
+
AsyncNetworkBackend,
|
| 10 |
+
AsyncNetworkStream,
|
| 11 |
+
NetworkBackend,
|
| 12 |
+
NetworkStream,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MockSSLObject:
|
| 17 |
+
def __init__(self, http2: bool):
|
| 18 |
+
self._http2 = http2
|
| 19 |
+
|
| 20 |
+
def selected_alpn_protocol(self) -> str:
|
| 21 |
+
return "h2" if self._http2 else "http/1.1"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class MockStream(NetworkStream):
|
| 25 |
+
def __init__(self, buffer: list[bytes], http2: bool = False) -> None:
|
| 26 |
+
self._buffer = buffer
|
| 27 |
+
self._http2 = http2
|
| 28 |
+
self._closed = False
|
| 29 |
+
|
| 30 |
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 31 |
+
if self._closed:
|
| 32 |
+
raise ReadError("Connection closed")
|
| 33 |
+
if not self._buffer:
|
| 34 |
+
return b""
|
| 35 |
+
return self._buffer.pop(0)
|
| 36 |
+
|
| 37 |
+
def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
def close(self) -> None:
|
| 41 |
+
self._closed = True
|
| 42 |
+
|
| 43 |
+
def start_tls(
|
| 44 |
+
self,
|
| 45 |
+
ssl_context: ssl.SSLContext,
|
| 46 |
+
server_hostname: str | None = None,
|
| 47 |
+
timeout: float | None = None,
|
| 48 |
+
) -> NetworkStream:
|
| 49 |
+
return self
|
| 50 |
+
|
| 51 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 52 |
+
return MockSSLObject(http2=self._http2) if info == "ssl_object" else None
|
| 53 |
+
|
| 54 |
+
def __repr__(self) -> str:
|
| 55 |
+
return "<httpcore.MockStream>"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class MockBackend(NetworkBackend):
|
| 59 |
+
def __init__(self, buffer: list[bytes], http2: bool = False) -> None:
|
| 60 |
+
self._buffer = buffer
|
| 61 |
+
self._http2 = http2
|
| 62 |
+
|
| 63 |
+
def connect_tcp(
|
| 64 |
+
self,
|
| 65 |
+
host: str,
|
| 66 |
+
port: int,
|
| 67 |
+
timeout: float | None = None,
|
| 68 |
+
local_address: str | None = None,
|
| 69 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 70 |
+
) -> NetworkStream:
|
| 71 |
+
return MockStream(list(self._buffer), http2=self._http2)
|
| 72 |
+
|
| 73 |
+
def connect_unix_socket(
|
| 74 |
+
self,
|
| 75 |
+
path: str,
|
| 76 |
+
timeout: float | None = None,
|
| 77 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 78 |
+
) -> NetworkStream:
|
| 79 |
+
return MockStream(list(self._buffer), http2=self._http2)
|
| 80 |
+
|
| 81 |
+
def sleep(self, seconds: float) -> None:
|
| 82 |
+
pass
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class AsyncMockStream(AsyncNetworkStream):
|
| 86 |
+
def __init__(self, buffer: list[bytes], http2: bool = False) -> None:
|
| 87 |
+
self._buffer = buffer
|
| 88 |
+
self._http2 = http2
|
| 89 |
+
self._closed = False
|
| 90 |
+
|
| 91 |
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 92 |
+
if self._closed:
|
| 93 |
+
raise ReadError("Connection closed")
|
| 94 |
+
if not self._buffer:
|
| 95 |
+
return b""
|
| 96 |
+
return self._buffer.pop(0)
|
| 97 |
+
|
| 98 |
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 99 |
+
pass
|
| 100 |
+
|
| 101 |
+
async def aclose(self) -> None:
|
| 102 |
+
self._closed = True
|
| 103 |
+
|
| 104 |
+
async def start_tls(
|
| 105 |
+
self,
|
| 106 |
+
ssl_context: ssl.SSLContext,
|
| 107 |
+
server_hostname: str | None = None,
|
| 108 |
+
timeout: float | None = None,
|
| 109 |
+
) -> AsyncNetworkStream:
|
| 110 |
+
return self
|
| 111 |
+
|
| 112 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 113 |
+
return MockSSLObject(http2=self._http2) if info == "ssl_object" else None
|
| 114 |
+
|
| 115 |
+
def __repr__(self) -> str:
|
| 116 |
+
return "<httpcore.AsyncMockStream>"
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class AsyncMockBackend(AsyncNetworkBackend):
|
| 120 |
+
def __init__(self, buffer: list[bytes], http2: bool = False) -> None:
|
| 121 |
+
self._buffer = buffer
|
| 122 |
+
self._http2 = http2
|
| 123 |
+
|
| 124 |
+
async def connect_tcp(
|
| 125 |
+
self,
|
| 126 |
+
host: str,
|
| 127 |
+
port: int,
|
| 128 |
+
timeout: float | None = None,
|
| 129 |
+
local_address: str | None = None,
|
| 130 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 131 |
+
) -> AsyncNetworkStream:
|
| 132 |
+
return AsyncMockStream(list(self._buffer), http2=self._http2)
|
| 133 |
+
|
| 134 |
+
async def connect_unix_socket(
|
| 135 |
+
self,
|
| 136 |
+
path: str,
|
| 137 |
+
timeout: float | None = None,
|
| 138 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 139 |
+
) -> AsyncNetworkStream:
|
| 140 |
+
return AsyncMockStream(list(self._buffer), http2=self._http2)
|
| 141 |
+
|
| 142 |
+
async def sleep(self, seconds: float) -> None:
|
| 143 |
+
pass
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/sync.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import socket
|
| 5 |
+
import ssl
|
| 6 |
+
import sys
|
| 7 |
+
import typing
|
| 8 |
+
|
| 9 |
+
from .._exceptions import (
|
| 10 |
+
ConnectError,
|
| 11 |
+
ConnectTimeout,
|
| 12 |
+
ExceptionMapping,
|
| 13 |
+
ReadError,
|
| 14 |
+
ReadTimeout,
|
| 15 |
+
WriteError,
|
| 16 |
+
WriteTimeout,
|
| 17 |
+
map_exceptions,
|
| 18 |
+
)
|
| 19 |
+
from .._utils import is_socket_readable
|
| 20 |
+
from .base import SOCKET_OPTION, NetworkBackend, NetworkStream
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TLSinTLSStream(NetworkStream): # pragma: no cover
|
| 24 |
+
"""
|
| 25 |
+
Because the standard `SSLContext.wrap_socket` method does
|
| 26 |
+
not work for `SSLSocket` objects, we need this class
|
| 27 |
+
to implement TLS stream using an underlying `SSLObject`
|
| 28 |
+
instance in order to support TLS on top of TLS.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
# Defined in RFC 8449
|
| 32 |
+
TLS_RECORD_SIZE = 16384
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
sock: socket.socket,
|
| 37 |
+
ssl_context: ssl.SSLContext,
|
| 38 |
+
server_hostname: str | None = None,
|
| 39 |
+
timeout: float | None = None,
|
| 40 |
+
):
|
| 41 |
+
self._sock = sock
|
| 42 |
+
self._incoming = ssl.MemoryBIO()
|
| 43 |
+
self._outgoing = ssl.MemoryBIO()
|
| 44 |
+
|
| 45 |
+
self.ssl_obj = ssl_context.wrap_bio(
|
| 46 |
+
incoming=self._incoming,
|
| 47 |
+
outgoing=self._outgoing,
|
| 48 |
+
server_hostname=server_hostname,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
self._sock.settimeout(timeout)
|
| 52 |
+
self._perform_io(self.ssl_obj.do_handshake)
|
| 53 |
+
|
| 54 |
+
def _perform_io(
|
| 55 |
+
self,
|
| 56 |
+
func: typing.Callable[..., typing.Any],
|
| 57 |
+
) -> typing.Any:
|
| 58 |
+
ret = None
|
| 59 |
+
|
| 60 |
+
while True:
|
| 61 |
+
errno = None
|
| 62 |
+
try:
|
| 63 |
+
ret = func()
|
| 64 |
+
except (ssl.SSLWantReadError, ssl.SSLWantWriteError) as e:
|
| 65 |
+
errno = e.errno
|
| 66 |
+
|
| 67 |
+
self._sock.sendall(self._outgoing.read())
|
| 68 |
+
|
| 69 |
+
if errno == ssl.SSL_ERROR_WANT_READ:
|
| 70 |
+
buf = self._sock.recv(self.TLS_RECORD_SIZE)
|
| 71 |
+
|
| 72 |
+
if buf:
|
| 73 |
+
self._incoming.write(buf)
|
| 74 |
+
else:
|
| 75 |
+
self._incoming.write_eof()
|
| 76 |
+
if errno is None:
|
| 77 |
+
return ret
|
| 78 |
+
|
| 79 |
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 80 |
+
exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError}
|
| 81 |
+
with map_exceptions(exc_map):
|
| 82 |
+
self._sock.settimeout(timeout)
|
| 83 |
+
return typing.cast(
|
| 84 |
+
bytes, self._perform_io(functools.partial(self.ssl_obj.read, max_bytes))
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 88 |
+
exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError}
|
| 89 |
+
with map_exceptions(exc_map):
|
| 90 |
+
self._sock.settimeout(timeout)
|
| 91 |
+
while buffer:
|
| 92 |
+
nsent = self._perform_io(functools.partial(self.ssl_obj.write, buffer))
|
| 93 |
+
buffer = buffer[nsent:]
|
| 94 |
+
|
| 95 |
+
def close(self) -> None:
|
| 96 |
+
self._sock.close()
|
| 97 |
+
|
| 98 |
+
def start_tls(
|
| 99 |
+
self,
|
| 100 |
+
ssl_context: ssl.SSLContext,
|
| 101 |
+
server_hostname: str | None = None,
|
| 102 |
+
timeout: float | None = None,
|
| 103 |
+
) -> NetworkStream:
|
| 104 |
+
raise NotImplementedError()
|
| 105 |
+
|
| 106 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 107 |
+
if info == "ssl_object":
|
| 108 |
+
return self.ssl_obj
|
| 109 |
+
if info == "client_addr":
|
| 110 |
+
return self._sock.getsockname()
|
| 111 |
+
if info == "server_addr":
|
| 112 |
+
return self._sock.getpeername()
|
| 113 |
+
if info == "socket":
|
| 114 |
+
return self._sock
|
| 115 |
+
if info == "is_readable":
|
| 116 |
+
return is_socket_readable(self._sock)
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class SyncStream(NetworkStream):
|
| 121 |
+
def __init__(self, sock: socket.socket) -> None:
|
| 122 |
+
self._sock = sock
|
| 123 |
+
|
| 124 |
+
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 125 |
+
exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError}
|
| 126 |
+
with map_exceptions(exc_map):
|
| 127 |
+
self._sock.settimeout(timeout)
|
| 128 |
+
return self._sock.recv(max_bytes)
|
| 129 |
+
|
| 130 |
+
def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 131 |
+
if not buffer:
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError}
|
| 135 |
+
with map_exceptions(exc_map):
|
| 136 |
+
while buffer:
|
| 137 |
+
self._sock.settimeout(timeout)
|
| 138 |
+
n = self._sock.send(buffer)
|
| 139 |
+
buffer = buffer[n:]
|
| 140 |
+
|
| 141 |
+
def close(self) -> None:
|
| 142 |
+
self._sock.close()
|
| 143 |
+
|
| 144 |
+
def start_tls(
|
| 145 |
+
self,
|
| 146 |
+
ssl_context: ssl.SSLContext,
|
| 147 |
+
server_hostname: str | None = None,
|
| 148 |
+
timeout: float | None = None,
|
| 149 |
+
) -> NetworkStream:
|
| 150 |
+
exc_map: ExceptionMapping = {
|
| 151 |
+
socket.timeout: ConnectTimeout,
|
| 152 |
+
OSError: ConnectError,
|
| 153 |
+
}
|
| 154 |
+
with map_exceptions(exc_map):
|
| 155 |
+
try:
|
| 156 |
+
if isinstance(self._sock, ssl.SSLSocket): # pragma: no cover
|
| 157 |
+
# If the underlying socket has already been upgraded
|
| 158 |
+
# to the TLS layer (i.e. is an instance of SSLSocket),
|
| 159 |
+
# we need some additional smarts to support TLS-in-TLS.
|
| 160 |
+
return TLSinTLSStream(
|
| 161 |
+
self._sock, ssl_context, server_hostname, timeout
|
| 162 |
+
)
|
| 163 |
+
else:
|
| 164 |
+
self._sock.settimeout(timeout)
|
| 165 |
+
sock = ssl_context.wrap_socket(
|
| 166 |
+
self._sock, server_hostname=server_hostname
|
| 167 |
+
)
|
| 168 |
+
except Exception as exc: # pragma: nocover
|
| 169 |
+
self.close()
|
| 170 |
+
raise exc
|
| 171 |
+
return SyncStream(sock)
|
| 172 |
+
|
| 173 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 174 |
+
if info == "ssl_object" and isinstance(self._sock, ssl.SSLSocket):
|
| 175 |
+
return self._sock._sslobj # type: ignore
|
| 176 |
+
if info == "client_addr":
|
| 177 |
+
return self._sock.getsockname()
|
| 178 |
+
if info == "server_addr":
|
| 179 |
+
return self._sock.getpeername()
|
| 180 |
+
if info == "socket":
|
| 181 |
+
return self._sock
|
| 182 |
+
if info == "is_readable":
|
| 183 |
+
return is_socket_readable(self._sock)
|
| 184 |
+
return None
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class SyncBackend(NetworkBackend):
|
| 188 |
+
def connect_tcp(
|
| 189 |
+
self,
|
| 190 |
+
host: str,
|
| 191 |
+
port: int,
|
| 192 |
+
timeout: float | None = None,
|
| 193 |
+
local_address: str | None = None,
|
| 194 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 195 |
+
) -> NetworkStream:
|
| 196 |
+
# Note that we automatically include `TCP_NODELAY`
|
| 197 |
+
# in addition to any other custom socket options.
|
| 198 |
+
if socket_options is None:
|
| 199 |
+
socket_options = [] # pragma: no cover
|
| 200 |
+
address = (host, port)
|
| 201 |
+
source_address = None if local_address is None else (local_address, 0)
|
| 202 |
+
exc_map: ExceptionMapping = {
|
| 203 |
+
socket.timeout: ConnectTimeout,
|
| 204 |
+
OSError: ConnectError,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
with map_exceptions(exc_map):
|
| 208 |
+
sock = socket.create_connection(
|
| 209 |
+
address,
|
| 210 |
+
timeout,
|
| 211 |
+
source_address=source_address,
|
| 212 |
+
)
|
| 213 |
+
for option in socket_options:
|
| 214 |
+
sock.setsockopt(*option) # pragma: no cover
|
| 215 |
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
| 216 |
+
return SyncStream(sock)
|
| 217 |
+
|
| 218 |
+
def connect_unix_socket(
|
| 219 |
+
self,
|
| 220 |
+
path: str,
|
| 221 |
+
timeout: float | None = None,
|
| 222 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 223 |
+
) -> NetworkStream: # pragma: nocover
|
| 224 |
+
if sys.platform == "win32":
|
| 225 |
+
raise RuntimeError(
|
| 226 |
+
"Attempted to connect to a UNIX socket on a Windows system."
|
| 227 |
+
)
|
| 228 |
+
if socket_options is None:
|
| 229 |
+
socket_options = []
|
| 230 |
+
|
| 231 |
+
exc_map: ExceptionMapping = {
|
| 232 |
+
socket.timeout: ConnectTimeout,
|
| 233 |
+
OSError: ConnectError,
|
| 234 |
+
}
|
| 235 |
+
with map_exceptions(exc_map):
|
| 236 |
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
| 237 |
+
for option in socket_options:
|
| 238 |
+
sock.setsockopt(*option)
|
| 239 |
+
sock.settimeout(timeout)
|
| 240 |
+
sock.connect(path)
|
| 241 |
+
return SyncStream(sock)
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_backends/trio.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ssl
|
| 4 |
+
import typing
|
| 5 |
+
|
| 6 |
+
import trio
|
| 7 |
+
|
| 8 |
+
from .._exceptions import (
|
| 9 |
+
ConnectError,
|
| 10 |
+
ConnectTimeout,
|
| 11 |
+
ExceptionMapping,
|
| 12 |
+
ReadError,
|
| 13 |
+
ReadTimeout,
|
| 14 |
+
WriteError,
|
| 15 |
+
WriteTimeout,
|
| 16 |
+
map_exceptions,
|
| 17 |
+
)
|
| 18 |
+
from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TrioStream(AsyncNetworkStream):
|
| 22 |
+
def __init__(self, stream: trio.abc.Stream) -> None:
|
| 23 |
+
self._stream = stream
|
| 24 |
+
|
| 25 |
+
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
|
| 26 |
+
timeout_or_inf = float("inf") if timeout is None else timeout
|
| 27 |
+
exc_map: ExceptionMapping = {
|
| 28 |
+
trio.TooSlowError: ReadTimeout,
|
| 29 |
+
trio.BrokenResourceError: ReadError,
|
| 30 |
+
trio.ClosedResourceError: ReadError,
|
| 31 |
+
}
|
| 32 |
+
with map_exceptions(exc_map):
|
| 33 |
+
with trio.fail_after(timeout_or_inf):
|
| 34 |
+
data: bytes = await self._stream.receive_some(max_bytes=max_bytes)
|
| 35 |
+
return data
|
| 36 |
+
|
| 37 |
+
async def write(self, buffer: bytes, timeout: float | None = None) -> None:
|
| 38 |
+
if not buffer:
|
| 39 |
+
return
|
| 40 |
+
|
| 41 |
+
timeout_or_inf = float("inf") if timeout is None else timeout
|
| 42 |
+
exc_map: ExceptionMapping = {
|
| 43 |
+
trio.TooSlowError: WriteTimeout,
|
| 44 |
+
trio.BrokenResourceError: WriteError,
|
| 45 |
+
trio.ClosedResourceError: WriteError,
|
| 46 |
+
}
|
| 47 |
+
with map_exceptions(exc_map):
|
| 48 |
+
with trio.fail_after(timeout_or_inf):
|
| 49 |
+
await self._stream.send_all(data=buffer)
|
| 50 |
+
|
| 51 |
+
async def aclose(self) -> None:
|
| 52 |
+
await self._stream.aclose()
|
| 53 |
+
|
| 54 |
+
async def start_tls(
|
| 55 |
+
self,
|
| 56 |
+
ssl_context: ssl.SSLContext,
|
| 57 |
+
server_hostname: str | None = None,
|
| 58 |
+
timeout: float | None = None,
|
| 59 |
+
) -> AsyncNetworkStream:
|
| 60 |
+
timeout_or_inf = float("inf") if timeout is None else timeout
|
| 61 |
+
exc_map: ExceptionMapping = {
|
| 62 |
+
trio.TooSlowError: ConnectTimeout,
|
| 63 |
+
trio.BrokenResourceError: ConnectError,
|
| 64 |
+
}
|
| 65 |
+
ssl_stream = trio.SSLStream(
|
| 66 |
+
self._stream,
|
| 67 |
+
ssl_context=ssl_context,
|
| 68 |
+
server_hostname=server_hostname,
|
| 69 |
+
https_compatible=True,
|
| 70 |
+
server_side=False,
|
| 71 |
+
)
|
| 72 |
+
with map_exceptions(exc_map):
|
| 73 |
+
try:
|
| 74 |
+
with trio.fail_after(timeout_or_inf):
|
| 75 |
+
await ssl_stream.do_handshake()
|
| 76 |
+
except Exception as exc: # pragma: nocover
|
| 77 |
+
await self.aclose()
|
| 78 |
+
raise exc
|
| 79 |
+
return TrioStream(ssl_stream)
|
| 80 |
+
|
| 81 |
+
def get_extra_info(self, info: str) -> typing.Any:
|
| 82 |
+
if info == "ssl_object" and isinstance(self._stream, trio.SSLStream):
|
| 83 |
+
# Type checkers cannot see `_ssl_object` attribute because trio._ssl.SSLStream uses __getattr__/__setattr__.
|
| 84 |
+
# Tracked at https://github.com/python-trio/trio/issues/542
|
| 85 |
+
return self._stream._ssl_object # type: ignore[attr-defined]
|
| 86 |
+
if info == "client_addr":
|
| 87 |
+
return self._get_socket_stream().socket.getsockname()
|
| 88 |
+
if info == "server_addr":
|
| 89 |
+
return self._get_socket_stream().socket.getpeername()
|
| 90 |
+
if info == "socket":
|
| 91 |
+
stream = self._stream
|
| 92 |
+
while isinstance(stream, trio.SSLStream):
|
| 93 |
+
stream = stream.transport_stream
|
| 94 |
+
assert isinstance(stream, trio.SocketStream)
|
| 95 |
+
return stream.socket
|
| 96 |
+
if info == "is_readable":
|
| 97 |
+
socket = self.get_extra_info("socket")
|
| 98 |
+
return socket.is_readable()
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
def _get_socket_stream(self) -> trio.SocketStream:
|
| 102 |
+
stream = self._stream
|
| 103 |
+
while isinstance(stream, trio.SSLStream):
|
| 104 |
+
stream = stream.transport_stream
|
| 105 |
+
assert isinstance(stream, trio.SocketStream)
|
| 106 |
+
return stream
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class TrioBackend(AsyncNetworkBackend):
|
| 110 |
+
async def connect_tcp(
|
| 111 |
+
self,
|
| 112 |
+
host: str,
|
| 113 |
+
port: int,
|
| 114 |
+
timeout: float | None = None,
|
| 115 |
+
local_address: str | None = None,
|
| 116 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 117 |
+
) -> AsyncNetworkStream:
|
| 118 |
+
# By default for TCP sockets, trio enables TCP_NODELAY.
|
| 119 |
+
# https://trio.readthedocs.io/en/stable/reference-io.html#trio.SocketStream
|
| 120 |
+
if socket_options is None:
|
| 121 |
+
socket_options = [] # pragma: no cover
|
| 122 |
+
timeout_or_inf = float("inf") if timeout is None else timeout
|
| 123 |
+
exc_map: ExceptionMapping = {
|
| 124 |
+
trio.TooSlowError: ConnectTimeout,
|
| 125 |
+
trio.BrokenResourceError: ConnectError,
|
| 126 |
+
OSError: ConnectError,
|
| 127 |
+
}
|
| 128 |
+
with map_exceptions(exc_map):
|
| 129 |
+
with trio.fail_after(timeout_or_inf):
|
| 130 |
+
stream: trio.abc.Stream = await trio.open_tcp_stream(
|
| 131 |
+
host=host, port=port, local_address=local_address
|
| 132 |
+
)
|
| 133 |
+
for option in socket_options:
|
| 134 |
+
stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover
|
| 135 |
+
return TrioStream(stream)
|
| 136 |
+
|
| 137 |
+
async def connect_unix_socket(
|
| 138 |
+
self,
|
| 139 |
+
path: str,
|
| 140 |
+
timeout: float | None = None,
|
| 141 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 142 |
+
) -> AsyncNetworkStream: # pragma: nocover
|
| 143 |
+
if socket_options is None:
|
| 144 |
+
socket_options = []
|
| 145 |
+
timeout_or_inf = float("inf") if timeout is None else timeout
|
| 146 |
+
exc_map: ExceptionMapping = {
|
| 147 |
+
trio.TooSlowError: ConnectTimeout,
|
| 148 |
+
trio.BrokenResourceError: ConnectError,
|
| 149 |
+
OSError: ConnectError,
|
| 150 |
+
}
|
| 151 |
+
with map_exceptions(exc_map):
|
| 152 |
+
with trio.fail_after(timeout_or_inf):
|
| 153 |
+
stream: trio.abc.Stream = await trio.open_unix_socket(path)
|
| 154 |
+
for option in socket_options:
|
| 155 |
+
stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover
|
| 156 |
+
return TrioStream(stream)
|
| 157 |
+
|
| 158 |
+
async def sleep(self, seconds: float) -> None:
|
| 159 |
+
await trio.sleep(seconds) # pragma: nocover
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_exceptions.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import typing
|
| 3 |
+
|
| 4 |
+
ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]]
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@contextlib.contextmanager
|
| 8 |
+
def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]:
|
| 9 |
+
try:
|
| 10 |
+
yield
|
| 11 |
+
except Exception as exc: # noqa: PIE786
|
| 12 |
+
for from_exc, to_exc in map.items():
|
| 13 |
+
if isinstance(exc, from_exc):
|
| 14 |
+
raise to_exc(exc) from exc
|
| 15 |
+
raise # pragma: nocover
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ConnectionNotAvailable(Exception):
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ProxyError(Exception):
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class UnsupportedProtocol(Exception):
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ProtocolError(Exception):
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class RemoteProtocolError(ProtocolError):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class LocalProtocolError(ProtocolError):
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# Timeout errors
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TimeoutException(Exception):
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PoolTimeout(TimeoutException):
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ConnectTimeout(TimeoutException):
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ReadTimeout(TimeoutException):
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class WriteTimeout(TimeoutException):
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# Network errors
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class NetworkError(Exception):
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ConnectError(NetworkError):
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class ReadError(NetworkError):
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class WriteError(NetworkError):
|
| 81 |
+
pass
|
.cache/uv/archive-v0/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import ssl
|
| 5 |
+
import typing
|
| 6 |
+
import urllib.parse
|
| 7 |
+
|
| 8 |
+
# Functions for typechecking...
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
ByteOrStr = typing.Union[bytes, str]
|
| 12 |
+
HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]]
|
| 13 |
+
HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr]
|
| 14 |
+
HeaderTypes = typing.Union[HeadersAsSequence, HeadersAsMapping, None]
|
| 15 |
+
|
| 16 |
+
Extensions = typing.MutableMapping[str, typing.Any]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def enforce_bytes(value: bytes | str, *, name: str) -> bytes:
|
| 20 |
+
"""
|
| 21 |
+
Any arguments that are ultimately represented as bytes can be specified
|
| 22 |
+
either as bytes or as strings.
|
| 23 |
+
|
| 24 |
+
However we enforce that any string arguments must only contain characters in
|
| 25 |
+
the plain ASCII range. chr(0)...chr(127). If you need to use characters
|
| 26 |
+
outside that range then be precise, and use a byte-wise argument.
|
| 27 |
+
"""
|
| 28 |
+
if isinstance(value, str):
|
| 29 |
+
try:
|
| 30 |
+
return value.encode("ascii")
|
| 31 |
+
except UnicodeEncodeError:
|
| 32 |
+
raise TypeError(f"{name} strings may not include unicode characters.")
|
| 33 |
+
elif isinstance(value, bytes):
|
| 34 |
+
return value
|
| 35 |
+
|
| 36 |
+
seen_type = type(value).__name__
|
| 37 |
+
raise TypeError(f"{name} must be bytes or str, but got {seen_type}.")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def enforce_url(value: URL | bytes | str, *, name: str) -> URL:
|
| 41 |
+
"""
|
| 42 |
+
Type check for URL parameters.
|
| 43 |
+
"""
|
| 44 |
+
if isinstance(value, (bytes, str)):
|
| 45 |
+
return URL(value)
|
| 46 |
+
elif isinstance(value, URL):
|
| 47 |
+
return value
|
| 48 |
+
|
| 49 |
+
seen_type = type(value).__name__
|
| 50 |
+
raise TypeError(f"{name} must be a URL, bytes, or str, but got {seen_type}.")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def enforce_headers(
|
| 54 |
+
value: HeadersAsMapping | HeadersAsSequence | None = None, *, name: str
|
| 55 |
+
) -> list[tuple[bytes, bytes]]:
|
| 56 |
+
"""
|
| 57 |
+
Convienence function that ensure all items in request or response headers
|
| 58 |
+
are either bytes or strings in the plain ASCII range.
|
| 59 |
+
"""
|
| 60 |
+
if value is None:
|
| 61 |
+
return []
|
| 62 |
+
elif isinstance(value, typing.Mapping):
|
| 63 |
+
return [
|
| 64 |
+
(
|
| 65 |
+
enforce_bytes(k, name="header name"),
|
| 66 |
+
enforce_bytes(v, name="header value"),
|
| 67 |
+
)
|
| 68 |
+
for k, v in value.items()
|
| 69 |
+
]
|
| 70 |
+
elif isinstance(value, typing.Sequence):
|
| 71 |
+
return [
|
| 72 |
+
(
|
| 73 |
+
enforce_bytes(k, name="header name"),
|
| 74 |
+
enforce_bytes(v, name="header value"),
|
| 75 |
+
)
|
| 76 |
+
for k, v in value
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
seen_type = type(value).__name__
|
| 80 |
+
raise TypeError(
|
| 81 |
+
f"{name} must be a mapping or sequence of two-tuples, but got {seen_type}."
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def enforce_stream(
|
| 86 |
+
value: bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes] | None,
|
| 87 |
+
*,
|
| 88 |
+
name: str,
|
| 89 |
+
) -> typing.Iterable[bytes] | typing.AsyncIterable[bytes]:
|
| 90 |
+
if value is None:
|
| 91 |
+
return ByteStream(b"")
|
| 92 |
+
elif isinstance(value, bytes):
|
| 93 |
+
return ByteStream(value)
|
| 94 |
+
return value
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# * https://tools.ietf.org/html/rfc3986#section-3.2.3
|
| 98 |
+
# * https://url.spec.whatwg.org/#url-miscellaneous
|
| 99 |
+
# * https://url.spec.whatwg.org/#scheme-state
|
| 100 |
+
DEFAULT_PORTS = {
|
| 101 |
+
b"ftp": 21,
|
| 102 |
+
b"http": 80,
|
| 103 |
+
b"https": 443,
|
| 104 |
+
b"ws": 80,
|
| 105 |
+
b"wss": 443,
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def include_request_headers(
|
| 110 |
+
headers: list[tuple[bytes, bytes]],
|
| 111 |
+
*,
|
| 112 |
+
url: "URL",
|
| 113 |
+
content: None | bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes],
|
| 114 |
+
) -> list[tuple[bytes, bytes]]:
|
| 115 |
+
headers_set = set(k.lower() for k, v in headers)
|
| 116 |
+
|
| 117 |
+
if b"host" not in headers_set:
|
| 118 |
+
default_port = DEFAULT_PORTS.get(url.scheme)
|
| 119 |
+
if url.port is None or url.port == default_port:
|
| 120 |
+
header_value = url.host
|
| 121 |
+
else:
|
| 122 |
+
header_value = b"%b:%d" % (url.host, url.port)
|
| 123 |
+
headers = [(b"Host", header_value)] + headers
|
| 124 |
+
|
| 125 |
+
if (
|
| 126 |
+
content is not None
|
| 127 |
+
and b"content-length" not in headers_set
|
| 128 |
+
and b"transfer-encoding" not in headers_set
|
| 129 |
+
):
|
| 130 |
+
if isinstance(content, bytes):
|
| 131 |
+
content_length = str(len(content)).encode("ascii")
|
| 132 |
+
headers += [(b"Content-Length", content_length)]
|
| 133 |
+
else:
|
| 134 |
+
headers += [(b"Transfer-Encoding", b"chunked")] # pragma: nocover
|
| 135 |
+
|
| 136 |
+
return headers
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# Interfaces for byte streams...
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class ByteStream:
|
| 143 |
+
"""
|
| 144 |
+
A container for non-streaming content, and that supports both sync and async
|
| 145 |
+
stream iteration.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
def __init__(self, content: bytes) -> None:
|
| 149 |
+
self._content = content
|
| 150 |
+
|
| 151 |
+
def __iter__(self) -> typing.Iterator[bytes]:
|
| 152 |
+
yield self._content
|
| 153 |
+
|
| 154 |
+
async def __aiter__(self) -> typing.AsyncIterator[bytes]:
|
| 155 |
+
yield self._content
|
| 156 |
+
|
| 157 |
+
def __repr__(self) -> str:
|
| 158 |
+
return f"<{self.__class__.__name__} [{len(self._content)} bytes]>"
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class Origin:
|
| 162 |
+
def __init__(self, scheme: bytes, host: bytes, port: int) -> None:
|
| 163 |
+
self.scheme = scheme
|
| 164 |
+
self.host = host
|
| 165 |
+
self.port = port
|
| 166 |
+
|
| 167 |
+
def __eq__(self, other: typing.Any) -> bool:
|
| 168 |
+
return (
|
| 169 |
+
isinstance(other, Origin)
|
| 170 |
+
and self.scheme == other.scheme
|
| 171 |
+
and self.host == other.host
|
| 172 |
+
and self.port == other.port
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
def __str__(self) -> str:
|
| 176 |
+
scheme = self.scheme.decode("ascii")
|
| 177 |
+
host = self.host.decode("ascii")
|
| 178 |
+
port = str(self.port)
|
| 179 |
+
return f"{scheme}://{host}:{port}"
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class URL:
|
| 183 |
+
"""
|
| 184 |
+
Represents the URL against which an HTTP request may be made.
|
| 185 |
+
|
| 186 |
+
The URL may either be specified as a plain string, for convienence:
|
| 187 |
+
|
| 188 |
+
```python
|
| 189 |
+
url = httpcore.URL("https://www.example.com/")
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
Or be constructed with explicitily pre-parsed components:
|
| 193 |
+
|
| 194 |
+
```python
|
| 195 |
+
url = httpcore.URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/')
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
Using this second more explicit style allows integrations that are using
|
| 199 |
+
`httpcore` to pass through URLs that have already been parsed in order to use
|
| 200 |
+
libraries such as `rfc-3986` rather than relying on the stdlib. It also ensures
|
| 201 |
+
that URL parsing is treated identically at both the networking level and at any
|
| 202 |
+
higher layers of abstraction.
|
| 203 |
+
|
| 204 |
+
The four components are important here, as they allow the URL to be precisely
|
| 205 |
+
specified in a pre-parsed format. They also allow certain types of request to
|
| 206 |
+
be created that could not otherwise be expressed.
|
| 207 |
+
|
| 208 |
+
For example, an HTTP request to `http://www.example.com/` forwarded via a proxy
|
| 209 |
+
at `http://localhost:8080`...
|
| 210 |
+
|
| 211 |
+
```python
|
| 212 |
+
# Constructs an HTTP request with a complete URL as the target:
|
| 213 |
+
# GET https://www.example.com/ HTTP/1.1
|
| 214 |
+
url = httpcore.URL(
|
| 215 |
+
scheme=b'http',
|
| 216 |
+
host=b'localhost',
|
| 217 |
+
port=8080,
|
| 218 |
+
target=b'https://www.example.com/'
|
| 219 |
+
)
|
| 220 |
+
request = httpcore.Request(
|
| 221 |
+
method="GET",
|
| 222 |
+
url=url
|
| 223 |
+
)
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
Another example is constructing an `OPTIONS *` request...
|
| 227 |
+
|
| 228 |
+
```python
|
| 229 |
+
# Constructs an 'OPTIONS *' HTTP request:
|
| 230 |
+
# OPTIONS * HTTP/1.1
|
| 231 |
+
url = httpcore.URL(scheme=b'https', host=b'www.example.com', target=b'*')
|
| 232 |
+
request = httpcore.Request(method="OPTIONS", url=url)
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
This kind of request is not possible to formulate with a URL string,
|
| 236 |
+
because the `/` delimiter is always used to demark the target from the
|
| 237 |
+
host/port portion of the URL.
|
| 238 |
+
|
| 239 |
+
For convenience, string-like arguments may be specified either as strings or
|
| 240 |
+
as bytes. However, once a request is being issue over-the-wire, the URL
|
| 241 |
+
components are always ultimately required to be a bytewise representation.
|
| 242 |
+
|
| 243 |
+
In order to avoid any ambiguity over character encodings, when strings are used
|
| 244 |
+
as arguments, they must be strictly limited to the ASCII range `chr(0)`-`chr(127)`.
|
| 245 |
+
If you require a bytewise representation that is outside this range you must
|
| 246 |
+
handle the character encoding directly, and pass a bytes instance.
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
def __init__(
|
| 250 |
+
self,
|
| 251 |
+
url: bytes | str = "",
|
| 252 |
+
*,
|
| 253 |
+
scheme: bytes | str = b"",
|
| 254 |
+
host: bytes | str = b"",
|
| 255 |
+
port: int | None = None,
|
| 256 |
+
target: bytes | str = b"",
|
| 257 |
+
) -> None:
|
| 258 |
+
"""
|
| 259 |
+
Parameters:
|
| 260 |
+
url: The complete URL as a string or bytes.
|
| 261 |
+
scheme: The URL scheme as a string or bytes.
|
| 262 |
+
Typically either `"http"` or `"https"`.
|
| 263 |
+
host: The URL host as a string or bytes. Such as `"www.example.com"`.
|
| 264 |
+
port: The port to connect to. Either an integer or `None`.
|
| 265 |
+
target: The target of the HTTP request. Such as `"/items?search=red"`.
|
| 266 |
+
"""
|
| 267 |
+
if url:
|
| 268 |
+
parsed = urllib.parse.urlparse(enforce_bytes(url, name="url"))
|
| 269 |
+
self.scheme = parsed.scheme
|
| 270 |
+
self.host = parsed.hostname or b""
|
| 271 |
+
self.port = parsed.port
|
| 272 |
+
self.target = (parsed.path or b"/") + (
|
| 273 |
+
b"?" + parsed.query if parsed.query else b""
|
| 274 |
+
)
|
| 275 |
+
else:
|
| 276 |
+
self.scheme = enforce_bytes(scheme, name="scheme")
|
| 277 |
+
self.host = enforce_bytes(host, name="host")
|
| 278 |
+
self.port = port
|
| 279 |
+
self.target = enforce_bytes(target, name="target")
|
| 280 |
+
|
| 281 |
+
@property
|
| 282 |
+
def origin(self) -> Origin:
|
| 283 |
+
default_port = {
|
| 284 |
+
b"http": 80,
|
| 285 |
+
b"https": 443,
|
| 286 |
+
b"ws": 80,
|
| 287 |
+
b"wss": 443,
|
| 288 |
+
b"socks5": 1080,
|
| 289 |
+
b"socks5h": 1080,
|
| 290 |
+
}[self.scheme]
|
| 291 |
+
return Origin(
|
| 292 |
+
scheme=self.scheme, host=self.host, port=self.port or default_port
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
def __eq__(self, other: typing.Any) -> bool:
|
| 296 |
+
return (
|
| 297 |
+
isinstance(other, URL)
|
| 298 |
+
and other.scheme == self.scheme
|
| 299 |
+
and other.host == self.host
|
| 300 |
+
and other.port == self.port
|
| 301 |
+
and other.target == self.target
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
def __bytes__(self) -> bytes:
|
| 305 |
+
if self.port is None:
|
| 306 |
+
return b"%b://%b%b" % (self.scheme, self.host, self.target)
|
| 307 |
+
return b"%b://%b:%d%b" % (self.scheme, self.host, self.port, self.target)
|
| 308 |
+
|
| 309 |
+
def __repr__(self) -> str:
|
| 310 |
+
return (
|
| 311 |
+
f"{self.__class__.__name__}(scheme={self.scheme!r}, "
|
| 312 |
+
f"host={self.host!r}, port={self.port!r}, target={self.target!r})"
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class Request:
|
| 317 |
+
"""
|
| 318 |
+
An HTTP request.
|
| 319 |
+
"""
|
| 320 |
+
|
| 321 |
+
def __init__(
|
| 322 |
+
self,
|
| 323 |
+
method: bytes | str,
|
| 324 |
+
url: URL | bytes | str,
|
| 325 |
+
*,
|
| 326 |
+
headers: HeaderTypes = None,
|
| 327 |
+
content: bytes
|
| 328 |
+
| typing.Iterable[bytes]
|
| 329 |
+
| typing.AsyncIterable[bytes]
|
| 330 |
+
| None = None,
|
| 331 |
+
extensions: Extensions | None = None,
|
| 332 |
+
) -> None:
|
| 333 |
+
"""
|
| 334 |
+
Parameters:
|
| 335 |
+
method: The HTTP request method, either as a string or bytes.
|
| 336 |
+
For example: `GET`.
|
| 337 |
+
url: The request URL, either as a `URL` instance, or as a string or bytes.
|
| 338 |
+
For example: `"https://www.example.com".`
|
| 339 |
+
headers: The HTTP request headers.
|
| 340 |
+
content: The content of the request body.
|
| 341 |
+
extensions: A dictionary of optional extra information included on
|
| 342 |
+
the request. Possible keys include `"timeout"`, and `"trace"`.
|
| 343 |
+
"""
|
| 344 |
+
self.method: bytes = enforce_bytes(method, name="method")
|
| 345 |
+
self.url: URL = enforce_url(url, name="url")
|
| 346 |
+
self.headers: list[tuple[bytes, bytes]] = enforce_headers(
|
| 347 |
+
headers, name="headers"
|
| 348 |
+
)
|
| 349 |
+
self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = (
|
| 350 |
+
enforce_stream(content, name="content")
|
| 351 |
+
)
|
| 352 |
+
self.extensions = {} if extensions is None else extensions
|
| 353 |
+
|
| 354 |
+
if "target" in self.extensions:
|
| 355 |
+
self.url = URL(
|
| 356 |
+
scheme=self.url.scheme,
|
| 357 |
+
host=self.url.host,
|
| 358 |
+
port=self.url.port,
|
| 359 |
+
target=self.extensions["target"],
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
def __repr__(self) -> str:
|
| 363 |
+
return f"<{self.__class__.__name__} [{self.method!r}]>"
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class Response:
|
| 367 |
+
"""
|
| 368 |
+
An HTTP response.
|
| 369 |
+
"""
|
| 370 |
+
|
| 371 |
+
def __init__(
|
| 372 |
+
self,
|
| 373 |
+
status: int,
|
| 374 |
+
*,
|
| 375 |
+
headers: HeaderTypes = None,
|
| 376 |
+
content: bytes
|
| 377 |
+
| typing.Iterable[bytes]
|
| 378 |
+
| typing.AsyncIterable[bytes]
|
| 379 |
+
| None = None,
|
| 380 |
+
extensions: Extensions | None = None,
|
| 381 |
+
) -> None:
|
| 382 |
+
"""
|
| 383 |
+
Parameters:
|
| 384 |
+
status: The HTTP status code of the response. For example `200`.
|
| 385 |
+
headers: The HTTP response headers.
|
| 386 |
+
content: The content of the response body.
|
| 387 |
+
extensions: A dictionary of optional extra information included on
|
| 388 |
+
the responseself.Possible keys include `"http_version"`,
|
| 389 |
+
`"reason_phrase"`, and `"network_stream"`.
|
| 390 |
+
"""
|
| 391 |
+
self.status: int = status
|
| 392 |
+
self.headers: list[tuple[bytes, bytes]] = enforce_headers(
|
| 393 |
+
headers, name="headers"
|
| 394 |
+
)
|
| 395 |
+
self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = (
|
| 396 |
+
enforce_stream(content, name="content")
|
| 397 |
+
)
|
| 398 |
+
self.extensions = {} if extensions is None else extensions
|
| 399 |
+
|
| 400 |
+
self._stream_consumed = False
|
| 401 |
+
|
| 402 |
+
@property
|
| 403 |
+
def content(self) -> bytes:
|
| 404 |
+
if not hasattr(self, "_content"):
|
| 405 |
+
if isinstance(self.stream, typing.Iterable):
|
| 406 |
+
raise RuntimeError(
|
| 407 |
+
"Attempted to access 'response.content' on a streaming response. "
|
| 408 |
+
"Call 'response.read()' first."
|
| 409 |
+
)
|
| 410 |
+
else:
|
| 411 |
+
raise RuntimeError(
|
| 412 |
+
"Attempted to access 'response.content' on a streaming response. "
|
| 413 |
+
"Call 'await response.aread()' first."
|
| 414 |
+
)
|
| 415 |
+
return self._content
|
| 416 |
+
|
| 417 |
+
def __repr__(self) -> str:
|
| 418 |
+
return f"<{self.__class__.__name__} [{self.status}]>"
|
| 419 |
+
|
| 420 |
+
# Sync interface...
|
| 421 |
+
|
| 422 |
+
def read(self) -> bytes:
|
| 423 |
+
if not isinstance(self.stream, typing.Iterable): # pragma: nocover
|
| 424 |
+
raise RuntimeError(
|
| 425 |
+
"Attempted to read an asynchronous response using 'response.read()'. "
|
| 426 |
+
"You should use 'await response.aread()' instead."
|
| 427 |
+
)
|
| 428 |
+
if not hasattr(self, "_content"):
|
| 429 |
+
self._content = b"".join([part for part in self.iter_stream()])
|
| 430 |
+
return self._content
|
| 431 |
+
|
| 432 |
+
def iter_stream(self) -> typing.Iterator[bytes]:
|
| 433 |
+
if not isinstance(self.stream, typing.Iterable): # pragma: nocover
|
| 434 |
+
raise RuntimeError(
|
| 435 |
+
"Attempted to stream an asynchronous response using 'for ... in "
|
| 436 |
+
"response.iter_stream()'. "
|
| 437 |
+
"You should use 'async for ... in response.aiter_stream()' instead."
|
| 438 |
+
)
|
| 439 |
+
if self._stream_consumed:
|
| 440 |
+
raise RuntimeError(
|
| 441 |
+
"Attempted to call 'for ... in response.iter_stream()' more than once."
|
| 442 |
+
)
|
| 443 |
+
self._stream_consumed = True
|
| 444 |
+
for chunk in self.stream:
|
| 445 |
+
yield chunk
|
| 446 |
+
|
| 447 |
+
def close(self) -> None:
|
| 448 |
+
if not isinstance(self.stream, typing.Iterable): # pragma: nocover
|
| 449 |
+
raise RuntimeError(
|
| 450 |
+
"Attempted to close an asynchronous response using 'response.close()'. "
|
| 451 |
+
"You should use 'await response.aclose()' instead."
|
| 452 |
+
)
|
| 453 |
+
if hasattr(self.stream, "close"):
|
| 454 |
+
self.stream.close()
|
| 455 |
+
|
| 456 |
+
# Async interface...
|
| 457 |
+
|
| 458 |
+
async def aread(self) -> bytes:
|
| 459 |
+
if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover
|
| 460 |
+
raise RuntimeError(
|
| 461 |
+
"Attempted to read an synchronous response using "
|
| 462 |
+
"'await response.aread()'. "
|
| 463 |
+
"You should use 'response.read()' instead."
|
| 464 |
+
)
|
| 465 |
+
if not hasattr(self, "_content"):
|
| 466 |
+
self._content = b"".join([part async for part in self.aiter_stream()])
|
| 467 |
+
return self._content
|
| 468 |
+
|
| 469 |
+
async def aiter_stream(self) -> typing.AsyncIterator[bytes]:
|
| 470 |
+
if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover
|
| 471 |
+
raise RuntimeError(
|
| 472 |
+
"Attempted to stream an synchronous response using 'async for ... in "
|
| 473 |
+
"response.aiter_stream()'. "
|
| 474 |
+
"You should use 'for ... in response.iter_stream()' instead."
|
| 475 |
+
)
|
| 476 |
+
if self._stream_consumed:
|
| 477 |
+
raise RuntimeError(
|
| 478 |
+
"Attempted to call 'async for ... in response.aiter_stream()' "
|
| 479 |
+
"more than once."
|
| 480 |
+
)
|
| 481 |
+
self._stream_consumed = True
|
| 482 |
+
async for chunk in self.stream:
|
| 483 |
+
yield chunk
|
| 484 |
+
|
| 485 |
+
async def aclose(self) -> None:
|
| 486 |
+
if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover
|
| 487 |
+
raise RuntimeError(
|
| 488 |
+
"Attempted to close a synchronous response using "
|
| 489 |
+
"'await response.aclose()'. "
|
| 490 |
+
"You should use 'response.close()' instead."
|
| 491 |
+
)
|
| 492 |
+
if hasattr(self.stream, "aclose"):
|
| 493 |
+
await self.stream.aclose()
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
class Proxy:
|
| 497 |
+
def __init__(
|
| 498 |
+
self,
|
| 499 |
+
url: URL | bytes | str,
|
| 500 |
+
auth: tuple[bytes | str, bytes | str] | None = None,
|
| 501 |
+
headers: HeadersAsMapping | HeadersAsSequence | None = None,
|
| 502 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 503 |
+
):
|
| 504 |
+
self.url = enforce_url(url, name="url")
|
| 505 |
+
self.headers = enforce_headers(headers, name="headers")
|
| 506 |
+
self.ssl_context = ssl_context
|
| 507 |
+
|
| 508 |
+
if auth is not None:
|
| 509 |
+
username = enforce_bytes(auth[0], name="auth")
|
| 510 |
+
password = enforce_bytes(auth[1], name="auth")
|
| 511 |
+
userpass = username + b":" + password
|
| 512 |
+
authorization = b"Basic " + base64.b64encode(userpass)
|
| 513 |
+
self.auth: tuple[bytes, bytes] | None = (username, password)
|
| 514 |
+
self.headers = [(b"Proxy-Authorization", authorization)] + self.headers
|
| 515 |
+
else:
|
| 516 |
+
self.auth = None
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_ssl.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ssl
|
| 2 |
+
|
| 3 |
+
import certifi
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def default_ssl_context() -> ssl.SSLContext:
|
| 7 |
+
context = ssl.create_default_context()
|
| 8 |
+
context.load_verify_locations(certifi.where())
|
| 9 |
+
return context
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_sync/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .connection import HTTPConnection
|
| 2 |
+
from .connection_pool import ConnectionPool
|
| 3 |
+
from .http11 import HTTP11Connection
|
| 4 |
+
from .http_proxy import HTTPProxy
|
| 5 |
+
from .interfaces import ConnectionInterface
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from .http2 import HTTP2Connection
|
| 9 |
+
except ImportError: # pragma: nocover
|
| 10 |
+
|
| 11 |
+
class HTTP2Connection: # type: ignore
|
| 12 |
+
def __init__(self, *args, **kwargs) -> None: # type: ignore
|
| 13 |
+
raise RuntimeError(
|
| 14 |
+
"Attempted to use http2 support, but the `h2` package is not "
|
| 15 |
+
"installed. Use 'pip install httpcore[http2]'."
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
from .socks_proxy import SOCKSProxy
|
| 21 |
+
except ImportError: # pragma: nocover
|
| 22 |
+
|
| 23 |
+
class SOCKSProxy: # type: ignore
|
| 24 |
+
def __init__(self, *args, **kwargs) -> None: # type: ignore
|
| 25 |
+
raise RuntimeError(
|
| 26 |
+
"Attempted to use SOCKS support, but the `socksio` package is not "
|
| 27 |
+
"installed. Use 'pip install httpcore[socks]'."
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
__all__ = [
|
| 32 |
+
"HTTPConnection",
|
| 33 |
+
"ConnectionPool",
|
| 34 |
+
"HTTPProxy",
|
| 35 |
+
"HTTP11Connection",
|
| 36 |
+
"HTTP2Connection",
|
| 37 |
+
"ConnectionInterface",
|
| 38 |
+
"SOCKSProxy",
|
| 39 |
+
]
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_sync/connection.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import itertools
|
| 4 |
+
import logging
|
| 5 |
+
import ssl
|
| 6 |
+
import types
|
| 7 |
+
import typing
|
| 8 |
+
|
| 9 |
+
from .._backends.sync import SyncBackend
|
| 10 |
+
from .._backends.base import SOCKET_OPTION, NetworkBackend, NetworkStream
|
| 11 |
+
from .._exceptions import ConnectError, ConnectTimeout
|
| 12 |
+
from .._models import Origin, Request, Response
|
| 13 |
+
from .._ssl import default_ssl_context
|
| 14 |
+
from .._synchronization import Lock
|
| 15 |
+
from .._trace import Trace
|
| 16 |
+
from .http11 import HTTP11Connection
|
| 17 |
+
from .interfaces import ConnectionInterface
|
| 18 |
+
|
| 19 |
+
RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger("httpcore.connection")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def exponential_backoff(factor: float) -> typing.Iterator[float]:
|
| 26 |
+
"""
|
| 27 |
+
Generate a geometric sequence that has a ratio of 2 and starts with 0.
|
| 28 |
+
|
| 29 |
+
For example:
|
| 30 |
+
- `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...`
|
| 31 |
+
- `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...`
|
| 32 |
+
"""
|
| 33 |
+
yield 0
|
| 34 |
+
for n in itertools.count():
|
| 35 |
+
yield factor * 2**n
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class HTTPConnection(ConnectionInterface):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
origin: Origin,
|
| 42 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 43 |
+
keepalive_expiry: float | None = None,
|
| 44 |
+
http1: bool = True,
|
| 45 |
+
http2: bool = False,
|
| 46 |
+
retries: int = 0,
|
| 47 |
+
local_address: str | None = None,
|
| 48 |
+
uds: str | None = None,
|
| 49 |
+
network_backend: NetworkBackend | None = None,
|
| 50 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 51 |
+
) -> None:
|
| 52 |
+
self._origin = origin
|
| 53 |
+
self._ssl_context = ssl_context
|
| 54 |
+
self._keepalive_expiry = keepalive_expiry
|
| 55 |
+
self._http1 = http1
|
| 56 |
+
self._http2 = http2
|
| 57 |
+
self._retries = retries
|
| 58 |
+
self._local_address = local_address
|
| 59 |
+
self._uds = uds
|
| 60 |
+
|
| 61 |
+
self._network_backend: NetworkBackend = (
|
| 62 |
+
SyncBackend() if network_backend is None else network_backend
|
| 63 |
+
)
|
| 64 |
+
self._connection: ConnectionInterface | None = None
|
| 65 |
+
self._connect_failed: bool = False
|
| 66 |
+
self._request_lock = Lock()
|
| 67 |
+
self._socket_options = socket_options
|
| 68 |
+
|
| 69 |
+
def handle_request(self, request: Request) -> Response:
|
| 70 |
+
if not self.can_handle_request(request.url.origin):
|
| 71 |
+
raise RuntimeError(
|
| 72 |
+
f"Attempted to send request to {request.url.origin} on connection to {self._origin}"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
with self._request_lock:
|
| 77 |
+
if self._connection is None:
|
| 78 |
+
stream = self._connect(request)
|
| 79 |
+
|
| 80 |
+
ssl_object = stream.get_extra_info("ssl_object")
|
| 81 |
+
http2_negotiated = (
|
| 82 |
+
ssl_object is not None
|
| 83 |
+
and ssl_object.selected_alpn_protocol() == "h2"
|
| 84 |
+
)
|
| 85 |
+
if http2_negotiated or (self._http2 and not self._http1):
|
| 86 |
+
from .http2 import HTTP2Connection
|
| 87 |
+
|
| 88 |
+
self._connection = HTTP2Connection(
|
| 89 |
+
origin=self._origin,
|
| 90 |
+
stream=stream,
|
| 91 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 92 |
+
)
|
| 93 |
+
else:
|
| 94 |
+
self._connection = HTTP11Connection(
|
| 95 |
+
origin=self._origin,
|
| 96 |
+
stream=stream,
|
| 97 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 98 |
+
)
|
| 99 |
+
except BaseException as exc:
|
| 100 |
+
self._connect_failed = True
|
| 101 |
+
raise exc
|
| 102 |
+
|
| 103 |
+
return self._connection.handle_request(request)
|
| 104 |
+
|
| 105 |
+
def _connect(self, request: Request) -> NetworkStream:
|
| 106 |
+
timeouts = request.extensions.get("timeout", {})
|
| 107 |
+
sni_hostname = request.extensions.get("sni_hostname", None)
|
| 108 |
+
timeout = timeouts.get("connect", None)
|
| 109 |
+
|
| 110 |
+
retries_left = self._retries
|
| 111 |
+
delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR)
|
| 112 |
+
|
| 113 |
+
while True:
|
| 114 |
+
try:
|
| 115 |
+
if self._uds is None:
|
| 116 |
+
kwargs = {
|
| 117 |
+
"host": self._origin.host.decode("ascii"),
|
| 118 |
+
"port": self._origin.port,
|
| 119 |
+
"local_address": self._local_address,
|
| 120 |
+
"timeout": timeout,
|
| 121 |
+
"socket_options": self._socket_options,
|
| 122 |
+
}
|
| 123 |
+
with Trace("connect_tcp", logger, request, kwargs) as trace:
|
| 124 |
+
stream = self._network_backend.connect_tcp(**kwargs)
|
| 125 |
+
trace.return_value = stream
|
| 126 |
+
else:
|
| 127 |
+
kwargs = {
|
| 128 |
+
"path": self._uds,
|
| 129 |
+
"timeout": timeout,
|
| 130 |
+
"socket_options": self._socket_options,
|
| 131 |
+
}
|
| 132 |
+
with Trace(
|
| 133 |
+
"connect_unix_socket", logger, request, kwargs
|
| 134 |
+
) as trace:
|
| 135 |
+
stream = self._network_backend.connect_unix_socket(
|
| 136 |
+
**kwargs
|
| 137 |
+
)
|
| 138 |
+
trace.return_value = stream
|
| 139 |
+
|
| 140 |
+
if self._origin.scheme in (b"https", b"wss"):
|
| 141 |
+
ssl_context = (
|
| 142 |
+
default_ssl_context()
|
| 143 |
+
if self._ssl_context is None
|
| 144 |
+
else self._ssl_context
|
| 145 |
+
)
|
| 146 |
+
alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"]
|
| 147 |
+
ssl_context.set_alpn_protocols(alpn_protocols)
|
| 148 |
+
|
| 149 |
+
kwargs = {
|
| 150 |
+
"ssl_context": ssl_context,
|
| 151 |
+
"server_hostname": sni_hostname
|
| 152 |
+
or self._origin.host.decode("ascii"),
|
| 153 |
+
"timeout": timeout,
|
| 154 |
+
}
|
| 155 |
+
with Trace("start_tls", logger, request, kwargs) as trace:
|
| 156 |
+
stream = stream.start_tls(**kwargs)
|
| 157 |
+
trace.return_value = stream
|
| 158 |
+
return stream
|
| 159 |
+
except (ConnectError, ConnectTimeout):
|
| 160 |
+
if retries_left <= 0:
|
| 161 |
+
raise
|
| 162 |
+
retries_left -= 1
|
| 163 |
+
delay = next(delays)
|
| 164 |
+
with Trace("retry", logger, request, kwargs) as trace:
|
| 165 |
+
self._network_backend.sleep(delay)
|
| 166 |
+
|
| 167 |
+
def can_handle_request(self, origin: Origin) -> bool:
|
| 168 |
+
return origin == self._origin
|
| 169 |
+
|
| 170 |
+
def close(self) -> None:
|
| 171 |
+
if self._connection is not None:
|
| 172 |
+
with Trace("close", logger, None, {}):
|
| 173 |
+
self._connection.close()
|
| 174 |
+
|
| 175 |
+
def is_available(self) -> bool:
|
| 176 |
+
if self._connection is None:
|
| 177 |
+
# If HTTP/2 support is enabled, and the resulting connection could
|
| 178 |
+
# end up as HTTP/2 then we should indicate the connection as being
|
| 179 |
+
# available to service multiple requests.
|
| 180 |
+
return (
|
| 181 |
+
self._http2
|
| 182 |
+
and (self._origin.scheme == b"https" or not self._http1)
|
| 183 |
+
and not self._connect_failed
|
| 184 |
+
)
|
| 185 |
+
return self._connection.is_available()
|
| 186 |
+
|
| 187 |
+
def has_expired(self) -> bool:
|
| 188 |
+
if self._connection is None:
|
| 189 |
+
return self._connect_failed
|
| 190 |
+
return self._connection.has_expired()
|
| 191 |
+
|
| 192 |
+
def is_idle(self) -> bool:
|
| 193 |
+
if self._connection is None:
|
| 194 |
+
return self._connect_failed
|
| 195 |
+
return self._connection.is_idle()
|
| 196 |
+
|
| 197 |
+
def is_closed(self) -> bool:
|
| 198 |
+
if self._connection is None:
|
| 199 |
+
return self._connect_failed
|
| 200 |
+
return self._connection.is_closed()
|
| 201 |
+
|
| 202 |
+
def info(self) -> str:
|
| 203 |
+
if self._connection is None:
|
| 204 |
+
return "CONNECTION FAILED" if self._connect_failed else "CONNECTING"
|
| 205 |
+
return self._connection.info()
|
| 206 |
+
|
| 207 |
+
def __repr__(self) -> str:
|
| 208 |
+
return f"<{self.__class__.__name__} [{self.info()}]>"
|
| 209 |
+
|
| 210 |
+
# These context managers are not used in the standard flow, but are
|
| 211 |
+
# useful for testing or working with connection instances directly.
|
| 212 |
+
|
| 213 |
+
def __enter__(self) -> HTTPConnection:
|
| 214 |
+
return self
|
| 215 |
+
|
| 216 |
+
def __exit__(
|
| 217 |
+
self,
|
| 218 |
+
exc_type: type[BaseException] | None = None,
|
| 219 |
+
exc_value: BaseException | None = None,
|
| 220 |
+
traceback: types.TracebackType | None = None,
|
| 221 |
+
) -> None:
|
| 222 |
+
self.close()
|
.cache/uv/archive-v0/4xX2yDNKqEaCJRp6U2iC4/httpcore/_sync/connection_pool.py
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import ssl
|
| 4 |
+
import sys
|
| 5 |
+
import types
|
| 6 |
+
import typing
|
| 7 |
+
|
| 8 |
+
from .._backends.sync import SyncBackend
|
| 9 |
+
from .._backends.base import SOCKET_OPTION, NetworkBackend
|
| 10 |
+
from .._exceptions import ConnectionNotAvailable, UnsupportedProtocol
|
| 11 |
+
from .._models import Origin, Proxy, Request, Response
|
| 12 |
+
from .._synchronization import Event, ShieldCancellation, ThreadLock
|
| 13 |
+
from .connection import HTTPConnection
|
| 14 |
+
from .interfaces import ConnectionInterface, RequestInterface
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class PoolRequest:
|
| 18 |
+
def __init__(self, request: Request) -> None:
|
| 19 |
+
self.request = request
|
| 20 |
+
self.connection: ConnectionInterface | None = None
|
| 21 |
+
self._connection_acquired = Event()
|
| 22 |
+
|
| 23 |
+
def assign_to_connection(self, connection: ConnectionInterface | None) -> None:
|
| 24 |
+
self.connection = connection
|
| 25 |
+
self._connection_acquired.set()
|
| 26 |
+
|
| 27 |
+
def clear_connection(self) -> None:
|
| 28 |
+
self.connection = None
|
| 29 |
+
self._connection_acquired = Event()
|
| 30 |
+
|
| 31 |
+
def wait_for_connection(
|
| 32 |
+
self, timeout: float | None = None
|
| 33 |
+
) -> ConnectionInterface:
|
| 34 |
+
if self.connection is None:
|
| 35 |
+
self._connection_acquired.wait(timeout=timeout)
|
| 36 |
+
assert self.connection is not None
|
| 37 |
+
return self.connection
|
| 38 |
+
|
| 39 |
+
def is_queued(self) -> bool:
|
| 40 |
+
return self.connection is None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ConnectionPool(RequestInterface):
|
| 44 |
+
"""
|
| 45 |
+
A connection pool for making HTTP requests.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
ssl_context: ssl.SSLContext | None = None,
|
| 51 |
+
proxy: Proxy | None = None,
|
| 52 |
+
max_connections: int | None = 10,
|
| 53 |
+
max_keepalive_connections: int | None = None,
|
| 54 |
+
keepalive_expiry: float | None = None,
|
| 55 |
+
http1: bool = True,
|
| 56 |
+
http2: bool = False,
|
| 57 |
+
retries: int = 0,
|
| 58 |
+
local_address: str | None = None,
|
| 59 |
+
uds: str | None = None,
|
| 60 |
+
network_backend: NetworkBackend | None = None,
|
| 61 |
+
socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
|
| 62 |
+
) -> None:
|
| 63 |
+
"""
|
| 64 |
+
A connection pool for making HTTP requests.
|
| 65 |
+
|
| 66 |
+
Parameters:
|
| 67 |
+
ssl_context: An SSL context to use for verifying connections.
|
| 68 |
+
If not specified, the default `httpcore.default_ssl_context()`
|
| 69 |
+
will be used.
|
| 70 |
+
max_connections: The maximum number of concurrent HTTP connections that
|
| 71 |
+
the pool should allow. Any attempt to send a request on a pool that
|
| 72 |
+
would exceed this amount will block until a connection is available.
|
| 73 |
+
max_keepalive_connections: The maximum number of idle HTTP connections
|
| 74 |
+
that will be maintained in the pool.
|
| 75 |
+
keepalive_expiry: The duration in seconds that an idle HTTP connection
|
| 76 |
+
may be maintained for before being expired from the pool.
|
| 77 |
+
http1: A boolean indicating if HTTP/1.1 requests should be supported
|
| 78 |
+
by the connection pool. Defaults to True.
|
| 79 |
+
http2: A boolean indicating if HTTP/2 requests should be supported by
|
| 80 |
+
the connection pool. Defaults to False.
|
| 81 |
+
retries: The maximum number of retries when trying to establish a
|
| 82 |
+
connection.
|
| 83 |
+
local_address: Local address to connect from. Can also be used to connect
|
| 84 |
+
using a particular address family. Using `local_address="0.0.0.0"`
|
| 85 |
+
will connect using an `AF_INET` address (IPv4), while using
|
| 86 |
+
`local_address="::"` will connect using an `AF_INET6` address (IPv6).
|
| 87 |
+
uds: Path to a Unix Domain Socket to use instead of TCP sockets.
|
| 88 |
+
network_backend: A backend instance to use for handling network I/O.
|
| 89 |
+
socket_options: Socket options that have to be included
|
| 90 |
+
in the TCP socket when the connection was established.
|
| 91 |
+
"""
|
| 92 |
+
self._ssl_context = ssl_context
|
| 93 |
+
self._proxy = proxy
|
| 94 |
+
self._max_connections = (
|
| 95 |
+
sys.maxsize if max_connections is None else max_connections
|
| 96 |
+
)
|
| 97 |
+
self._max_keepalive_connections = (
|
| 98 |
+
sys.maxsize
|
| 99 |
+
if max_keepalive_connections is None
|
| 100 |
+
else max_keepalive_connections
|
| 101 |
+
)
|
| 102 |
+
self._max_keepalive_connections = min(
|
| 103 |
+
self._max_connections, self._max_keepalive_connections
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
self._keepalive_expiry = keepalive_expiry
|
| 107 |
+
self._http1 = http1
|
| 108 |
+
self._http2 = http2
|
| 109 |
+
self._retries = retries
|
| 110 |
+
self._local_address = local_address
|
| 111 |
+
self._uds = uds
|
| 112 |
+
|
| 113 |
+
self._network_backend = (
|
| 114 |
+
SyncBackend() if network_backend is None else network_backend
|
| 115 |
+
)
|
| 116 |
+
self._socket_options = socket_options
|
| 117 |
+
|
| 118 |
+
# The mutable state on a connection pool is the queue of incoming requests,
|
| 119 |
+
# and the set of connections that are servicing those requests.
|
| 120 |
+
self._connections: list[ConnectionInterface] = []
|
| 121 |
+
self._requests: list[PoolRequest] = []
|
| 122 |
+
|
| 123 |
+
# We only mutate the state of the connection pool within an 'optional_thread_lock'
|
| 124 |
+
# context. This holds a threading lock unless we're running in async mode,
|
| 125 |
+
# in which case it is a no-op.
|
| 126 |
+
self._optional_thread_lock = ThreadLock()
|
| 127 |
+
|
| 128 |
+
def create_connection(self, origin: Origin) -> ConnectionInterface:
|
| 129 |
+
if self._proxy is not None:
|
| 130 |
+
if self._proxy.url.scheme in (b"socks5", b"socks5h"):
|
| 131 |
+
from .socks_proxy import Socks5Connection
|
| 132 |
+
|
| 133 |
+
return Socks5Connection(
|
| 134 |
+
proxy_origin=self._proxy.url.origin,
|
| 135 |
+
proxy_auth=self._proxy.auth,
|
| 136 |
+
remote_origin=origin,
|
| 137 |
+
ssl_context=self._ssl_context,
|
| 138 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 139 |
+
http1=self._http1,
|
| 140 |
+
http2=self._http2,
|
| 141 |
+
network_backend=self._network_backend,
|
| 142 |
+
)
|
| 143 |
+
elif origin.scheme == b"http":
|
| 144 |
+
from .http_proxy import ForwardHTTPConnection
|
| 145 |
+
|
| 146 |
+
return ForwardHTTPConnection(
|
| 147 |
+
proxy_origin=self._proxy.url.origin,
|
| 148 |
+
proxy_headers=self._proxy.headers,
|
| 149 |
+
proxy_ssl_context=self._proxy.ssl_context,
|
| 150 |
+
remote_origin=origin,
|
| 151 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 152 |
+
network_backend=self._network_backend,
|
| 153 |
+
)
|
| 154 |
+
from .http_proxy import TunnelHTTPConnection
|
| 155 |
+
|
| 156 |
+
return TunnelHTTPConnection(
|
| 157 |
+
proxy_origin=self._proxy.url.origin,
|
| 158 |
+
proxy_headers=self._proxy.headers,
|
| 159 |
+
proxy_ssl_context=self._proxy.ssl_context,
|
| 160 |
+
remote_origin=origin,
|
| 161 |
+
ssl_context=self._ssl_context,
|
| 162 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 163 |
+
http1=self._http1,
|
| 164 |
+
http2=self._http2,
|
| 165 |
+
network_backend=self._network_backend,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
return HTTPConnection(
|
| 169 |
+
origin=origin,
|
| 170 |
+
ssl_context=self._ssl_context,
|
| 171 |
+
keepalive_expiry=self._keepalive_expiry,
|
| 172 |
+
http1=self._http1,
|
| 173 |
+
http2=self._http2,
|
| 174 |
+
retries=self._retries,
|
| 175 |
+
local_address=self._local_address,
|
| 176 |
+
uds=self._uds,
|
| 177 |
+
network_backend=self._network_backend,
|
| 178 |
+
socket_options=self._socket_options,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
@property
|
| 182 |
+
def connections(self) -> list[ConnectionInterface]:
|
| 183 |
+
"""
|
| 184 |
+
Return a list of the connections currently in the pool.
|
| 185 |
+
|
| 186 |
+
For example:
|
| 187 |
+
|
| 188 |
+
```python
|
| 189 |
+
>>> pool.connections
|
| 190 |
+
[
|
| 191 |
+
<HTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 6]>,
|
| 192 |
+
<HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 9]> ,
|
| 193 |
+
<HTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>,
|
| 194 |
+
]
|
| 195 |
+
```
|
| 196 |
+
"""
|
| 197 |
+
return list(self._connections)
|
| 198 |
+
|
| 199 |
+
def handle_request(self, request: Request) -> Response:
|
| 200 |
+
"""
|
| 201 |
+
Send an HTTP request, and return an HTTP response.
|
| 202 |
+
|
| 203 |
+
This is the core implementation that is called into by `.request()` or `.stream()`.
|
| 204 |
+
"""
|
| 205 |
+
scheme = request.url.scheme.decode()
|
| 206 |
+
if scheme == "":
|
| 207 |
+
raise UnsupportedProtocol(
|
| 208 |
+
"Request URL is missing an 'http://' or 'https://' protocol."
|
| 209 |
+
)
|
| 210 |
+
if scheme not in ("http", "https", "ws", "wss"):
|
| 211 |
+
raise UnsupportedProtocol(
|
| 212 |
+
f"Request URL has an unsupported protocol '{scheme}://'."
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
timeouts = request.extensions.get("timeout", {})
|
| 216 |
+
timeout = timeouts.get("pool", None)
|
| 217 |
+
|
| 218 |
+
with self._optional_thread_lock:
|
| 219 |
+
# Add the incoming request to our request queue.
|
| 220 |
+
pool_request = PoolRequest(request)
|
| 221 |
+
self._requests.append(pool_request)
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
while True:
|
| 225 |
+
with self._optional_thread_lock:
|
| 226 |
+
# Assign incoming requests to available connections,
|
| 227 |
+
# closing or creating new connections as required.
|
| 228 |
+
closing = self._assign_requests_to_connections()
|
| 229 |
+
self._close_connections(closing)
|
| 230 |
+
|
| 231 |
+
# Wait until this request has an assigned connection.
|
| 232 |
+
connection = pool_request.wait_for_connection(timeout=timeout)
|
| 233 |
+
|
| 234 |
+
try:
|
| 235 |
+
# Send the request on the assigned connection.
|
| 236 |
+
response = connection.handle_request(
|
| 237 |
+
pool_request.request
|
| 238 |
+
)
|
| 239 |
+
except ConnectionNotAvailable:
|
| 240 |
+
# In some cases a connection may initially be available to
|
| 241 |
+
# handle a request, but then become unavailable.
|
| 242 |
+
#
|
| 243 |
+
# In this case we clear the connection and try again.
|
| 244 |
+
pool_request.clear_connection()
|
| 245 |
+
else:
|
| 246 |
+
break # pragma: nocover
|
| 247 |
+
|
| 248 |
+
except BaseException as exc:
|
| 249 |
+
with self._optional_thread_lock:
|
| 250 |
+
# For any exception or cancellation we remove the request from
|
| 251 |
+
# the queue, and then re-assign requests to connections.
|
| 252 |
+
self._requests.remove(pool_request)
|
| 253 |
+
closing = self._assign_requests_to_connections()
|
| 254 |
+
|
| 255 |
+
self._close_connections(closing)
|
| 256 |
+
raise exc from None
|
| 257 |
+
|
| 258 |
+
# Return the response. Note that in this case we still have to manage
|
| 259 |
+
# the point at which the response is closed.
|
| 260 |
+
assert isinstance(response.stream, typing.Iterable)
|
| 261 |
+
return Response(
|
| 262 |
+
status=response.status,
|
| 263 |
+
headers=response.headers,
|
| 264 |
+
content=PoolByteStream(
|
| 265 |
+
stream=response.stream, pool_request=pool_request, pool=self
|
| 266 |
+
),
|
| 267 |
+
extensions=response.extensions,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
def _assign_requests_to_connections(self) -> list[ConnectionInterface]:
|
| 271 |
+
"""
|
| 272 |
+
Manage the state of the connection pool, assigning incoming
|
| 273 |
+
requests to connections as available.
|
| 274 |
+
|
| 275 |
+
Called whenever a new request is added or removed from the pool.
|
| 276 |
+
|
| 277 |
+
Any closing connections are returned, allowing the I/O for closing
|
| 278 |
+
those connections to be handled seperately.
|
| 279 |
+
"""
|
| 280 |
+
closing_connections = []
|
| 281 |
+
|
| 282 |
+
# First we handle cleaning up any connections that are closed,
|
| 283 |
+
# have expired their keep-alive, or surplus idle connections.
|
| 284 |
+
for connection in list(self._connections):
|
| 285 |
+
if connection.is_closed():
|
| 286 |
+
# log: "removing closed connection"
|
| 287 |
+
self._connections.remove(connection)
|
| 288 |
+
elif connection.has_expired():
|
| 289 |
+
# log: "closing expired connection"
|
| 290 |
+
self._connections.remove(connection)
|
| 291 |
+
closing_connections.append(connection)
|
| 292 |
+
elif (
|
| 293 |
+
connection.is_idle()
|
| 294 |
+
and len([connection.is_idle() for connection in self._connections])
|
| 295 |
+
> self._max_keepalive_connections
|
| 296 |
+
):
|
| 297 |
+
# log: "closing idle connection"
|
| 298 |
+
self._connections.remove(connection)
|
| 299 |
+
closing_connections.append(connection)
|
| 300 |
+
|
| 301 |
+
# Assign queued requests to connections.
|
| 302 |
+
queued_requests = [request for request in self._requests if request.is_queued()]
|
| 303 |
+
for pool_request in queued_requests:
|
| 304 |
+
origin = pool_request.request.url.origin
|
| 305 |
+
available_connections = [
|
| 306 |
+
connection
|
| 307 |
+
for connection in self._connections
|
| 308 |
+
if connection.can_handle_request(origin) and connection.is_available()
|
| 309 |
+
]
|
| 310 |
+
idle_connections = [
|
| 311 |
+
connection for connection in self._connections if connection.is_idle()
|
| 312 |
+
]
|
| 313 |
+
|
| 314 |
+
# There are three cases for how we may be able to handle the request:
|
| 315 |
+
#
|
| 316 |
+
# 1. There is an existing connection that can handle the request.
|
| 317 |
+
# 2. We can create a new connection to handle the request.
|
| 318 |
+
# 3. We can close an idle connection and then create a new connection
|
| 319 |
+
# to handle the request.
|
| 320 |
+
if available_connections:
|
| 321 |
+
# log: "reusing existing connection"
|
| 322 |
+
connection = available_connections[0]
|
| 323 |
+
pool_request.assign_to_connection(connection)
|
| 324 |
+
elif len(self._connections) < self._max_connections:
|
| 325 |
+
# log: "creating new connection"
|
| 326 |
+
connection = self.create_connection(origin)
|
| 327 |
+
self._connections.append(connection)
|
| 328 |
+
pool_request.assign_to_connection(connection)
|
| 329 |
+
elif idle_connections:
|
| 330 |
+
# log: "closing idle connection"
|
| 331 |
+
connection = idle_connections[0]
|
| 332 |
+
self._connections.remove(connection)
|
| 333 |
+
closing_connections.append(connection)
|
| 334 |
+
# log: "creating new connection"
|
| 335 |
+
connection = self.create_connection(origin)
|
| 336 |
+
self._connections.append(connection)
|
| 337 |
+
pool_request.assign_to_connection(connection)
|
| 338 |
+
|
| 339 |
+
return closing_connections
|
| 340 |
+
|
| 341 |
+
def _close_connections(self, closing: list[ConnectionInterface]) -> None:
|
| 342 |
+
# Close connections which have been removed from the pool.
|
| 343 |
+
with ShieldCancellation():
|
| 344 |
+
for connection in closing:
|
| 345 |
+
connection.close()
|
| 346 |
+
|
| 347 |
+
def close(self) -> None:
|
| 348 |
+
# Explicitly close the connection pool.
|
| 349 |
+
# Clears all existing requests and connections.
|
| 350 |
+
with self._optional_thread_lock:
|
| 351 |
+
closing_connections = list(self._connections)
|
| 352 |
+
self._connections = []
|
| 353 |
+
self._close_connections(closing_connections)
|
| 354 |
+
|
| 355 |
+
def __enter__(self) -> ConnectionPool:
|
| 356 |
+
return self
|
| 357 |
+
|
| 358 |
+
def __exit__(
|
| 359 |
+
self,
|
| 360 |
+
exc_type: type[BaseException] | None = None,
|
| 361 |
+
exc_value: BaseException | None = None,
|
| 362 |
+
traceback: types.TracebackType | None = None,
|
| 363 |
+
) -> None:
|
| 364 |
+
self.close()
|
| 365 |
+
|
| 366 |
+
def __repr__(self) -> str:
|
| 367 |
+
class_name = self.__class__.__name__
|
| 368 |
+
with self._optional_thread_lock:
|
| 369 |
+
request_is_queued = [request.is_queued() for request in self._requests]
|
| 370 |
+
connection_is_idle = [
|
| 371 |
+
connection.is_idle() for connection in self._connections
|
| 372 |
+
]
|
| 373 |
+
|
| 374 |
+
num_active_requests = request_is_queued.count(False)
|
| 375 |
+
num_queued_requests = request_is_queued.count(True)
|
| 376 |
+
num_active_connections = connection_is_idle.count(False)
|
| 377 |
+
num_idle_connections = connection_is_idle.count(True)
|
| 378 |
+
|
| 379 |
+
requests_info = (
|
| 380 |
+
f"Requests: {num_active_requests} active, {num_queued_requests} queued"
|
| 381 |
+
)
|
| 382 |
+
connection_info = (
|
| 383 |
+
f"Connections: {num_active_connections} active, {num_idle_connections} idle"
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
return f"<{class_name} [{requests_info} | {connection_info}]>"
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class PoolByteStream:
|
| 390 |
+
def __init__(
|
| 391 |
+
self,
|
| 392 |
+
stream: typing.Iterable[bytes],
|
| 393 |
+
pool_request: PoolRequest,
|
| 394 |
+
pool: ConnectionPool,
|
| 395 |
+
) -> None:
|
| 396 |
+
self._stream = stream
|
| 397 |
+
self._pool_request = pool_request
|
| 398 |
+
self._pool = pool
|
| 399 |
+
self._closed = False
|
| 400 |
+
|
| 401 |
+
def __iter__(self) -> typing.Iterator[bytes]:
|
| 402 |
+
try:
|
| 403 |
+
for part in self._stream:
|
| 404 |
+
yield part
|
| 405 |
+
except BaseException as exc:
|
| 406 |
+
self.close()
|
| 407 |
+
raise exc from None
|
| 408 |
+
|
| 409 |
+
def close(self) -> None:
|
| 410 |
+
if not self._closed:
|
| 411 |
+
self._closed = True
|
| 412 |
+
with ShieldCancellation():
|
| 413 |
+
if hasattr(self._stream, "close"):
|
| 414 |
+
self._stream.close()
|
| 415 |
+
|
| 416 |
+
with self._pool._optional_thread_lock:
|
| 417 |
+
self._pool._requests.remove(self._pool_request)
|
| 418 |
+
closing = self._pool._assign_requests_to_connections()
|
| 419 |
+
|
| 420 |
+
self._pool._close_connections(closing)
|